<template>
  <div style="width: 100%">
    <!-- radio -->
    <el-radio-group v-model="modelVal" @change="onChange" v-if="props.selectType === 'radio'" :disabled="props.disabled">
      <el-radio v-for="(item, i) in options" :key="i" :label="item[fieldNames.value]" :disabled="item.disabled" @click="getlable(item)">
        {{ item[fieldNames.label] }}
      </el-radio>
    </el-radio-group>
    <!-- select -->
    <el-select
      v-else-if="props.selectType === 'select'"
      class="pxdx_box"
      v-model="modelVal"
      clearable
      :multiple="props.multiple"
      :disabled="props.disabled"
      :placeholder="props.placeholder"
      @change="onChange"
      @clear="changeclear"
      style="width: 100%"
      :collapse-tags="collapseTags"
    >
      <el-option
        v-for="item in options"
        :key="item[fieldNames.value]"
        :label="item[fieldNames.label]"
        :value="item[fieldNames.value]"
        :disabled="item.disabled"
        @click="getlable(item)"
      />
    </el-select>
  </div>
</template>
<script setup>
import { unref, watchEffect, watch, getCurrentInstance, ref } from "vue"
import { DICT_TYPE } from "./const/dict"
import { getSysDictByCode } from "@/api/sysDict"

/**使用说明
 * 2种模式：dictKey 和 dictData 二选一，必填
 *  1. dictKey：集成请求，根据key获取字典数据
 *  2. dictData：外部传入options，无需请求数据源
 */
const props = defineProps({
  //选择方式
  selectType: {
    type: String,
    default: "radio" //radio || select
  },
  modelValue: String, //选中值 || 回显
  //字典key
  dictKey: {
    type: String,
    validator: value => Object.keys(DICT_TYPE).includes(value),
    message: "dictKey必须是DICT_TYPE中定义的有效值"
  },
  // options的数据格式
  fieldNames: {
    type: Object,
    validator: value => {
      return "label" in value && "value" in value
    },
    default: () => ({ label: "zdmc", value: "dm" })
  },
  dictData: Array, //数据
  disabled: {
    type: Boolean,
    default: false
  }, //禁用
  placeholder: {
    type: String,
    default: "请选择"
  },
  //是否多选
  multiple: {
    type: Boolean,
    default: false
  },
  /** 原生属性 -- 多选时是否将选中值按文字的形式展示 */
  collapseTags: {
    type: Boolean,
    default: undefined
  },
  //需要禁用的某个或者多个选项
  disabledItem: Array,
  /** 自动清空字典匹配不上的内容(目前仅做单选) */
  autoClear: {
    type: Boolean,
    default: true
  }
})

const { proxy } = getCurrentInstance()

const modelVal = defineModel()
const emits = defineEmits(["update:modelValue", "onChange", "getselect", "changeclear", "getOptions"])
const options = ref([])
const loading = ref(false)

const onChange = val => {
  emits("update:modelValue", val)

  let namearr = []
  if (props.multiple) {
    for (let i = 0; i < val.length; i++) {
      const name = options.value.find(item => item.value == val[i])?.label
      namearr.push(name)
    }
    emits("onChange", val, namearr)
  } else {
    const label = options.value.find(item => item[props.fieldNames.value] == val)?.[props.fieldNames.label]
    emits("onChange", val, label)
  }
}

function getlable(val) {
  if (props.disabled) return
  emits("getselect", val)
}

function changeclear(val) {
  emits("changeclear", val)
}

const getDictData = async () => {
  if (!props.dictKey) return
  // 显示加载状态
  loading.value = true
  try {
    // 等待字典数据加载完成
    const dict = await getSysDictByCode({ dictCode: props.dictKey })
    // 检查是否有数据
    if (dict) {
      options.value = (dict?.itemList || []).map(item => ({
        ...item,
        disabled: props.disabledItem?.includes(item[props.fieldNames.value]) || false,
        label: item[props.fieldNames.label],
        value: item[props.fieldNames.value]
      }))
    } else {
      console.warn("未找到字典数据或数据为空", props.dictKey)
      options.value = []
    }
    emits("getOptions", options.value)
  } catch (error) {
    console.error("字典数据加载失败:", error)
    options.value = []
  } finally {
    // 隐藏加载状态
    loading.value = false
  }
}

watch(
  [() => props.dictData],
  ([opt]) => {
    if (props.autoClear && opt?.length) {
      options.value = (opt || []).map(item => ({
        ...item,
        disabled: props.disabledItem?.includes(item[props.fieldNames.value]) || false,
        label: item[props.fieldNames.label],
        value: item[props.fieldNames.value]
      }))
      // 多选
      // if (props.multiple) {
      //   // 单选
      // } else {
      //   // 清除不存在的项
      //   let arr = Array.isArray(opt) ? opt : []
      //   const curr = arr.find(item => item?.value == val || item?.dm == val) // select 用value ,radio 用value或者dm
      //   if (!curr) modelVal.value = ""
      // }
    }
  },
  {
    immediate: true
  }
)
watch(
  [() => props.dictKey],
  ([val]) => {
    if (val) {
      getDictData()
    }
  },
  {
    immediate: true
  }
)
watchEffect(() => {
  //处理是否禁用选项
  if (props.dictData?.length) {
    options.value = props.dictData.map(item => {
      item.disabled = false
      return item
    })
    if (props.disabledItem?.length) {
      options.value = options.value.map(item => {
        item.disabled = props.disabledItem.includes(item[props.fieldNames.value]) ? true : false
        return item
      })
    } else {
      props.dictData.forEach(item => {
        item.disabled = false
      })
    }
  }
})
</script>
<style>
.el-select-dropdown__item.is-disabled {
  color: #999 !important;
}
</style>
