<script setup lang="ts">
import type { ACTION_TYPE, FILTER_TYPE } from '#/components/Filter'

import { ElInput } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import getDict from '#/hooks/useDict'

import { XBJ_CONFIG } from './config'

const props = withDefaults(
  defineProps<{
    actions?: ((actions: ACTION_TYPE[]) => ACTION_TYPE[]) | ACTION_TYPE[]
    config: FILTER_TYPE[]
    modelValue: anyObj
  }>(),
  {
    modelValue: () => ({}),
    actions: () => [
      {
        type: 'primary',
        label: '查询',
        value: 'search',
      },
      {
        label: '重置',
        value: 'reset',
      },
    ],
  },
)

const emits = defineEmits(['update:modelValue', 'handleAction', 'selectChange'])

const defaultActions = [
  {
    type: 'primary',
    label: '查询',
    value: 'search',
  },
  {
    label: '重置',
    value: 'reset',
  },
]

// 配置日期类型的样式
// const DATEPICKER_WIDTH = XBJ_CONFIG.DATEPICKER.width
// 配置
const _config = computed(() => {
  const d = cloneDeep(props.config)
  d.forEach((i) => {
    if (i.comName === 'el-select') {
      if (i.dict) {
        i.options = getDict(i.dict)
      }
      if (i.options && i.showAll !== false) {
        i.options = [
          {
            [i.selectConfig?.label || 'label']: '全部',
            [i.selectConfig?.value || 'value']: '',
          },
          ...i.options,
        ]
      }
      i.opKey = i.selectConfig?.key || 'id'
      i.opLabel = i.selectConfig?.label || 'label'
      i.opValue = i.selectConfig?.value || 'value'
      i.style = {
        width: XBJ_CONFIG.SELECT.width,
        ...i.style,
      }
    }
  })
  return d
})
// 操作按钮配置
const _actions = computed(() => {
  if (Array.isArray(props.actions)) {
    return props.actions
  }
  if (typeof props.actions === 'function') {
    return props.actions(defaultActions)
  }
})
// 表单dom
const formRef = ref()
// 筛选数据
const filterData = reactive(props.modelValue)
/**
 * @description: 按钮点击事件
 * @param {*} item
 */
const handleAction = (item: ACTION_TYPE) => {
  if (item.value === 'reset') {
    onClear()
  }
  emits('handleAction', item)
}
/**
 * @description: 重置表单数据
 */
const onClear = () => {
  formRef.value?.resetFields()
  for (const i in filterData) {
    filterData[i] = null
  }
}
/**
 * @description: 针对 全部 这个选项 进行优化
 * @param {*} val
 * @param {*} d
 */
const selectOnChange = (val: string | string[], d: anyObj) => {
  emits('selectChange', val)

  if (typeof val === 'object') {
    if (val.length <= 1) return
    if (val.length === 2 && val.includes('')) {
      filterData[d.prop] = filterData[d.prop].filter((i: string) => i !== '')
      return
    }
    val.includes('') && (filterData[d.prop] = [''])
  }
}
/**
 * @description: 组件的变更事件
 * @param {*} val
 * @param {*} d
 */
const comOnChange = (val: string | string[], d: anyObj) => {
  if (d.comName === 'el-date-picker') {
    const fm = d.propFormat as string[]
    const s = fm ? fm[0] : 'startTime'
    const e = fm ? fm[1] : 'endTime'
    filterData[s] = val ? val[0] : null
    filterData[e] = val ? val[1] : null
  }
}

watch(filterData, (newVal) => {
  emits('update:modelValue', newVal)
})

defineExpose({
  getRef: () => formRef.value,
})

// export default {
//   components: {
//     ElAutocomplete,
//     ElCascader,
//     ElInput,
//     ElDatePicker,
//     ElSelectV2,
//   },
// }
</script>

<template>
  <el-form
    ref="formRef"
    inline
    class="filterBox"
    :model="filterData"
    @submit.prevent
  >
    <el-form-item
      v-for="item in _config"
      :key="item.prop"
      :label="item.label"
      :prop="item.prop"
      v-bind="item.formItemConfig"
    >
      <template v-if="item.comName === 'el-input'">
        <ElInput
          v-model="filterData[item.prop]"
          v-bind="item"
          placeholder="请输入"
          @change="comOnChange($event, item)"
          @keyup.enter="handleAction(defaultActions[0])"
        />
      </template>
      <template v-else-if="item.comName === 'el-select'">
        <el-select
          v-model="filterData[item.prop]"
          v-bind="item"
          @change="selectOnChange($event, item)"
        >
          <el-option
            v-for="op in item.options"
            :key="op[item.opKey]"
            :label="op[item.opLabel]"
            :value="op[item.opValue]"
          />
        </el-select>
      </template>
      <template v-else>
        <component
          :is="item.comName"
          v-model="filterData[item.prop]"
          v-bind="item"
          @change="comOnChange($event, item)"
        />
      </template>
    </el-form-item>
    <el-form-item>
      <el-button
        v-for="item in _actions"
        :key="item.value"
        v-bind="item"
        @click="handleAction(item)"
      >
        {{ item.label }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
@include xbj_filter;

:deep(.el-date-editor) {
  // width: v-bind(datepicker_width);
}
</style>
