<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';

  defineOptions({ name: 'SchemeDrawer' });

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

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

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

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

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

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      if (isUpdate.value) {
        var querys = 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);
        closeDrawer();
        emit('success');
      } else {
        const data = await postAdd('FlowSort', values);
        closeDrawer();
        emit('success');
      }

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