<template>
  <div v-if="drillData" class="drill-plan-detail">
    <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" v-if="drillData.coordinateDeptNameList">
              <div>
                <span class="label">配合部门：</span>
                <template 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>
              <!-- <a v-if="emergencyPlanDetail" class="value font-primary" :href="emergencyPlanDetail.appendix">{{
                emergencyPlanDetail.planName
              }}</a> -->
            </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-activity-container" style="margin-top: 20px">
      <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">{{ drillData.drillTime }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">演练地点：</span>
              <span class="value">{{ drillData.drillLocation }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">演练负责人：</span>
              <span class="value">{{ drillData.personInChargeName }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="drill-container__content--item" v-if="drillData.drillScript">
              <span class="label">演练脚本：</span>
              <span class="value font-primary link" @click="handlePreviewFile(drillData.drillScript)">{{
                JSON.parse(drillData.drillScript).fileName
              }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="drill-container__content--item">
              <span class="label">签到码：</span>
              <span class="value font-primary link" @click="basicDialogRef.openDialog">查看签到码</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="drill-container__title" style="margin-top: 20px">
      <div class="drill-container--line"></div>
      <span>演练参与部门</span>
    </div>
    <el-button style="margin-top: 20px" type="primary" :icon="Download" @click="downloadSignList(Number(id))">
      下载签到名单
    </el-button>
    <BasicTable style="margin-top: 20px" :tableConfig="tableConfig" :tableData="drillData.planDetailList!">
      <template #drillScriptStatus="scope">
        <span>{{ scope.row.drillScriptStatus === 1 ? '未会签' : '已会签' }}</span>
      </template>
    </BasicTable>
    <PreviewOnline ref="previewOnlineRef" />
    <BasicDialog ref="basicDialogRef" title="签到码" width="640">
      <template #form>
        <QrCode :value="qrCode" :width="600" />
      </template>
    </BasicDialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { Download } from '@element-plus/icons-vue';
  import { useRoute } from 'vue-router';
  import { DrillPlanItemDetail } from '../types';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { getAllApproval } from '@/api/approval/approval';
  import { queryEmergencyDrillPlanDetail, getSignListFile } from '@/api/emergency-drill/emergency-drill';
  import { DRILL_PLAN_ACTIVITIES_TABLE_OPTIONS, DRILL_PLAN_ACTIVITIES_TABLE_COLUMNS } from '../configs/plan/table';
  import { useEmergencyDrillHook } from '../hook';
  import QrCode from '@/components/Qrcode/src/Qrcode.vue';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import { downloadFile } from '@/views/disaster/utils/download';
  import { useGlobSetting } from '@/hooks/setting';

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

  const { getDrillScopeDict, getDrillScope } = useEmergencyDrillHook();

  const { drillSignUrl } = useGlobSetting();

  const getApprovalList = async () => {
    approvalList.value = await getAllApproval();
  };

  async function getDrillData() {
    try {
      tableConfig.loading = true;
      drillData.value = await queryEmergencyDrillPlanDetail(id);

      // 获取应急预案名 (取消 需求文档显示文件名而非预案名，无需获取)
      // if (drillData.value.emergencyPlanId) {
      //   emergencyPlanDetail.value = await queryEmergencyPlanDetail(drillData.value.emergencyPlanId);
      // }

      // 获取二维码
      qrCode.value = drillSignUrl + '?id=' + id;

      tableConfig.loading = false;
    } catch (e) {
      console.log(e);
    }
  }

  const { tableConfig } = useTableConfig(
    DRILL_PLAN_ACTIVITIES_TABLE_COLUMNS,
    DRILL_PLAN_ACTIVITIES_TABLE_OPTIONS,
    false,
  );

  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 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 downloadSignList(id: number) {
    try {
      const res = await getSignListFile(id);
      if (res.size === 0) return;
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      downloadFile(url, '演练签到名单.xlsx');
    } catch (e) {
      ElMessage.error('下载失败');
      console.log(e);
    }
  }
</script>

<style scoped lang="scss">
  @use '../style/common.scss' as *;
  .link {
    cursor: pointer;
  }
  :deep(.basic-dialog--custom) {
    max-height: unset;
  }
</style>
