<script setup lang="ts">
import { computed, watch } from "vue";
import { useDictStore } from "@/store/modules/dict";
import type { DictData } from "@/api/dict";

const props = defineProps<{
  dictCode: string;
  modelValue?: string | number;
  placeholder?: string;
  disabled?: boolean;
  clearable?: boolean;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: string | number): void;
  (e: "change", value: string | number): void;
}>();

const dictStore = useDictStore();

const dictList = computed<DictData[]>(() => {
  return dictStore.getDictList(props.dictCode);
});

const currentValue = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit("update:modelValue", val as string | number);
    emit("change", val as string | number);
  }
});

watch(
  () => props.dictCode,
  () => {
    if (!dictStore.loaded) {
      dictStore.loadDictData();
    }
  },
  { immediate: true }
);
</script>

<template>
  <el-select
    v-model="currentValue"
    :placeholder="placeholder || '请选择'"
    :disabled="disabled"
    :clearable="clearable"
    style="width: 100%"
  >
    <el-option
      v-for="item in dictList"
      :key="item.itemValue"
      :label="item.itemLabel"
      :value="item.itemValue"
    />
  </el-select>
</template>
