<template>
  <div>
    <a-select
      v-bind="$attrs"
      v-model:value="valueRef"
      style="width: 100%"
      :options="
        data.map((item) => ({
          value: props.valueField ? item[props.valueField] : item.id,
          label: item.name,
        }))
      "
      :placeholder="placeholder"
      :mode="mode"
    >
      <template #dropdownRender="{ menuNode: menu }" v-if="isShowAdd">
        <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>
    </a-select>
    <DicDetailDrawer @register="registerDetailDrawer" @success="handleDetailSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Divider } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { onMounted, ref, unref, watch } from 'vue';
  import { getDicDetailList } from '/@/api/system/dic';
  import { DicDetailListParams } from '/@/api/system/dic/model';
  import DicDetailDrawer from '../components/DicDetailDrawer.vue';
  import { useDrawer } from '../../Drawer/src/useDrawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['change']);

  const props = defineProps({
    value: [String, Array],
    itemId: {
      type: String,
      required: true,
    },
    placeholder: String,
    isShowAdd: {
      type: Boolean,
      default: true,
    },
    mode: {
      type: String,
    },
    isDefaultValue: {
      type: Boolean,
      default: false,
    },
    valueField: String,
  });

  const valueRef = ref();

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

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

  watch(
    () => valueRef,
    (val) => {
      emit(
        'change',
        unref(valueRef),
        unref(data).find((x) => x.id === val),
      );
    },
    { deep: true },
  );

  watch(
    () => props.value,
    (val) => {
      valueRef.value = val;
      emit(
        'change',
        unref(valueRef),
        unref(data).find((x) => x.id === val),
      );
    },
    { deep: true },
  );

  async function fetch() {
    const params = { itemId: props.itemId } as DicDetailListParams;
    data.value = ((await getDicDetailList(params)) as unknown as Recordable[]) || [];

    valueRef.value = props.value || (props.isDefaultValue ? data.value[0].id : undefined);
  }

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

  const add = () => {
    openDrawer(true, { itemId: props.itemId });
  };

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