<template>
  <div>
    <a-modal
      :title="title"
      :visible="value"
      :width="width"
      :destroyOnClose="true"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p-grid-form
        ref="formTarget"
        class="mb-10"
        :items="gridItems"
        :span="colNum"
        :label-col="{ span: 8 }"
      >
        <template v-for="item in formSlotCol" :slot="item" slot-scope="text, record">
          <slot :name="item" :text="text" :record="record" />
        </template>
      </p-grid-form>
      <slot name="bottomComponets" />
    </a-modal>
  </div>
</template>

<script>
// 定义一个深拷贝函数  接收目标target参数
const deepClone = function(target) {
  // 定义一个变量
  let result
  // 如果当前需要深拷贝的是一个对象的话
  if (typeof target === 'object') {
    // 如果是一个数组的话
    if (Array.isArray(target)) {
      result = [] // 将result赋值为一个数组，并且执行遍历
      for (let i in target) {
        // 递归克隆数组中的每一项
        result.push(deepClone(target[i]))
      }
      // 判断如果当前的值是null的话；直接赋值为null
    } else if (target === null) {
      result = null
      // 判断如果当前的值是一个RegExp对象的话，直接赋值
    } else if (target.constructor === RegExp) {
      result = target
    } else {
      // 否则是普通对象，直接for in循环，递归赋值对象的所有值
      result = {}
      for (let i in target) {
        result[i] = deepClone(target[i])
      }
    }
    // 如果不是对象的话，就是基本数据类型，那么直接赋值
  } else {
    result = target
  }
  // 返回最终结果
  return result
}
export default {
  name: 'PFormDialog',
  components: {},
  props: {
    value: {
      type: Boolean,
      default: false
    },
    setFormItems: {
      type: Array,
      default() {
        return []
      }
    },
    //表单数据
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    title: {
      type: String,
      default: ''
    },
    colNum: {
      type: Number,
      default: 8
    },
    width: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: Number | String,
      default: 1000
    },
    //输入框禁用
    disabledArray: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: Array | Boolean,
      default() {
        return []
      }
    },
    // eslint-disable-next-line vue/require-default-prop
    funArray: {
      type: Function
    }
  },
  data() {
    return {
      confirmLoading: false,
      formSlotCol: [],
      gridItems: []
    }
  },
  computed: {},
  watch: {
    setFormItems: {
      handler(val) {
        let _this = this
        this.formSlotCol = val.reduce((prew, item) => {
          if (item.scopedSlots) {
            prew.push(item.scopedSlots.customRender)
          }
          return prew
        }, [])
        this.gridItems = deepClone(val)
        //回调事件
        this.gridItems.forEach((item, i) => {
          let name = item.name
          if (item.type == 'searchModal' || (item.type == 'select' && item.tableConfig)) {
            // item.tableConfig.remoteBefore = function (event, remoteParams) {
            //   // console.log(remoteParams,'remoteParamsremoteParamsremoteParams')
            //   _this.remoteBefore(event, remoteParams, name)
            // }
          }
          if (item.type !== 'searchModal') {
            item.on = {
              change: function(event, form) {
                let value = ''
                if (item.type == 'select') {
                  value = event
                } else if (item.type == 'textarea') {
                  value = event
                } else if (item.type == 'input') {
                  value = event.target.value
                } else if (item.type == 'switch') {
                  value = event
                } else if (item.type == 'check') {
                  value = event.target.checked
                }
                // console.log(event, 'eventevent')
                _this.formChange(event, value, form, name)
              }
            }
          }
        })
        this.gridItems = [...this.gridItems]
      },
      immediate: true,
      deep: true
    },
    formData: {
      handler(val) {
        this.$nextTick(() => {
          if (JSON.stringify(val) == '{}') {
            this.$refs.formTarget.form.resetFields()
          } else {
            this.$refs.formTarget.form.setFieldsValue(val)
          }
        })
      }
    },
    disabledArray: {
      handler(val) {
        this.$nextTick(() => {
          // if (!this.value) {
          //   return
          // }
          if (!val) {
            this.$refs.formTarget.form.disableItem()
          } else {
            this.$refs.formTarget.form.enableItem()
            this.$refs.formTarget.form.disableItem(val)
          }
        })
      }
      // immediate: true,
    }
  },
  created() {},
  methods: {
    handleOk() {
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (!error) {
          if (this.funArray) {
            this.confirmLoading = true
            this.verificationFun(this.funArray, values).then(res => {
              this.confirmLoading = false
              this.$emit('handleOk', error, values, this.title, res)
            })
          } else {
            this.$emit('handleOk', error, values, this.title)
          }
        }
      })
    },
    verificationFun(funArray, values, callback) {
      return new Promise(async (resolve, reject) => {
        const res = await funArray(values)
        if (res) {
          resolve(res)
        } else {
          resolve(false)
        }
      })
    },
    remoteBefore(event, remoteParams, name) {
      console.log(remoteParams, 'remoteBeforeFM')
      this.$emit('remoteBeforeFM', event, remoteParams, name)
    },
    handleCancel() {
      this.$emit('handleCancel')
    },
    formChange(event, value, rowData, form, name) {
      this.$emit('inputChange', event, value, rowData, form, name)
    }
  }
}
</script>

<style></style>
