<template>
  <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { addApprovalNodeInstance } from '@/api/approval/approval';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ApprovalNodeInstanceRuleForm } from '../types';
  import { APPROVAL_NODE_FORM_CONFIG, APPROVAL_NODE_FORM_DATA, APPROVAL_NODE_FORM_RULES } from '../config/form';

  const props = defineProps<{
    initData?: ApprovalNodeInstanceRuleForm;
    orderList?: number[];
  }>();

  //   console.log(props.initData);

  const emits = defineEmits<{
    (e: 'success'): void;
  }>();

  const orderCache = ref(props.initData?.approvalOrder);

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<ApprovalNodeInstanceRuleForm>(
      APPROVAL_NODE_FORM_CONFIG,
      props.initData || APPROVAL_NODE_FORM_DATA,
      APPROVAL_NODE_FORM_RULES,
    );

  const onSumbit = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;
    // console.log(props.orderList);
    if (
      orderCache.value !== ruleFormData.approvalOrder! &&
      props.orderList &&
      props.orderList.includes(ruleFormData.approvalOrder!)
    ) {
      ElMessage.error('该顺序已存在，请重新输入');
      return;
    }
    // 提交表单接口
    try {
      await addApprovalNodeInstance(ruleFormData);
      emits('success');
      orderCache.value = undefined;
    } catch (e) {
      console.log(e);
    }
  };

  const onRefresh = () => {
    basicFormRef.value?.clearValidate();
  };

  defineExpose({
    onSumbit,
    onRefresh,
  });
</script>

<style scoped></style>
