<script>
import formBuilder from '@/utils/formBuilder'
import moment from "moment/moment";
import MobileMultipleSelect from "@/components/MobileMultipleSelect/index.vue";
import {deepCopy} from "@/utils";
import {PopupManager} from "element-ui/lib/utils/popup";
import request from '@/utils/request'
import {getToken} from '@/utils/auth'
export default {
  components: {
    MobileMultipleSelect
  },
  props: {
    config: {
      type: Object
    },
    isFirstNode: {
      type: Boolean,
      default: true
    },
    readable: {
      type: Array,
      default: () => [],
      required: true
    },
    writeable: {
      type: Array,
      default: () => [],
      required: true
    },
    originalForm: {
      type: Object,
      default: () => ({}),
      required: true
    },
    subForm: {
      type: Map,
      default: () => new Map()
    },
    device: {
      type: String,
      default: 'desktop',
      required: true
    },
    fields: {
      type: Array,
      default: () => [],
      required: true
    },
    scriptContent: String,
    rules: {
      type: Object,
      default: () => ({}),
    },
    subRules: {
      type: Object,
      default: () => ({}),
    },
    logs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isShowModal: false,
      modalRender: () => {},
      zIndex: PopupManager.nextZIndex(),

      jointlySignLog: [], // 所有会签log记录
      form: {},
      file: {
        ggg: []
      },
      flows: {},
      showControl: {},
      vanCalendarOption: {
        isShow: false,
        forFormName: "",
        originalObj: ""
      },
      vanTimePickerOption: {
        isShow: false,
        forFormName: "",
        originalObj: ""
      },
      vanPopupOption: {
        isShow: false,
        forFormName: "",
        columns: [],
        originalObj: ""
      },
      multipleSelectOption: {
        isShow: false,
        forFormName: "",
        columns: [],
        originalObj: "",
        multipleLimit: 50,
        options: {
          label: 'name',
          value: 'id'
        }
      }
    }
  },
  methods: {
    request,
    getToken,
    async validate() {
      const $vanForm = this.$refs['vanForm']
      if ($vanForm) {
        const res = await $vanForm.validate()
      }
      let subFormName = this.fields.filter(i => i.type === 'relation').map(i => i.name)
      for (let i = 0;i < subFormName.length;i++) {
        const $subVanForm = this.$refs[`subVanForm-${i}`]
        if ($subVanForm) {
          await $subVanForm.validate()
        }
      }
    },
  },
  computed: {},
  watch: {
    info(newVal) {
      let keys = newVal.map(i => i.name)
      keys.forEach(key => {
        this.form[key] = ''
      })
    },
    originalForm(newVal) {
      this.form = deepCopy(newVal)
    },
    scriptContent(newVal) {
      if(newVal) {
        try {
          new Function(newVal).bind(this)()
        } catch (err) {
          console.error(err)
        }
      }
    },
    isShowModal(newVal) {
      if(newVal) {
        this.zIndex = PopupManager.nextZIndex()
      }
    },
    logs: {
      handler: function (newVal) {
        if (newVal && newVal instanceof Array && newVal.length > 0) {
          this.jointlySignLog = newVal.filter(log => {
            try {
              JSON.parse(log.data)
              return log.is_jointly_sign && /custom_field_id/g.test(log.data)
            } catch (e) {
              return false
            }
          })
        } else {
          this.jointlySignLog = []
        }
      },
      immediate: true
    }
  },
  render(h) {
    const authFields = this.fields.map(field => ({
      ...field,
      _readable: this.readable.indexOf(field.id) !== -1,
      _writeable: this.writeable.indexOf(field.id) !== -1
    }))
    const subFields = Array.from(this.subForm).map(i => i[1]?.customModel?.fields).filter(i => i).flat()
    return h('div',[
      h('van-form',{
        ref: 'vanForm',
        props: {
          'validate-first': true,
          'scroll-to-error': true
        }
      },authFields.map(field => formBuilder.bind(this)(this.device, field, h))),
      //calendar
      (authFields.findIndex(i => i.type === 'date') !== -1 || subFields.findIndex(i => i.type === 'date')) ?
        h('van-calendar',{
          ref: `vanCalendar`,
          props: {
            position: 'bottom',
            value: this.vanCalendarOption.isShow,
            'min-date': this.$moment().subtract('years',10).toDate(),
            'max-date': this.$moment().add('years',10).toDate(),
          },
          on: {
            input: e => {
              this.$set(this.vanCalendarOption,'isShow',e)
              this.$set(this.vanCalendarOption,'isShow',false)
            },
            confirm: date => {
              if(typeof this.vanCalendarOption.originalObj === 'object') {
                this.$set(this.vanCalendarOption.originalObj,this.vanCalendarOption.forFormName,moment(date).format('YYYY-MM-DD'))
              } else {
                this.$set(this.form,this.vanCalendarOption.forFormName,moment(date).format('YYYY-MM-DD'))
              }
              this.$set(this.vanCalendarOption,'isShow',false)
            }
          }
        }) : '',
      //datetimepicker
      (authFields.findIndex(i => i.type === 'datetime') !== -1 || subFields.findIndex(i => i.type === 'datetime') !== -1) ?
        h('van-popup',{
          props: {
            value: this.vanTimePickerOption.isShow,
            position: 'bottom',
          },
          on: {
            input: e => {
              this.$set(this.vanTimePickerOption,'isShow',e)
            },
          }
        },[
          h('van-datetime-picker',{
            props: {
              type: 'datetime',
              title: '选择时间'
            },
            on: {
              confirm: time => {
                if(typeof this.vanTimePickerOption.originalObj === 'object') {
                  this.$set(this.vanTimePickerOption.originalObj,this.vanTimePickerOption.forFormName,moment(time).format('YYYY-MM-DD HH:mm:ss'))
                } else {
                  this.$set(this.form,this.vanTimePickerOption.forFormName,moment(time).format('YYYY-MM-DD HH:mm:ss'))
                }
                this.$set(this.vanTimePickerOption,'isShow',false)
              },
              cancel: _ => {
                this.$set(this.vanTimePickerOption,'isShow',false)
              }
            }
          })
        ]) : '',
      //popup
      (authFields.findIndex(i => i.type === 'select') !== -1 || subFields.findIndex(i => i.type === 'select') !== -1) ?
        h('van-popup',{
          props: {
            value: this.vanPopupOption.isShow,
            position: 'bottom',
          },
          on: {
            input: e => {
              this.$set(this.vanPopupOption,'isShow',e)
            },
          }
        },[
          h('van-picker',{
            props: {
              'show-toolbar': true,
              columns: this.vanPopupOption.columns,
              'value-key': typeof this.vanPopupOption.columns[0] === 'object' ? 'name' : 'yext'
            },
            on: {
              confirm: value => {
                if(typeof this.vanPopupOption.originalObj === 'object') {
                  this.$set(this.vanPopupOption.originalObj,this.vanPopupOption.forFormName,typeof value === 'object' ? value['id'] : value)
                } else {
                  this.$set(this.form,this.vanPopupOption.forFormName,typeof value === 'object' ? value['id'] : value)
                }
                this.$set(this.vanPopupOption,'isShow',false)
              },
              cancel: _ => {
                this.$set(this.vanPopupOption,'isShow',false)
              }
            }
          })
        ]) : '',
      // 多选
      (authFields.findIndex(i => ['relation-flow','choice','choices'].indexOf(i.type) !== -1) !== -1 || subFields.findIndex(i => ['relation-flow','choice','choices'].indexOf(i.type) !== -1) !== -1) ?
        h('van-popup',{
          props: {
            value: this.multipleSelectOption.isShow,
            position: 'bottom',
          },
          on: {
            input: e => {
              this.$set(this.multipleSelectOption,'isShow',e)
            },
          }
        },[
          h(MobileMultipleSelect,{
            props: {
              selectDataOpts: this.multipleSelectOption.columns,
              multipleLimit: this.multipleSelectOption.multipleLimit,
              options: this.multipleSelectOption.options,
              outputType: this.multipleSelectOption.outputType,
            },
            on: {
              confirm: value => {
                if(typeof this.multipleSelectOption.originalObj === 'object') {
                  console.log(this.multipleSelectOption.originalObj)
                  this.$set(this.multipleSelectOption.originalObj,this.multipleSelectOption.forFormName,value)
                } else {
                  this.$set(this.form,this.multipleSelectOption.forFormName,value)
                }
                this.$set(this.multipleSelectOption,'isShow',false)
              },
              cancel: _ => {
                this.$set(this.multipleSelectOption,'isShow',false)
              }
            }
          })
        ]) : '',

      // 用于编写脚本中弹窗
      h('vxe-modal',{
        props: {
          zIndex: this.zIndex,
          value: this.isShowModal,
          fullscreen: true,
          transfer: true
        },
        on: {
          input: e => {
            this.isShowModal = e
          }
        }
      }, [
        this.modalRender.bind(this)(h)
      ])
    ])
  }
}
</script>

<style scoped lang="scss">
</style>
