<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from './dict.item.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { saveOrEditDictItem } from '/@/api/system/dict';
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    name: 'ItemDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      let dictId, id;
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        await resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        dictId = data.dictId;
        if (unref(isUpdate)) {
          id = data.record.id;
          await setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增字典值' : '编辑字典值'));

      async function handleSubmit() {
        try {
          const values = await validate();
          const { createMessage } = useMessage();
          setDrawerProps({ confirmLoading: true });
          let message = '添加成功';
          if (unref(isUpdate)) {
            //如果是修改需要传入id
            Reflect.set(values, 'id', id);
            message = '修改成功';
          } else {
            //添加需要dictId
            Reflect.set(values, 'dictId', dictId);
          }
          await saveOrEditDictItem(values, unref(isUpdate));
          closeDrawer();
          emit('success');
          createMessage.success(message);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
