<template>
  <div>
    <p-grid-form
      class="mb-10"
      ref="formTarget"
      :items="gridItems"
      :span="colunmRow"
      :labelCol="{ span: 8 }"
      @submit="
        ($event, form) => {
          handleSubmit($event, form, 'formTarget')
        }
      "
    />
  </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: '',
  components: {},
  props: {
    //配置项
    setFormItems: {
      type: Array,
      default() {
        return []
      }
    },
    //表单数据
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    //每行放置数量
    searchColNum: {
      type: Number,
      default: 3
    },
    isQuery: {
      type: Boolean,
      default: true
    },
    //输入框禁用
    disabledArray: {
      type: Array | Boolean,
      default() {
        return []
      }
    },
    hiddenInitial: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      gridItems: [],
      isShow: false, //隐藏状态
      colunmRow: 0,
      hiddenItem: []
    }
  },
  created() {},
  mounted() {},
  computed: {},
  watch: {
    hiddenInitial: {
      handler(val) {
        this.isShow = !val
      },
      immediate: true
    },
    disabledArray: {
      handler(val) {
        this.$nextTick(() => {
          if(!val) {
            this.$refs.formTarget.form.disableItem()
          } else {
            this.$refs.formTarget.form.enableItem()
            this.$refs.formTarget.form.disableItem(val)
          }
        });
      },
      immediate: true,
    },
    setFormItems: {
      handler(val) {
        //默认隐藏行
        let _this = this
        this.colunmRow = 24 / this.searchColNum
        let columns = []
        val.forEach(item => {
          if (!item.hidden) {
            columns.push(item)
          }
        })
        let buttonArrAy = []
        let columnsLength = columns.length - this.searchColNum >= 0 ? columns.length - this.searchColNum : 0
        if (columnsLength > 0) {
          buttonArrAy = [
            {
              span: 24,
              type: 'buttonGroup',
              style: { textAlign: 'right' },
              options: [
                {
                  value: '查询',
                  icon: 'search',
                  btnType: 'primary',
                  style: 'margin-right:10px',
                  htmlType: 'submit'
                },
                {
                  value: '重置',
                  style: 'margin-right:10px',
                  icon: 'redo',
                  on: {
                    click: () => {
                      this.resetFields()
                    }
                  }
                },
                {
                  value: this.hiddenInitial ? '显示' : '隐藏',
                  on: {
                    click: () => {
                      this.moreClick()
                    }
                  }
                }
              ]
            }
          ]
        } else {
          buttonArrAy = [
            {
              span: 24,
              type: 'buttonGroup',
              style: { textAlign: 'right' },
              options: [
                {
                  value: '查询',
                  icon: 'search',
                  btnType: 'primary',
                  style: 'margin-right:10px',
                  htmlType: 'submit'
                },
                {
                  value: '重置',
                  style: 'margin-right:10px',
                  icon: 'redo',
                  on: {
                    click: () => {
                      this.resetFields()
                    }
                  }
                }
              ]
            }
          ]
        }
        let num = this.searchColNum - 1
        this.hiddenItem = val
          .filter(item => {
            return !item.hidden
          })
          .filter((item, i) => {
            return i > num
          })
        this.gridItems =  deepClone([
            ...val.filter(item => {
              return !item.hidden
            }),
            ...val.filter(item => {
              return item.hidden
            })
          ])
        //是否加入查询按键
        if (this.isQuery) {
           //初始状态是否隐藏
          if(this.hiddenInitial) {
            for (let i = this.gridItems.length - 1; i >= 0; i--) {
              if (num < i) {
                this.$nextTick(() => {
                  this.$refs.formTarget.form.hiddenItem(this.gridItems[i].name)
                })
              }
            }
          }
        } else {
          buttonArrAy = []
        }

        //回调事件
        this.gridItems.forEach((item, i) => {
          let name = item.name
          if (item.type == 'searchModal' || item.type == 'select' && item.tableConfig) {
            item.tableConfig.remoteBefore = function(event, remoteParams) {
              _this.remoteBefore(event, remoteParams, name)
            }
          }
          if(item.type !== 'searchModal') {
            item.on = {
              change: function(event, form) {
                let value = ''
                if(item.type == 'select') {
                  value = event
                } else {
                  value = event.target.value
                }
                _this.searchModalChange(event, value, form, name)
              }
            }
          }
          
        })
        this.gridItems = [...this.gridItems, ...buttonArrAy]
      },
      immediate: true,
      deep: true
    },
    isShow: {
      handler(val) {
        if (!this.isQuery) {
          return
        }
        let lable = val ? '隐藏' : '显示'
        this.gridItems.forEach(item => {
          if (item.type == 'buttonGroup') {
            item.options[2].value = lable
          }
        })
        this.hiddenItem.forEach(item => {
          for (let i = this.gridItems.length - 1; i >= 0; i--) {
            if (item.name == this.gridItems[i].name) {
              this.$nextTick(() => {
                if (val) {
                  this.$refs.formTarget.form.unhiddenItem(this.gridItems[i].name)
                } else {
                  this.$refs.formTarget.form.hiddenItem(this.gridItems[i].name)
                }
              })
            }
          }
        })
      },
      deep: true
    },
    formData: {
      handler(val) {
        this.$nextTick(() => {
          this.$refs.formTarget.form.setFieldsValue(val)
        })
      }
    }
  },
  methods: {
    searchModalChange(event, value, rowData, form, name) {
      this.$emit('formChange', event, value, rowData, form, name)
    },
    remoteBefore(event, remoteParams, name) {
      console.log(remoteParams,'remoteBeforeFM')
      this.$emit('remoteBeforeFM', event, remoteParams, name)
    },
    resetFields() {
      this.$refs.formTarget.form.resetFields()
    },
    moreClick() {
      this.isShow = !this.isShow
    },
    handleSubmit(event) {
      event.preventDefault()
      this.$refs.formTarget.form.validateFields((error, values) => {
        if (!error) {
          this.$emit('handleSubmit', error, values)
        }
      })
    }
  }
}
</script>

<style></style>
