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

  import { postAdd, update } from '@/api/sys/sysDataItemDetail';
  import { useMessage } from '@/hooks/web/useMessage';
  const {  createMessage } = useMessage();
  defineOptions({ name: 'SchemeDrawer' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const detail = ref({})
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      detail.value = data.record
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  interface querysType{
    description?:string,
    enabledMark?:number,
    itemName?:string,
    itemValue?:string,
    sortCode?:number,
  }
  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      if (isUpdate.value) {
        const querys:querysType = detail.value
        querys.description = values.description
        querys.enabledMark = values.enabledMark
        querys.itemName = values.itemName
        querys.itemValue = values.itemValue
        querys.sortCode = values.sortCode
        const data = await update(querys);
        if (data) {
          closeDrawer();
          emit('success');
          return createMessage.success('编辑成功');
        } else {
          return createMessage.error('编辑失败');
        }
      } else {
        const data = await postAdd('FlowSort', values);
        if (data) {
          closeDrawer();
          emit('success');
          return createMessage.success('新增成功');
        } else {
          return createMessage.error('新增失败');
        }
      }

    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>