<template>
  <div>
    <Select
      v-model:value="value"
      style="width: 100%"
      :options="data.map((item) => ({ value: item.id, label: item.name }))"
      :placeholder="t('请选择数据选项')"
    >
      <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>
    </Select>
    <DatasourceDrawer @register="registerDbDrawer" @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, watch } from 'vue';
  import { getDatasourceList } from '/@/api/system/datasource';
  import { useDrawer } from '../../Drawer';
  import DatasourceDrawer from '../components/DatasourceDrawer.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['update:value', 'change']);

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

  const value = ref();

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

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

  watch(
    () => props.value,
    (val) => {
      value.value = val;

      // emit('change', val);
      // emit('update:value', value.value);
    },
    { deep: true, immediate: true },
  );

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

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

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

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

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