<template>
  <view>
    <u-dropdown
      ref="dropdownRef"
      :class="{ dropdownClose: !isOpen }"
      @open="isOpen = true"
      @close="isOpen = false"
    >
      <SearchItem
        v-for="schema in getSchema"
        :key="schema.field"
        :schema="schema"
        :formModel="formModel"
        :setFormModel="setFormModel"
        :formActionType="formActionType"
        :isOpen="isOpen"
        @close-dropdown="handleCloseDropdown"
      ></SearchItem>
    </u-dropdown>
    <portal-target name="calendar-portal" />
  </view>
</template>
<script>
import SearchItem from './components/SearchItem.vue'
import { cloneDeep } from 'lodash-es'
export default {
  props: {
    schemas: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    SearchItem,
  },
  computed: {
    formActionType() {
      return {
        setFieldsValue: (values) => {
          const fields = this.getSchema
            .map((item) => item.field)
            .filter(Boolean)
          const delimiter = '.'
          const nestKeyArray = fields.filter(
            (item) => item.indexOf(delimiter) >= 0
          )

          const validKeys = []

          Object.keys(values).forEach((key) => {
            const schema = this.getSchema.find((item) => item.field === key)
            let value = values[key]
            const hasKey = Reflect.has(values, key)

            if (hasKey && fields.includes(key)) {
              //todo 判断时间
              this.formModel[key] = value
              // this.$set(this.formModel, key, value)
              // console.log(key, value);
              validKeys.push(key)
            } else {
              nestKeyArray.forEach((nestKey) => {
                try {
                  const value = eval('values' + delimiter + nestKey)
                  if (this.isDef(value)) {
                    this.formModel[nestKey] = value
                    // this.$set(this.formModel, nestKey, value)
                    validKeys.push(nestKey)
                  }
                } catch (e) {
                  if (this.isDef(defaultValueRef.value[nestKey])) {
                    // this.$set(this.formModel, nestKey, cloneDeep(
                    //   defaultValueRef.value[nestKey]
                    // ))

                    this.formModel[nestKey] = cloneDeep(
                      defaultValueRef.value[nestKey]
                    )
                  }
                }
              })
            }
          })
          // this.formModel = {
          //   ...this.formModel,
          //   ...values,
          // }
        },
      }
    },
    getSchema() {
      const { schemas } = this
      for (const schema of schemas) {
        //todo 判断时间
      }
      return cloneDeep(schemas)
    },
  },
  data() {
    return {
      isOpen: false,
      formModel: {},
    }
  },
  created() {
    this.initFormModel()
  },
  methods: {
    handleOpen() {
      console.log('====')
    },
    handleCloseDropdown() {
      this.$refs.dropdownRef?.close()
    },
    initFormModel() {
      const { schemas } = this
      const formModel = {}
      schemas.forEach((item) => {
        const { field, defaultValue } = item
        if (field) {
          formModel[field] = defaultValue
        }
      })
      this.formModel = formModel
    },
    handleInputNumberValue(component, val) {
      if (!component) return val
      if (
        ['Input', 'InputPassword', 'InputSearch', 'InputTextArea'].includes(
          component
        )
      ) {
        return val && this.isNumber(val) ? `${val}` : val
      }
      return val
    },
    isDef(val) {
      return typeof val !== 'undefined'
    },
    isNumber(val) {
      return typeof val === 'number' && !isNaN(val)
    },
    isArray(val) {
      return Array.isArray(val)
    },
    isObject(val) {
      return typeof val === 'object' && val !== null
    },
    isFunction(val) {
      return typeof val === 'function'
    },
    setFormModel(key, value) {
      // this.$set(this.formModel, key, value)
      // console.log(key, value);
      this.formModel[key] = value
      this.$emit('field-value-change', key, value)
    },
    handleFormValues(values) {
      if (!this.isObject(values)) return {}
      const res = {}
      for (const item of Object.entries(values)) {
        let [, value] = item
        const [key] = item
        const pattern = /^\[(.+)\]$/
        if (pattern.test(key)) {
          const keyArr = key.match(pattern)[1].split(',')
          keyArr.forEach((item, index) => {
            const _val = value?.[index] ?? ''
            if (_val) {
              res[item.trim()] = _val
            }
          })
        } else {
          value && (res[key] = value)
        }
      }
      return Object.assign({}, res)
    },
  },
  watch: {
    formModel: {
      handler(val) {
        this.$u.debounce(() => {
          const res = this.handleFormValues(val)
          this.$emit('submit', res)
        }, 300)
      },
      deep: true,
    },
  },
}
</script>
