<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { DictDataApi } from '#/api/system/dict/dictData';

import { computed, defineComponent, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, Divider, Input, Select, Space } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/system/dict/dictData';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { tagSelectOptions } from './data';

// import { getDictOptions } from '#/utils/dict';

const emit = defineEmits<{
  success: [];
}>();
const formData = ref<DictDataApi.DictData>();

const tagSelectList = ref(tagSelectOptions());
const newTag = ref('');
const inputRef = ref();

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'dictId',
  },
  {
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    fieldName: 'dictType',
    label: '字典类型',
  },
  {
    component: 'Input',
    fieldName: 'dictLabel',
    label: '字典标签',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'dictValue',
    label: '字典键值',
    rules: 'required',
  },
  {
    component: 'Select',
    // slots: { default: 'dictLabel' },
    componentProps: {
      allowClear: true,
      filterOption: true,
      // mode: 'tags',
      // maxTagCount: 1,
      placeholder: '请选择',
      options: tagSelectList,
    },
    fieldName: 'listClass',
    label: '标签样式',
  },
  {
    component: 'Input',
    fieldName: 'dictSort',
    label: '排序',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'description',
    label: '描述',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 90,
  },
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<DictDataApi.DictData>();
    if (data) {
      formData.value = data;
      await formApi.setValues(formData.value);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<DictDataApi.DictData>();
    try {
      await (formData.value?.id
        ? apiUpdate({ id: formData.value.id, ...data })
        : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

const addItem = (e: Event) => {
  e.preventDefault();
  tagSelectList.value.push({ label: newTag.value, value: newTag.value });
  newTag.value = '';
  setTimeout(() => {
    inputRef.value?.focus();
  }, 0);
};

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  formData.value?.id ? '修改字典明细' : '新增字典明细',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4">
      <template #listClass="slotProps">
        <Select v-bind="slotProps" placeholder="请选择标签样式">
          <template #dropdownRender="{ menuNode: menu }">
            <VNodes :vnodes="menu" />
            <Divider style="margin: 4px 0" />
            <Space style="padding: 4px 8px">
              <Input
                ref="inputRef"
                v-model:value="newTag"
                placeholder="Please enter item"
              />
              <Button type="text" @click="addItem">
                <template #icon>
                  <Plus />
                </template>
                Add item
              </Button>
            </Space>
          </template>
        </Select>
      </template>
    </BasicForm>
  </Drawer>
</template>
