<template>
  <div class="emergency-plan-container">
    <BasicForm ref="formRef" :formData="ruleFormData" :formConfig="ruleFormConfig">
      <template #uploadFile>
        <div class="appendix-container" v-if="ruleFormData.uploadFile.length">
          <div class="appendix-item" v-for="item in ruleFormData.uploadFile" :key="item.fileId">
            <div class="appendix-item-name" @click="handlePreviewScript(item.fileUrl, item.fileType)">
              {{ item.fileName }}
            </div>
          </div>
        </div>
        <div v-else style="color: rgba(0, 0, 0, 0.65)">暂无预案文件</div>
      </template>
    </BasicForm>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.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 { queryEmergencyPlan } from '@/api/emergency-plan';
  import { PLAN_MANAGEMENT_FORM_CONFIG_EDIT, PLAN_MANAGEMENT_FORM_DATA_EDIT } from '../config';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';

  const formRef = ref();
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const props = defineProps<{
    id: number;
  }>();
  const { ruleFormConfig, ruleFormData } = useFormConfigHook<EditEmergencyPlaneForm>(
    PLAN_MANAGEMENT_FORM_CONFIG_EDIT,
    PLAN_MANAGEMENT_FORM_DATA_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 handlePreviewScript = (url: string | undefined, type: string) => {
    if (!url) return;
    previewOnlineRef.value?.open(url, type as keyof typeof FILE_TYPE_ICON);
  };
  onMounted(async () => {
    await getPlanTypeDict();
    await getEmergencyEventDict();
    await getApprovalList();
    getPlanDetail();
  });
</script>

<style lang="scss" scoped>
  @use '../styles/info.scss' as *;
  .appendix-item-name {
    cursor: pointer;
    color: $primary-color;
  }
</style>
