<template>
  <div class="emergency-plan-container">
    <BasicForm ref="formRef" :formData="ruleFormData" :formConfig="ruleFormConfig" :formRules="formRules">
      <template #uploadFile>
        <UploadFiles
          label="上传附件"
          :maxCount="1"
          @uploadSuccess="handleUploadSuccess"
          :fileList="ruleFormData.uploadFile"
        />
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useEmergencyHook } from '@/views/emergency/src/hoos';
  import { useEmergencyPlanHook } from '../hook';
  import type { EditEmergencyPlaneForm } from '@/types/emergency-plan';
  import type { FileItem } from '@/components/UploadFiles/types.ts';
  import { queryEmergencyPlan } from '@/api/emergency-plan';
  import {
    PLAN_MANAGEMENT_FORM_CONFIG_EDIT,
    PLAN_MANAGEMENT_FORM_DATA_EDIT,
    PLAN_MANAGEMENT_FORM_RULES_EDIT,
  } from '../config';

  const formRef = ref();
  const props = defineProps<{
    id: number;
  }>();
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<EditEmergencyPlaneForm>(
      PLAN_MANAGEMENT_FORM_CONFIG_EDIT,
      PLAN_MANAGEMENT_FORM_DATA_EDIT,
      PLAN_MANAGEMENT_FORM_RULES_EDIT,
    );

  const { getEmergencyEventDict, getEmergencyEvent, getApprovalList, approvalList } = useEmergencyHook();
  const { getPlanTypeDict, getPlanType } = useEmergencyPlanHook();
  const getPlanDetail = async () => {
    const res = await queryEmergencyPlan(props.id);
    for (const key in res) {
      ruleFormData[key] = res[key as keyof typeof res];
      ruleFormData.planTypeName = getPlanType(res.planType) || '';
      ruleFormData.eventTypeName = getEmergencyEvent(res.eventType) || '';
      ruleFormData.approvalTemplateName =
        approvalList.value?.find((item) => item.id === res.approvalTemplateId)?.templateName || '';
      ruleFormData.uploadFile = JSON.parse(res.appendix);
    }
    cloneRuleFormData();
  };
  const handleUploadSuccess = (fileList: FileItem[]) => {
    ruleFormData.uploadFile = fileList;
  };
  const handleValidate = async () => {
    if (!formRef.value) return;
    const validateResult = await formRef.value.validateForm();
    return validateResult;
  };
  const getFormData = () => {
    cloneRuleFormData();
    return ruleFormData;
  };
  onMounted(async () => {
    await getPlanTypeDict();
    await getEmergencyEventDict();
    await getApprovalList();
    getPlanDetail();
    beforeRouteLeave();
  });
  defineExpose({
    handleValidate,
    getFormData,
  });
</script>

<style lang="scss" scoped>
  @use '../styles/info.scss' as *;
</style>
