<template>
  <el-select
    :size="size"
    :disabled="disabled"
    :multiple="multiple"
    filterable
    clearable
    style="width: 100%; min-width: 200px"
    :placeholder="placeholder"
    v-model="state.dataVal"
    @change="handleChange"
  >
    <template #empty>
      <el-empty :image-size="40" description="暂无数据" />
    </template>
    <el-option
      v-for="(item, idx) in state.dicts"
      :key="idx"
      :label="item.name || item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
import { onMounted, reactive, watch, nextTick } from "vue";
import dictUtil from "@/utils/dict";

defineOptions({ name: "ExtDSelect" });

const props = defineProps({
  modelValue: {
    type: [Number, String]
  },
  type: {
    type: String,
    required: true
  },
  dataRange: {
    type: Array as () => Array<{ label: string; value: any }>,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: "请选择"
  },
  size: {
    type: String,
    default: "default"
  }
});

const emit = defineEmits(["update:modelValue", "on-change"]);

const state = reactive({
  dicts: [] as Array<any>,
  dataVal: null as any
});

watch(
  () => props.modelValue,
  val => {
    nextTick(() => {
      if (typeof val === "number") {
        state.dataVal = val + "";
      } else {
        state.dataVal = val;
      }
    });
  },
  { immediate: true }
);

const handleChange = (val: any) => {
  emit("update:modelValue", val);
  emit("on-change", val);
};

const setupDicts = () => {
  if (props.dataRange && props.dataRange.length > 0) {
    state.dicts = props.dataRange;
  } else {
    state.dicts = dictUtil.getDictList(props.type);
  }
};

onMounted(() => {
  setupDicts();
});
</script>

<style scoped>
</style>
