<template>
  <div>
    <Select
      v-model:value="valueRef"
      style="width: 100%"
      :options="data.map((item) => ({ value: item.id, label: item.name }))"
    >
      <template #dropdownRender="{ menuNode: menu }">
        <component :is="menu" />
        <Divider style="margin: 4px 0" />
        <div
          style="padding: 4px 8px; cursor: pointer"
          @mousedown="(e) => e.preventDefault()"
          @click="add"
        >
          <plus-outlined />
          {{ t('新增') }}
        </div>
      </template>
    </Select>
    <DicItemDrawer @register="registerDetailDrawer" @success="handleDetailSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Select, Divider } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { onMounted, ref, unref, watch } from 'vue';
  import { getDicItemList } from '/@/api/system/dic';
  import DicItemDrawer from '../components/DicItemDrawer.vue';
  import { useDrawer } from '../../Drawer/src/useDrawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['update:value', 'change']);

  const props = defineProps({
    value: String,
  });

  const valueRef = ref();

  const data = ref<Recordable[]>([]);

  onMounted(() => {
    fetch();
  });

  watch(
    () => valueRef,
    () => {
      emit('update:value', unref(valueRef).toString());
      emit('change', unref(valueRef).toString());
    },
    { deep: true },
  );

  watch(
    () => props.value,
    (val) => {
      valueRef.value = val;
      emit('update:value', unref(valueRef).toString());
      emit('change', unref(valueRef).toString());
    },
    { deep: true },
  );

  async function fetch() {
    data.value = await getDicItemList();

    valueRef.value = props.value;
  }

  const [registerDetailDrawer, { openDrawer }] = useDrawer();

  const add = () => {
    openDrawer(true);
  };

  const handleDetailSuccess = () => {
    fetch();
  };
</script>
