<template>
  <div v-if="drillData">
    <div class="drill-activity-container">
      <div class="drill-container__title">
        <div class="drill-container--line"></div>
        <span>演练活动</span>
      </div>
      <div class="drill-container__content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">演练规模：</span>
              <span class="value">{{ getDrillScope(drillData.drillScope) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">演练内容：</span>
              <span class="value">{{ drillData.drillContent }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">计划完成时间：</span>
              <span class="value">{{ drillData.dueCompleteTime }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="drill-container__content--item">
              <div>
                <span class="label">责任部门：</span>
                <template v-for="(dept, index) in safatyJsonParse(drillData.responsibleDeptNameList)" :key="index">
                  <span class="value">
                    {{ dept }}
                    <span v-if="index !== safatyJsonParse(drillData.responsibleDeptNameList).length - 1">、</span>
                  </span>
                </template>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <div>
                <span class="label">配合部门：</span>
                <template
                  v-if="drillData.coordinateDeptNameList"
                  v-for="(dept, index) in safatyJsonParse(drillData.coordinateDeptNameList)"
                  :key="index"
                >
                  <span class="value">
                    {{ dept }}
                    <span v-if="index !== safatyJsonParse(drillData.coordinateDeptNameList).length - 1">、</span>
                  </span>
                </template>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item" v-if="drillData.emergencyPlanAppendix">
              <span class="label">关联应急预案：</span>
              <span class="value font-primary link" @click="handlePreviewFile(drillData.emergencyPlanAppendix)">{{
                JSON.parse(drillData.emergencyPlanAppendix)[0].fileName
              }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <div class="drill-container__content--item">
              <span class="label">审批流程：</span>
              <span class="value">{{ getApprovalName(drillData.approvalTemplateId) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="drill-execute-form" style="margin-top: 20px">
      <div class="drill-container__title">
        <div class="drill-container--line"></div>
        <span>演练实施</span>
      </div>
      <DrillPlanExecuteForm
        v-if="drillData"
        ref="drillPlanExecuteFormRef"
        :ins-name="drillScopeDice[0].itemCode"
        :drill-data="drillData"
        style="margin-top: 20px"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRoute } from 'vue-router';
  import { DrillPlanItemDetail } from '../types';
  import DrillPlanExecuteForm from './DrillPlanExecuteForm.vue';
  import {
    queryEmergencyDrillPlanDetail,
    saveEmergencyDrillExecute,
    submitEmergencyDrillExecute,
  } from '@/api/emergency-drill/emergency-drill';
  import { getAllApproval } from '@/api/approval/approval';
  import type { FileItem } from '@/views/disaster/types';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
  import { useEmergencyDrillHook } from '../hook';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/views/disaster/constant';

  const route = useRoute();
  const id = route.query.id;
  const approvalList = ref();
  const drillData = ref<DrillPlanItemDetail>();
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();

  const { drillScopeDice, getDrillScopeDict, getDrillScope } = useEmergencyDrillHook();

  const getApprovalList = async () => {
    approvalList.value = await getAllApproval();
  };
  async function getDrillData() {
    try {
      drillData.value = await queryEmergencyDrillPlanDetail(id);
    } catch (e) {
      console.log(e);
    }
  }

  onMounted(async () => {
    await getApprovalList();
    await getDrillScopeDict();
    getDrillData();
  });

  const getApprovalName = (id: number) => {
    return approvalList.value.find((item) => item.id === id)?.templateName;
  };
  const safatyJsonParse = (str: string) => {
    return str.slice(1, -1).split(',');
  };

  const drillPlanExecuteFormRef = ref();

  const formatAttachmentList = async (data: FileItem[]) => {
    if (!data || data.length === 0) return null;
    const file = data[0];
    if (!file.file) return file;
    const fileName = file.fileName;
    const res = await uploadFileApi({ bizType: UPLOAD_BIZ_TYPE.ATTACHMENT, fileName, file: file.file });
    const fileType = file.fileType;
    const fileSize = file.fileSize;
    const fileId = file.fileId;
    const fileUrl = res.url;
    return {
      fileName,
      fileType,
      fileSize,
      fileUrl,
      fileId,
    };
  };

  const handlePreviewFile = (str: string) => {
    const obj = JSON.parse(str);
    const file = Array.isArray(obj) ? obj[0] : obj;
    const url = file.fileUrl;
    const type = file.fileType as keyof typeof FILE_TYPE_ICON;
    if (!url) return;
    previewOnlineRef.value?.open(url, type);
  };

  async function executeSaveOrSubmit(mode: string) {
    if (!drillPlanExecuteFormRef.value) return;
    // drillPlanExecuteFormRef.value.handleClearValidate();
    if (mode === 'submit') {
      const res = await drillPlanExecuteFormRef.value.formValidate();
      if (!res) return;
    }

    const formData = drillPlanExecuteFormRef.value.getFormData();
    let attachmentListRes;
    if (typeof formData.drillScript === 'string') {
      attachmentListRes = formData.drillScript;
    } else if (!formData.drillScript || formData.drillScript.length === 0) {
      attachmentListRes = '';
    } else {
      attachmentListRes = JSON.stringify(await formatAttachmentList(formData.drillScript));
    }

    const executeParams = {
      drillPlanId: formData.drillPlanId,
      drillTime: formData.drillTime,
      drillLocation: formData.drillLocation,
      personInChargeId: formData.personInChargeId,
      drillDeptIdList: formData.drillDeptIdList,
      drillScript: attachmentListRes,
    };

    if (mode === 'save') {
      try {
        await saveEmergencyDrillExecute(executeParams);
        ElMessage.success('保存成功');
        drillPlanExecuteFormRef.value.formClearValidate();
        drillData.value = undefined;
        getDrillData();
      } catch (e) {
        console.log(e);
        ElMessage.error('保存失败');
      }
    } else {
      try {
        await submitEmergencyDrillExecute(executeParams);
        ElMessage.success('提交成功');
        drillPlanExecuteFormRef.value.formClearValidate();
        drillData.value = undefined;
        getDrillData();
      } catch (e) {
        console.log(e);
        ElMessage.error('提交失败');
      }
    }
  }

  defineExpose({
    executeSaveOrSubmit,
  });
</script>

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