<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="t('新增数据字典')"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { addDicItem } from '/@/api/system/dic';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);

  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('字典名称'),
      required: true,
      title: t('基本信息'),
      component: 'Input',
      componentProps: {
        placeholder: t('请输入字典名称'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'code',
      label: t('字典编码'),
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: t('请输入字典编码'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'value',
      label: t('字典值'),
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: t('请输入字典值'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'sortCode',
      label: t('排序'),
      component: 'InputNumber',
      componentProps: {
        style: { width: '100%' },
        placeholder: t('请输入排序号'),
      },
      colProps: { span: 24 },
    },
    {
      label: t('备注'),
      field: 'remark',
      component: 'InputTextArea',
      componentProps: {
        placeholder: t('请输入备注'),
      },
      colProps: { span: 24 },
    },
  ];

  const { notification } = useMessage();

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (_) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      await addDicItem(values);
      notification.success({
        message: t('提示'),
        description: t('新增成功'),
      }); //提示消息
      closeDrawer();
      emit('success', values);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
