<template>
  <div>
    <a-select
      v-bind="$attrs"
      v-model:value="valueRef"
      style="width: 100%"
      :mode="mode"
      :options="data"
      :fieldNames="{ label: 'dbName', value: 'id' }"
      :placeholder="placeholder"
      @change="handleChange"
    >
      <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"
        >
          <PlusOutlined />
          {{ t('新增') }}
        </div>
      </template>
    </a-select>
    <DatabaseLinkDrawer @register="registerDbDrawer" @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 { getDatabaselinkTree } from '/@/api/system/databaselink';
  import DatabaseLinkDrawer from '../components/DatabaseLinkDrawer.vue';
  import { TreeItem } from '/@/components/Tree';
  import { useDrawer } from '../../Drawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isNil } from 'lodash-es';

  const { t } = useI18n();
  const emit = defineEmits(['change']);

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

  const valueRef = ref();

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

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

  const handleChange = async (value, option?) => {
    if (!option) {
      if (!data.value.length) await fetch();
      const selectData = data.value.filter((item) => item.id === value);
      option = selectData.length ? selectData[0] : null;
      if (isNil(value)) value = data.value[0].id;
    }
    emit('change', value, option);
  };

  watch(
    () => props.value,
    (val) => {
      valueRef.value = val;
      handleChange(unref(valueRef));
    },
    {
      immediate: true,
    },
  );

  async function fetch() {
    data.value = ((await getDatabaselinkTree()) as unknown as TreeItem[]) || [];
  }

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

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

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