<template>
  <BasicDialog ref="basicDialogRef" title="添加审批流程" @refresh="refreshFromData">
    <template #form>
      <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig" />
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSumbit">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog">取消</el-button>
    </template>
  </BasicDialog>
  <UploadLoading :form-loading="formLoading" v-if="formLoading" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ApprovalInstanceRuleForm } from '../types';
  import { APPROVAL_FORM_CONFIG, APPROVAL_FORM_DATA, APPROVAL_FORM_RULES } from '../config/form';
  import { addApprovalInstance } from '@/api/approval/approval';
  import UploadLoading from '@/components/UploadLoading.vue';

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<ApprovalInstanceRuleForm>(APPROVAL_FORM_CONFIG, APPROVAL_FORM_DATA, APPROVAL_FORM_RULES);
  const formLoading = ref(false);

  const emits = defineEmits<{
    (e: 'success'): void;
  }>();
  const openDialog = () => {
    basicDialogRef.value?.openDialog();
  };
  const handleSumbit = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;
    // 提交表单接口
    try {
      formLoading.value = true;
      await addApprovalInstance(ruleFormData);
      emits('success');
      formLoading.value = false;
      basicDialogRef.value?.closeDialog();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };
  const refreshFromData = () => {
    basicFormRef.value?.clearValidate();
  };
  defineExpose({
    openDialog,
  });
</script>

<style scoped lang="scss"></style>
