<!--
  审批流 基本信息 新增/编辑弹窗（先选单据）
  @author GHT
  @date 2026-05-29 for：【QH-MES审批流设计】新增审批流可视化设计
-->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" :width="560" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './approvalFlow.data';
  import { saveOrUpdateApprovalFlow, getApprovalFlowById } from './approvalFlow.api';

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

  const isUpdate = ref(true);
  const title = computed(() => (unref(isUpdate) ? '编辑审批流' : '新增审批流'));

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

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate) && data?.record?.id) {
      const record = await getApprovalFlowById({ id: data.record.id });
      await setFieldsValue({ ...record });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await saveOrUpdateApprovalFlow(values, unref(isUpdate));
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
