<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="600px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="OperationOrderDetailDrawer">
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './schema';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import * as OperationOrderDetailApi from '/@/api/order/operationOrderDetailApi';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const entityId = ref(0);

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

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

    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
        goodsId: { label: data.record.goodsName, value: data.record.goodsId },
      });
    }
  });

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

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const {
        goodsId,
        ...rest
      } = values;
      const action = !unref(isUpdate) ? OperationOrderDetailApi.add : OperationOrderDetailApi.update;
      const data = !unref(isUpdate)
        ? {
            ...rest,
            goodsId: goodsId.value,
            goodsName: goodsId.label,
          }
        : Object.assign({},
          {
            ...rest,
            id: unref(entityId),
            goodsId: goodsId.value,
            goodsName: goodsId.label,
          },
        );
      await action(data);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
