<template>
  <Dialog v-model="diaVisible" diaTitle="数据分析" width="90%" height="90%" @close="closeFun">
    <div class="content">
      <div class="filter-analysis-content">
        <el-checkbox class="check-all" v-model="checkAll" label="全选" value="all" @change="checkAllChangeFun" />
        <el-checkbox-group class="check-all" v-model="checkAnalysisList">
          <template v-for="item in analysisTypeList" :key="item.value">
            <el-checkbox
              v-show="item.includes.includes(analysisType)"
              :label="item.name"
              :value="item.value"
              @change="checkChangeFun(item.value)"
            />
          </template>
        </el-checkbox-group>
        <el-button @click="exportPdfFun">导出PDF</el-button>
      </div>
      <div class="check-table-content" id="compare-content" ref="contentToConvertRef" v-loading="isLoading">
        <div class="loadcase-table-content">
          <BaseTable
            v-if="checkTableName"
            @checkbox-all="changeChceckFun"
            @checkbox-change="changeChceckFun"
            ref="checkTableRef"
            :tableName="checkTableName"
            showCheckbox
            hidePagination
          ></BaseTable>
        </div>
        <template v-for="item in analysisTypeList" :key="item.value">
          <div class="analysis-type-content" v-show="checkAnalysisList.includes(item.value)">
            <div class="analysis-type-content-title">
              <div class="title-item">{{ getTitleFun(item.value) }}</div>
            </div>
            <div class="analysis-type-content-item" v-if="checktableData.length">
              <template v-if="item.value === 'model'">
                <modelFileResult v-if="showComponents" :check-task-info="modelData" :cloumn-width="cloumnWidth">
                </modelFileResult>
              </template>
              <template v-if="item.value === 'calculationFile'">
                <calculationFileResult
                  v-if="showComponents"
                  :check-task-info="calculationFileData"
                  :cloumn-width="cloumnWidth"
                ></calculationFileResult>
              </template>
              <template v-if="item.value === 'numericalResult'">
                <performanceAnalysis
                  v-if="showComponents"
                  :check-task-info="performanceData"
                  :cloumn-width="cloumnWidth"
                ></performanceAnalysis>
              </template>
              <template v-if="item.value === 'result'">
                <cloudImage v-if="showComponents" :check-task-info="resultData" :cloumn-width="cloumnWidth">
                </cloudImage>
              </template>
              <template v-if="item.value === 'curve'">
                <curveResult v-if="showComponents" :check-task-info="curveData" :cloumn-width="cloumnWidth">
                </curveResult>
              </template>
              <template v-if="item.value === 'report'">
                <reportComparison v-if="showComponents" :check-task-info="reportData" :cloumn-width="cloumnWidth">
                </reportComparison>
              </template>
            </div>
          </div>
        </template>
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="closeFun">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import modelFileResult from './modelFileResult.vue';
import calculationFileResult from './calculationFileResult.vue';
import performanceAnalysis from './performanceAnalysis.vue';
import cloudImage from './cloudImage.vue';
import curveResult from './curveResult.vue';
import reportComparison from './reportComparison.vue';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';
import { getAllRunResultByTaskIdApi } from '@/api/project/analysis';
import { getSimulationTaskFileApi } from '@/api/data/dataAnalysis';

const props = defineProps({
  analysisData: {
    type: Object,
    default: () => { },
  },
});

const cloumnWidth = ref('200');

const checkTableRef = ref();

const diaVisible = ref(true);

const checkAnalysisList = ref<any>([]);
const checktableData = ref<any>([]);

const emits = defineEmits(['close']);

const closeFun = () => {
  emits('close');
};

const analysisType = ref<any>('');
const analysisTableData = ref<any>([]);
const showComponents = ref(true);
const performanceData = ref<any>([]);
const modelData = ref<any>([]);
const calculationFileData = ref<any>([]);
const resultData = ref<any>([]);
const curveData = ref<any>([]);
const reportData = ref<any>([]);
const isLoading = ref(false);
const changeChceckFun = async () => {
  isLoading.value = true;
  showComponents.value = false;
  checktableData.value = checkTableRef.value.tableRef.getCheckboxRecords();
  console.log(checktableData.value);

  const fileType = analysisType.value;

  for (let i = 0; i < checkAnalysisList.value.length; i++) {
    await getConvertData(checkAnalysisList.value[i], fileType);
  }
  isLoading.value = false;

  setTimeout(() => {
    showComponents.value = true;
  }, 50);
};

const getConvertData = async (flag: any, type: any) => {
  let data: any = [];
  // const tasklist = [
  //   {
  //     id: 'simu_dc3a8eeb-9108-4058-b9a8-eb8427fb175a13657',
  //   },
  //   {
  //     id: 'simu_a308aaba-db9e-40fd-9870-062a177f6faf78765',
  //   },
  // ];

  const tasklist = checktableData.value;

  if (flag === 'numericalResult') {

    if (type === '仿真工况' || type === '仿真算例') {
      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.performances;
          data = data.concat(list);
        }
      } else {
        data = [];
      }

      performanceData.value = data;
    } else {
      performanceData.value = checktableData.value;
    }

  } else if (flag === 'model') {
    modelData.value = [];
    if (type === '仿真工况' || type === '仿真算例') {
      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.runs;
          data = data.concat(list);
        }
      } else {
        data = checktableData.value;
      }

      const runs = data || [];
      for (let i = 0; i < runs.length; i++) {
        const datas = await getFileInfo(runs[i], 1);
        modelData.value = modelData.value.concat(datas);
      }
    } else {
      modelData.value = checktableData.value;
    }

  } else if (flag === 'calculationFile') {
    calculationFileData.value = [];
    if (type === '仿真工况' || type === '仿真算例') {
      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.runs;
          data = data.concat(list);
        }
      } else {
        data = checktableData.value;
      }
      const runs = data || [];
      for (let i = 0; i < runs.length; i++) {
        const datas = await getFileInfo(runs[i], 3);
        calculationFileData.value = calculationFileData.value.concat(datas);
      }
    } else {
      calculationFileData.value = checktableData.value;
    }

  } else if (flag === 'result') {
    resultData.value = [];

    if (type === '仿真工况' || type === '仿真算例') {
      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.runs;
          data = data.concat(list);
        }
      } else {
        data = checktableData.value;
      }
      const runs = data || [];
      for (let i = 0; i < runs.length; i++) {
        const datas = await getFileInfo(runs[i], 5);
        resultData.value = resultData.value.concat(datas);
      }
    } else {
      resultData.value = checktableData.value;
    }

  } else if (flag === 'curve') {
    curveData.value = [];
    if (type === '仿真工况' || type === '仿真算例') {
      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.runs;
          data = data.concat(list);
        }
      } else {
        data = checktableData.value;
      }
      const runs = data || [];
      for (let i = 0; i < runs.length; i++) {
        const datas = await getFileInfo(runs[i], 4);
        curveData.value = curveData.value.concat(datas);
      }
    } else {
      curveData.value = checktableData.value;

    }

  } else if (flag === 'report') {
    reportData.value = [];
    if (type === '仿真工况' || type === '仿真算例') {

      if (type === '仿真工况') {
        for (let i = 0; i < tasklist.length; i++) {
          const list = (await getAllRunResultByTaskIdFun(tasklist[i].uuid))?.runs;
          data = data.concat(list);
        }
      } else {
        data = checktableData.value;
      }
      const runs = data || [];
      for (let i = 0; i < runs.length; i++) {
        const datas = await getFileInfo(runs[i], 2);
        reportData.value = reportData.value.concat(datas);
      }
    } else {
      reportData.value = checktableData.value;

    }

  }

  return data || [];

};

const getAllRunResultByTaskIdFun = async (id: any) => {
  const param = {
    taskId: id,
  };
  try {
    const res: any = await getAllRunResultByTaskIdApi(param);
    if (res && res.code === 200) {

      let performanceList: any = [];

      const runs: any = [];

      for (let i = 0; i < res.data.runResultResp.length; i++) {
        performanceList = performanceList.concat(res.data.runResultResp[i].simulationPerformance);

        const obj: any = {
          ...res.data.runResultResp[i].simulationRun,
          taskName: res.data.runResultResp[i]?.simulationPerformance[0]?.taskName,
        };

        runs.push(obj);
      }

      return {
        performances: performanceList,
        runs,
      };
    }
  } catch (error) {
    console.log(error);

  }
};

const analysisTypeList = ref<any>([

  {
    value: 'model',
    name: '模型文件',
    includes: ['仿真工况', '仿真算例', '模型文件'],
  },
  {
    value: 'calculationFile',
    name: '计算文件',
    includes: ['仿真工况', '仿真算例', '计算文件'],
  },
  {
    value: 'numericalResult',
    name: '数值结果',
    includes: ['仿真工况', '仿真算例', '数据指标'],
  },
  {
    value: 'result',
    name: '云图结果',
    includes: ['仿真工况', '仿真算例', '结果云图'],
  },
  {
    value: 'curve',
    name: '曲线结果',
    includes: ['仿真工况', '仿真算例', '结果曲线'],
  },
  {
    value: 'report',
    name: '仿真报告',
    includes: ['仿真工况', '仿真算例', '仿真报告'],
  },
]);

const checkTableName = ref<any>('');

const getFileInfo = async (data: any, fileType: any) => {
  const res: any = await getSimulationTaskFileApi({
    taskId: '',
    runId: data.uuid,
    fileBizType: fileType,
    fileName: '',
    startTime: '',
    endTime: '',
    current: 1,
    size: 1000,
  });

  if (res && res.code === 200) {
    const list = res.data.data.map((item: any) => {
      return {
        ...item,
        runName: data.runName,
        taskName: data.taskName,
        taskId: data.taskId,
        uuid: data.uuid,
      };
    });

    return list;
  } else {
    return [];
  }
};

watch(() => props.analysisData, async (newVal) => {
  if (newVal) {
    analysisType.value = newVal.flag;
    analysisTableData.value = newVal.data;

    checkTableName.value = newVal.tableName;
    const list = analysisTypeList.value.filter((item: any) => {
      return item.includes.includes(analysisType.value);
    });

    checkAnalysisList.value = list.map((item: any) => {
      return item.value;
    });

    setTimeout(async () => {
      checkTableRef.value?.setDataFun(analysisTableData.value);
    }, 1000);
  }
}, {
  deep: true,
  immediate: true,
});

const checkChangeFun = (flag: any) => {
  console.log(flag, 'flag');
  console.log(checkAnalysisList.value, 'checkAnalysisList');

  const list = analysisTypeList.value.filter((item: any) => {
    return item.includes.includes(analysisType.value);
  });

  if (checkAnalysisList.value.length === list.length) {
    checkAll.value = true;
  } else {
    checkAll.value = false;

  }

};

const checkAll = ref(true);
const checkAllChangeFun = () => {

  const list = analysisTypeList.value.filter((item: any) => {
    return item.includes.includes(analysisType.value);
  });

  if (checkAll.value) {
    checkAnalysisList.value = list.map((item: any) => {
      return item.value;
    });
  } else {
    checkAnalysisList.value = [];
  }
};

const getTitleFun = (flag: any) => {
  const name = analysisTypeList.value.find((item: any) => {
    return item.value === flag;
  })?.name;

  return name + '对比';
};

const contentToConvertRef = ref();
const exportPdfFun = async () => {
  ElMessage.success('文件正在导出，请稍后');
  const content = contentToConvertRef.value;
  const canvas = await html2canvas(content);
  const imgData = canvas.toDataURL('image/png');
  const pdf = new jsPDF('p', 'mm', 'a4');
  const imgWidth = pdf.internal.pageSize.getWidth();
  const imgHeight = (canvas.height * imgWidth) / canvas.width;
  pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
  pdf.save(`分析报告_${dayjs().format('YYYYMMDDHHmm')}.pdf`); // 保存PDF文件
};

</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: 100%;
  overflow: auto;

  .filter-analysis-content {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .check-all {
      margin-right: 30px;
    }
  }

  .check-table-content {
    width: 100%;

    .loadcase-table-content {
      width: 100%;

    }

    .analysis-type-content {
      width: 100%;

      .analysis-type-content-title {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;

        .title-item {
          border-left: 4px solid #409eff;
          padding-left: 10px;
          font-size: 16px;
          font-weight: 600;
        }

      }

      .analysis-type-content-item {
        width: 100%;
      }
    }

  }
}
</style>
