<template>
  <component
    :is="elTagNameValue"
    v-bind="item.compOptions"
    v-model.trim="_formModel[handleProp(item.prop)]"
    :data="['tree-select'].includes(item.compOptions.elTagName!) ? itemEnum : []"
    :options="['cascader', 'select-v2'].includes(item.compOptions.elTagName!) ? itemEnum : []"
  >
    <template v-if="item.compOptions.elTagName === 'cascader'" #default="{ data }">
      <span>{{ data[item.compOptions.labelKey || 'label'] }}</span>
    </template>
    <template v-if="item.compOptions.elTagName === 'select'">
      <component
        :is="`el-option`"
        v-for="(col, index) in itemEnum"
        :key="index"
        :label="col[item.compOptions.labelKey || 'label']"
        :value="col[item.compOptions.valueKey || 'value']"
      ></component>
    </template>
    <template v-if="item.compOptions.elTagName === 'radio-group'">
      <component :is="`el-radio`" v-for="(col, index) in itemEnum" :key="index" :value="col[item.compOptions.valueKey || 'value']">
        {{ col[item.compOptions.labelKey || 'label'] }}
      </component>
    </template>
    <template v-if="item.compOptions.elTagName === 'radio-button'">
      <component :is="`el-radio-button`" v-for="(col, index) in itemEnum" :key="index" :label="col[item.compOptions.valueKey || 'value']">
        {{ col[item.compOptions.labelKey || 'label'] }}
      </component>
    </template>
    <template v-if="item.compOptions.elTagName === 'checkbox-group'">
      <component
        :is="`el-checkbox`"
        v-for="col in itemEnum"
        :key="col[item.compOptions.valueKey || 'value']"
        :value="col[item.compOptions.valueKey || 'value']"
      >
        {{ col[item.compOptions.labelKey || 'label'] }}
      </component>
    </template>
  </component>
</template>

<script setup lang="ts" name="Item">
import { computed, inject, ref } from 'vue'
import { handleProp } from '@/utils'
interface FormItem {
  item: ProForm.ItemsOptions
  formModel: Record<string, any>
}
const props = defineProps<FormItem>()
const _formModel = computed(() => props.formModel)
const elTagNameValue = computed(() => {
  const val = props.item.compOptions.elTagName
  if ('radio-button' == val) return `el-radio-group`
  return `el-${val || 'input'}`
})
// 接收 enumMap (el 为 select-v2 需单独处理 enumData)
const enumMap = inject('enumMap', ref(new Map()))
const itemEnum = computed(() => {
  // CompAttributes
  let enumData = enumMap.value.get(props.item.compOptions?.enumKey || props.item.prop)
  if (!enumData) return []
  // 返回对象类型
  if (props.item.compOptions.elTagName === 'tree-select') {
    enumData = enumData.map((el: { [key: string]: any }) => {
      return {
        ...el,
        label: el[props.item.compOptions?.labelKey || 'label'],
        children: el[props.item.compOptions?.children || 'children'] || []
      }
    })
  }
  return enumData
})
</script>
