<template>
  <div class="emergency-plan-container">
    <BasicForm ref="formRef" :formData="ruleFormData" :formConfig="ruleFormConfig" :formRules="formRules">
      <template #appendix>
        <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 '@/views/disaster/components/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 '@/views/disaster/types';
  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 } = 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);
    }
  };
  const handleUploadSuccess = (fileList: FileItem[]) => {
    ruleFormData.uploadFile = fileList;
  };
  const handleValidate = async () => {
    if (!formRef.value) return;
    const validateResult = await formRef.value.validateForm();
    return validateResult;
  };
  const getFormData = () => {
    return ruleFormData;
  };
  onMounted(async () => {
    await getPlanTypeDict();
    await getEmergencyEventDict();
    await getApprovalList();
    getPlanDetail();
  });
  defineExpose({
    handleValidate,
    getFormData,
  });
</script>

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