<template>
  <div class="gl-page-content-full">
    <div class="table">
      <BaseTable
        ref="tableRef"
        :tableName="modelData[currentModel].tableName"
        :api="modelData[currentModel].api"
        :exportApi="modelData[currentModel].exportApi"
        :exportFileName="modelData[currentModel].exportFileName"
        :exportParams="modelData[currentModel].exportParams"
        showIndex
        showCheckbox
        :params="modelData[currentModel].params"
        :actionList="actionList"
        fullHeight
        :searchAttrs="{
          startTime: {
            'disabled-date': disabledStartDateFun,
          },
          beginTime: {
            'disabled-date': disabledStartDateFun,
          },
          endTime: {
            'disabled-date': disabledEndDateFun,
          },
        }"
        :rowConfig="{
          keyField: 'id',
        }"
        @checkbox-change="checkboxChangeFun"
        @checkbox-all="checkBoxAllChangeFun"
        @searchChange="searchChangeFun"
        @dataChange="tableDataChangeFun"
      >
        <template #leftOptions>
          <div class="options">
            <div class="chose-mode">
              <el-select v-model="currentModel" @change="modeChangeFun">
                <el-option
                  v-for="item in modeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="btn">
              <el-button @click="showCompareListFun">已选数据</el-button>
              <div v-if="compareList.length > 0" class="num">{{ compareList.length }}</div>
            </div>
            <el-button
              type="primary"
              :disabled="!compareList.length"
              @click="compareFun(currentModel)"
            >
              对比
            </el-button>
            <el-button
              type="primary"
              v-if="currentModel === '数据指标'"
              :disabled="!compareList.length"
              @click="showAnalysisDialog = true"
            >
              指标分析
            </el-button>
          </div>
        </template>
        <template #achieveStatus="{ row }">
          <StatusDot
            :status="statusMapFun5(row.achieveStatus)"
            :title="RESULT_ACHIEVE_STATUS.O[row.achieveStatus]"
          />
        </template>
        <template #exeStatus="{ row }">
          <StatusDot
            :status="statusMapFun6(row.exeStatus)"
            :title="TASK_ACHIEVE_STATUS.O[row.exeStatus]"
          />
        </template>
        <!-- 指标类型 PERFORMANCE_TYPE-->
        <template #performanceType="{ row }">
          {{ PERFORMANCE_TYPE.O[row.performanceType] }}
        </template>
        <!-- 单位 PERFORMANCE_UNIT-->
        <template #unit="{ row }">
          {{ PERFORMANCE_UNIT.O[row.unit] }}
        </template>
      </BaseTable>
    </div>
    <Dialog
      v-model="diaVisible"
      diaTitle="曲线对比"
      :width="'90%'"
      :height="'90%'"
      :confirm-closable="false"
      :zIndex="100"
    >
      <div class="compare-wrapper">
        <div class="compare-header">
          <el-button @click="exportCurvePdfFun">{{ $t('通用.导出PDF') }}</el-button>
        </div>
        <div class="compare-container compare-flex-item" ref="curveCompareRef">
          <div class="compare-container-left">
            <BaseTable
              ref="tableCompareRef"
              tableName="COMPARE_CURVE"
              showIndex
              showCheckbox
              hidePagination
              @checkbox-change="checkBoxChangeFun"
              @checkbox-all="checkBoxChangeFun"
              @searchChange="searchChangeFun"
            >
              <template #leftOptions>
                <div class="compare-container-left-options">
                  <span>设置列数据：</span>
                  <el-input-number v-model="columnData" :min="1" :max="10" />
                </div>
              </template>
              <template #operate="{ row }">
                <span>图：</span>
                <el-input
                  class="image-number-input"
                  v-model="row.imageNumber"
                  @blur="changeImageNumberFun"
                />
              </template>
            </BaseTable>
          </div>
          <div class="compare-container-right">
            <div
              class="chart-container"
              :style="{
                // eslint-disable-next-line
                display: 'grid',
                gridTemplateColumns: `repeat(${columnData} ,${100 / columnData}%)`,
              }"
            >
              <div class="chart-box" v-for="(value, key) in compareData" :key="key">
                <EchartCard
                  :title="`图${key}`"
                  :ref="(el) => (projectStorageSpaceStatisticsRef[`chart-${key}`] = el)"
                  :charts-id="'chart-' + key"
                  :bar-type="'lineChart'"
                >
                </EchartCard>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div>
          <el-button @click="closeFun">关闭</el-button>
        </div>
      </template>
    </Dialog>
    <Dialog
      v-model="diaPngVisible"
      diaTitle="云图对比"
      :width="'90%'"
      :height="'90%'"
      :confirm-closable="false"
      :zIndex="100"
    >
      <div class="compare-wrapper">
        <div class="compare-header">
          <el-button @click="exportCloudPdfFun">{{ $t('通用.导出PDF') }}</el-button>
        </div>
        <div class="compare-container compare-flex-item" ref="cloudCompareRef">
          <div class="compare-container-left">
            <BaseTable
              ref="tableComparePngRef"
              tableName="COMPARE_PNG"
              showIndex
              showCheckbox
              hidePagination
              @checkbox-change="checkBoxPngChangeFun"
              fullHeight
            >
              <template #leftOptions>
                <div class="compare-container-left-options">
                  <span>设置列数据：</span>
                  <el-input-number v-model="columnPngData" :min="1" :max="10" />
                </div>
              </template>
            </BaseTable>
          </div>
          <div class="compare-container-right">
            <div
              class="chart-container"
              :style="{
                // eslint-disable-next-line
                display: 'grid',
                gridTemplateColumns: `repeat(${columnPngData} ,${100 / columnPngData}%)`,
              }"
            >
              <div class="chart-box-png" v-for="(item, index) in comparePngData" :key="index">
                <div class="png-container">
                  <div class="png-title">{{ item.originalName }}</div>
                  <div class="png-image">
                    <el-image :src="item.url" fit="scale-down" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div>
          <el-button @click="closePngFun">关闭</el-button>
        </div>
      </template>
    </Dialog>
    <Dialog
      v-model="compareListVisible"
      diaTitle="已选数据列表"
      :width="'50%'"
      :height="'80%'"
      :confirm-closable="false"
      :zIndex="101"
      @close="closeCompareListFun"
    >
      <div class="compare-content">
        <BaseTable
          ref="compareTableRef"
          showIndex
          showCheckbox
          fullHeight
          table-name="DATA_COMPARE_POOL"
          :hide-pagination="true"
          :action-list="cmpareActionList"
          @checkbox-change="compareTableCheckboxChangeFun"
          @checkbox-all="compareTableCheckboxChangeFun"
        >
          <template #leftOptions>
            <el-button
              :disabled="!selectedDeleteRowsInCompareTable.length"
              @click="deleteMulcompareDataFun"
              >批量删除</el-button
            >
          </template>
        </BaseTable>
      </div>
    </Dialog>
    <taskDetail
      v-if="showTaskDetailDialog"
      :show-task-info="false"
      :taskId="currentTaskInfo.id"
      :currentTaskInfo="currentTaskInfo"
      :showApproval="false"
      :showFooter="false"
      :showLeftOptions="false"
      @closeFn="showTaskDetailDialog = false"
    />
    <runDetailPage
      v-if="showRunDetailDialog"
      :run-info="currentRunInfo"
      @close="showRunDetailDialog = false"
    />
    <analysisDataDialog
      v-if="loadcaseAnalysisVisable"
      @close="closeAnalysisFun"
      :analysis-data="selectAnalysisData"
    />
    <FilePreview v-model="previewVisible" :fileId="currentRow?.id" />
    <editPerformancePage
      v-if="showPerformanceInfoDialog"
      :performance-info="currentPerformance"
      :table-name="'SIMULATION_PERFORMANCE_ANALYSIS'"
      @cancel="showPerformanceInfoDialog = false"
      @submit="updatePerformanceFun"
    />
    <AnalysisDia v-model="showAnalysisDialog" :analysisData="compareList" />
    <PedigreeDialog
      v-model="pedigreeVisible"
      :rowData="currentPedigreeRow"
      :dataType="currentModel"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import BaseTable from '@/components/common/table/baseTable.vue';
import { queryNodeListApi, getChildrenDataListApi } from '@/api/project/node';
import {
  getSimulationTaskFileApi,
  getCSVDataApi,
  exportTaskFileByScriptApi,
} from '@/api/data/dataAnalysis';
import { NODE_TYPE } from '@/utils/enum/node';
import {
  getTaskListApi,
  getPerformanceListApi,
  getRunListApi,
  exportTaskByScriptApi,
  exportRunByScriptApi,
  exportPerformanceByScriptApi,
} from '@/api/project/analysis';
import { ElMessage } from 'element-plus';
import Dialog from '@/components/common/dialog/index.vue';
import EchartCard from '@/components/common/echartCard/index.vue';
import { groupBy } from 'lodash-es';
import analysisDataDialog from './components/analysisDataDialog.vue';
import taskDetail from '@/views/task/projectDetail/components/taskDetail.vue';
import FilePreview from '@/components/common/filePreview/index.vue';
import runDetailPage from '@/components/task/runDetailPage.vue';
import { useDict } from '@/utils/useDict';
import editPerformancePage from '@/components/taskDetail/editPerformancePage.vue';
import { editPerformanceApi } from '@/api/task/taskPerformance';
import StatusDot from '@/components/common/statusDot/index.vue';
import { statusMapFun5, statusMapFun6 } from '@/components/common/statusDot/statusMap';
import AnalysisDia from './components/analysisDia.vue';
import PedigreeDialog from './components/pedigree/pedigreeDialog.vue';
import { downloadFileById } from '@/utils/file';
import { exportToPdf } from '@/utils/exportPdf';
import dayjs from 'dayjs';

const { RESULT_ACHIEVE_STATUS, TASK_ACHIEVE_STATUS, PERFORMANCE_TYPE, PERFORMANCE_UNIT } = useDict(
  'RESULT_ACHIEVE_STATUS',
  'TASK_ACHIEVE_STATUS',
  'PERFORMANCE_UNIT',
  'PERFORMANCE_TYPE'
);
const { t } = useI18n();
const showTaskDetailDialog = ref(false);
const showRunDetailDialog = ref(false);
const showPerformanceInfoDialog = ref(false);
const showAnalysisDialog = ref(false);
const pedigreeVisible = ref(false);
const currentPedigreeRow = ref<any>({});

const tableRef = ref();

// 更新选中数据
const checkboxChangeFun = (data: any) => {
  if (data.checked) {
    compareList.value.push(data.row);
  } else {
    compareList.value = compareList.value.filter((item: any) => item.id !== data.row.id);
  }
};
const checkBoxAllChangeFun = (data: any) => {
  if (data.checked) {
    compareList.value = [...compareList.value, ...tableRef.value.tableData];
    // 根据id去重
    compareList.value = compareList.value.filter(
      (item: any, index: number, arr: any) => arr.findIndex((i: any) => i.id === item.id) === index
    );
  } else {
    compareList.value = compareList.value.filter((item: any) => {
      return !tableRef.value.tableData.some((i: any) => i.id === item.id);
    });
  }
};
const tableDataChangeFun = () => {
  nextTick(() => {
    const selectedKeys = compareList.value.map((item: any) => item.id);
    tableRef.value.tableRef.setCheckboxRowKey(selectedKeys, true); // 设置为选中
  });
};

const disabledStartDateFun = (time: any) => {
  const params = tableRef.value?.getSearchParamsFun();
  if (params.endTime) {
    const end = new Date(params.endTime).getTime();
    return time.getTime() > end;
  }
  return false;
};

const disabledEndDateFun = (time: any) => {
  const params = tableRef.value?.getSearchParamsFun();
  if (params.beginTime) {
    const start = new Date(params.beginTime).getTime();
    return time.getTime() < start;
  } else if (params.startTime) {
    const start = new Date(params.startTime).getTime();
    return time.getTime() < start;
  }
  return false;
};

// 处理查询接口信息
const calcUuidFromParams = (params: any) => {
  const levelOrder = [
    'projectNodeId',
    'phaseNodeId',
    'machineNodeId',
    'workspaceNodeId',
    'taskNodeId',
    'runId',
  ];
  let uuid = '';
  for (const key of levelOrder) {
    if (params[key]) {
      uuid = params[key];
    }
  }
  return uuid;
};

const getSimulationTaskFileFun = async (datas: any) => {
  const params = {
    ...datas,
    uuid: calcUuidFromParams(datas),
  };
  const res: any = await getSimulationTaskFileApi(params);
  return res;
};

const createFileExportParams = (model: string, fileBizType: number) => {
  return {
    model,
    fileBizType,
    get uuid() {
      const searchParams = tableRef.value?.getSearchParamsFun() || {};
      return calcUuidFromParams(searchParams);
    },
  };
};

const modelData = ref<any>({
  仿真任务: {
    tableName: 'SIMULATION_TASK_ANALYSIS',
    api: getTaskListApi,
    params: { model: '仿真任务' },
    exportApi: exportTaskByScriptApi,
    exportFileName: '仿真任务',
    exportParams: { model: '仿真任务' },
  },
  仿真算例: {
    tableName: 'SIMULATION_RUN_ANALYSIS',
    api: getRunListApi,
    params: { model: '仿真算例' },
    exportApi: exportRunByScriptApi,
    exportFileName: '仿真算例',
    exportParams: { model: '仿真算例' },
  },
  数据指标: {
    tableName: 'SIMULATION_PERFORMANCE_ANALYSIS',
    api: getPerformanceListApi,
    params: { model: '数据指标' },
    exportApi: exportPerformanceByScriptApi,
    exportFileName: '数据指标',
    exportParams: { model: '数据指标' },
  },
  模型文件: {
    tableName: 'RESULT_MODEL',
    api: getSimulationTaskFileFun,
    params: { model: '模型文件', fileBizType: 1 },
    exportApi: exportTaskFileByScriptApi,
    exportFileName: '模型文件',
    exportParams: createFileExportParams('模型文件', 1),
  },
  仿真报告: {
    tableName: 'RESULT_REPORT',
    api: getSimulationTaskFileFun,
    params: { model: '仿真报告', fileBizType: 2 },
    exportApi: exportTaskFileByScriptApi,
    exportFileName: '仿真报告',
    exportParams: createFileExportParams('仿真报告', 2),
  },
  计算文件: {
    tableName: 'RESULT_FILE',
    api: getSimulationTaskFileFun,
    params: { model: '计算文件', fileBizType: 3 },
    exportApi: exportTaskFileByScriptApi,
    exportFileName: '计算文件',
    exportParams: createFileExportParams('计算文件', 3),
  },
  结果曲线: {
    tableName: 'RESULT_CURVE',
    api: getSimulationTaskFileFun,
    params: { model: '结果曲线', fileBizType: 4 },
    exportApi: exportTaskFileByScriptApi,
    exportFileName: '结果曲线',
    exportParams: createFileExportParams('结果曲线', 4),
  },
  结果云图: {
    tableName: 'RESULT_PNG',
    api: getSimulationTaskFileFun,
    params: { model: '结果云图', fileBizType: 5 },
    exportApi: exportTaskFileByScriptApi,
    exportFileName: '结果云图',
    exportParams: createFileExportParams('结果云图', 5),
  },
});

const modeOptions = ref<any>([
  { label: '仿真任务', value: '仿真任务' },
  { label: '仿真算例', value: '仿真算例' },
  { label: '数据指标', value: '数据指标' },
  { label: '模型文件', value: '模型文件' },
  { label: '仿真报告', value: '仿真报告' },
  { label: '计算文件', value: '计算文件' },
  { label: '结果曲线', value: '结果曲线' },
  { label: '结果云图', value: '结果云图' },
]);

const currentPerformance = ref<any>({});
const actionList = ref<any>([]);
const compareList = ref<any[]>([]);

const modeChangeFun = () => {
  tableRef.value?.setSearchParamsFun({});
  const build: any = [];
  const actionData: any = [
    {
      id: 0,
      title: '详情',
      type: 'primary',
      click: (row: any) => {
        if (currentModel.value === '仿真任务') {
          showTaskDetailFun(row);
        }
        if (currentModel.value === '仿真算例') {
          showRunDetailFun(row);
        }
      },
    },
    {
      id: 1,
      title: '预览',
      type: 'primary',
      click: (row: any) => {
        previewFileFun(row);
      },
    },
    {
      id: 2,
      title: '预览',
      type: 'primary',
      click: (row: any) => {
        previewFileFun(row);
      },
    },
    {
      id: 5,
      title: t('通用.谱系'),
      type: 'primary',
      click: (row: any) => {
        if (!row.ownRunId && !row.runId) {
          ElMessage.warning('该数据暂无谱系信息');
          return;
        }
        currentPedigreeRow.value = row;
        pedigreeVisible.value = true;
      },
      hide: (row: any) => {
        return !row.ownRunId && !row.runId;
      },
    },
    {
      id: 3,
      title: '下载',
      type: 'primary',
      click: (row: any) => {
        downloadFileById(row.id);
      },
    },
    {
      id: 4,
      title: '编辑',
      type: 'primary',
      click: (row: any) => {
        currentPerformance.value = row;
        showPerformanceInfoDialog.value = true;
      },
    },
  ];
  actionData.forEach((item: any) => {
    if (item.id === 0 && ['仿真任务', '仿真算例'].includes(currentModel.value)) {
      build.push(item);
    }
    if (item.id === 1 && ['模型文件', '仿真报告', '结果云图'].includes(currentModel.value)) {
      build.push(item);
    }
    if (item.id === 2 && ['结果曲线'].includes(currentModel.value)) {
      build.push(item);
    }
    if (
      item.id === 3 &&
      ['模型文件', '仿真报告', '计算文件', '结果曲线', '结果云图'].includes(currentModel.value)
    ) {
      build.push(item);
    }
    if (item.id === 4 && ['数据指标'].includes(currentModel.value)) {
      build.push(item);
    }
    if (
      item.id === 5 &&
      ['模型文件', '仿真报告', '计算文件', '结果曲线', '结果云图'].includes(currentModel.value)
    ) {
      build.push(item);
    }
  });
  actionList.value = build;
  compareList.value = [];
};

const searchChangeFun = (searchData: any) => {
  const { key, val } = searchData;
  const searchParams = tableRef.value?.getSearchParamsFun();

  const clearChildOptions = (keys: string[]) => {
    keys.forEach((k) => {
      searchParams[k] = '';
      tableRef.value?.setOptionsFun(k, []);
    });
  };

  if (key === 'projectNodeId' || key === 'uuid') {
    if (val.uuid) {
      getChildNodeFun('phase');
    }
    clearChildOptions(['phaseNodeId', 'machineNodeId', 'workspaceNodeId', 'taskNodeId', 'runId']);
  }

  if (key === 'phaseNodeId') {
    if (val) {
      getChildNodeFun('machine');
      getChildNodeFun('workspace');
    }
    clearChildOptions(['machineNodeId', 'workspaceNodeId', 'taskNodeId', 'runId']);
  }

  if (key === 'machineNodeId') {
    if (val) {
      getChildNodeFun('workspace');
    }
    clearChildOptions(['workspaceNodeId', 'taskNodeId', 'runId']);
  }

  if (key === 'workspaceNodeId') {
    if (val) {
      getChildNodeFun('task');
    }
    clearChildOptions(['taskNodeId', 'runId']);
  }

  if (key === 'taskNodeId') {
    if (val) {
      getChildNodeFun('run');
    }
    clearChildOptions(['runId']);
  }
};

const getChildNodeFun = (nodeType: 'phase' | 'machine' | 'workspace' | 'task' | 'run') => {
  const searchParams = tableRef.value?.getSearchParamsFun() || {};
  const params: any = { nodeType };

  if (searchParams.projectNodeId) {
    params.projectNodeId = searchParams.projectNodeId;
  }
  if (nodeType !== 'phase' && searchParams.phaseNodeId) {
    params.phaseNodeId = searchParams.phaseNodeId;
  }
  if (!['phase', 'machine'].includes(nodeType) && searchParams.machineNodeId) {
    params.machineNodeId = searchParams.machineNodeId;
  }
  if (!['phase', 'machine', 'workspace'].includes(nodeType) && searchParams.workspaceNodeId) {
    params.workspaceNodeId = searchParams.workspaceNodeId;
  }
  if (nodeType === 'run' && searchParams.taskNodeId) {
    params.taskNodeId = searchParams.taskNodeId;
  }

  getChildrenDataListApi(params).then((res: any) => {
    if (res.code === 200) {
      const options = res.data.map((item: any) => ({
        label: item.nodeName || item.taskName || item.runName,
        value: item.uuid,
      }));

      if (nodeType === 'phase') {
        tableRef.value?.setOptionsFun('phaseNodeId', options);
      }
      if (nodeType === 'machine') {
        tableRef.value?.setOptionsFun('machineNodeId', options);
      }
      if (nodeType === 'workspace') {
        tableRef.value?.setOptionsFun('workspaceNodeId', options);
      }
      if (nodeType === 'task') {
        tableRef.value?.setOptionsFun('taskNodeId', options);
      }
      if (nodeType === 'run') {
        tableRef.value?.setOptionsFun('runId', options);
      }
    }
  });
};

const currentModel = ref('仿真任务');
modeChangeFun();

const projectOptions = ref<any[]>([]);

const getProjectOptionsFun = () => {
  queryNodeListApi({ current: 1, size: 999, nodeType: NODE_TYPE.PROJECT }).then((res: any) => {
    if (res.code === 200) {
      projectOptions.value = res.data.data.map((item: any) => {
        return {
          label: item.nodeName,
          value: item.uuid,
          uuid: item.uuid,
        };
      });
      tableRef.value?.setOptionsFun(NODE_TYPE.PROJECT, projectOptions.value);
    }
  });
};

const diaVisible = ref<boolean>(false);
const closeFun = () => {
  diaVisible.value = false;
};
const displayCompareFun = (flag: any) => {
  if (!compareList.value.length) {
    ElMessage.warning('请先加入对比池');
    return;
  }

  const data = compareList.value.map((item: any) => {
    return {
      ...item,
      name: item.originalName,
      imageNumber: 1,
    };
  });
  if (flag === '结果曲线') {
    diaVisible.value = true;
    nextTick(() => {
      tableCompareRef.value.setDataFun(data);
    });
  } else {
    diaPngVisible.value = true;
    nextTick(() => {
      tableComparePngRef.value.setDataFun(data);
    });
  }
};
const columnData = ref<number>(1);
const tableCompareRef = ref();
const compareData = ref<any>({});
const projectStorageSpaceStatisticsRef = ref<any>({});
// 初始化图表chart-1
const initProjectTaskAchievementStatistics = async ({
  dom,
  seriesData,
  XData,
  titleList,
  key,
}: any) => {
  dom.commonChartRef.disposeEchartsByKey('chart-' + key);
  dom.commonChartRef.option = {
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      top: '0%',
      left: 'center',
      data: titleList,
    },
    grid: {
      top: '10%',
      bottom: '10%',
      left: '5%',
      right: '5%',
    },
    xAxis: {
      type: 'value',
      // type: 'category',
      data: XData,
      axisLabel: {
        show: true,
        // interval: 9,
        interval: XData.length > 10 ? Math.floor(XData.length / 10) : 1,
      },
      splitLine: {
        show: true,
      },
      axisLine: {
        show: true,
      },
      axisTick: {
        show: true,
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
      },
      axisTick: {
        show: true,
      },
      minorTick: {
        show: true,
        splitNumber: 5, // 大刻度之间分割成5份
        length: 3, // 小刻度长度
      },
      minorSplitLine: {
        show: true,
        lineStyle: {
          type: 'dotted',
        },
      },
    },
    series: seriesData,
  };
  dom.commonChartRef.initChart();
};
const setChartFun = () => {
  const selectedRows = tableCompareRef.value?.tableRef?.getCheckboxRecords();
  if (selectedRows.length) {
    compareData.value = groupBy(selectedRows, 'imageNumber');
    nextTick(() => {
      for (const key in compareData.value) {
        getCSVDataApi({
          fileId: compareData.value[key].map((item: any) => item.id).join(','),
        }).then((res: any) => {
          const seriesData: any = [];
          const titleList: any = [];
          let XData: any = [];
          if (res.code === 200) {
            res.data.xData.forEach((item: any, index: number) => {
              const data = res.data.xData[index].map((item_1: any, index_1: number) => {
                return [item_1, res.data.yData[index][index_1]];
              });
              XData = res.data.xData[index].map((item: any) => {
                return item;
              });
              const title = compareData.value[key][index].originalName;
              titleList.push(title);
              seriesData.push({
                name: title,
                type: 'line',

                data,
                showSymbol: false, // 默认不显示数据点
                symbolSize: 6, // 悬停时数据点的大小
                itemStyle: {
                  opacity: 0, // 默认数据点透明度
                  borderWidth: 2,
                },
                emphasis: {
                  scale: true, // 悬停时放大
                  focus: 'series', // 悬停时高亮整个系列
                  itemStyle: {
                    opacity: 1, // 悬停时显示数据点
                  },
                },
              });
            });
          }

          initProjectTaskAchievementStatistics({
            dom: projectStorageSpaceStatisticsRef.value[`chart-${key}`],
            seriesData,
            XData,
            titleList,
            key,
          });
        });
      }
    });
  } else {
    compareData.value = [];
  }
};
const checkBoxChangeFun = () => {
  setChartFun();
};
const changeImageNumberFun = () => {
  setChartFun();
};
const tableComparePngRef = ref();

const diaPngVisible = ref<boolean>(false);
const columnPngData = ref<number>(1);
const comparePngData = ref<any>([]);
const closePngFun = () => {
  diaPngVisible.value = false;
};

const env = import.meta.env;
const checkBoxPngChangeFun = () => {
  comparePngData.value = tableComparePngRef.value?.tableRef?.getCheckboxRecords();
  comparePngData.value.forEach((item: any) => {
    item.url = `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${item.id}`;
  });
};

const loadcaseAnalysisVisable = ref(false);

const selectAnalysisData = ref<any>({});

const openDataAnalysisFun = (flag: any, tableName: any) => {
  selectAnalysisData.value = {
    flag,
    data: compareList.value,
    tableName,
  };
  loadcaseAnalysisVisable.value = true;
};

const closeAnalysisFun = () => {
  loadcaseAnalysisVisable.value = false;
};

const compareFun = (flag: any) => {
  if (!compareList.value.length) {
    ElMessage.warning('对比池为空，无法对比');
    return;
  }
  if (flag === '仿真任务') {
    openDataAnalysisFun(flag, 'SIMULATION_TASK_ANALYSIS_NO_SEARCH');
  }
  if (flag === '仿真算例') {
    openDataAnalysisFun(flag, 'SIMULATION_RUN_ANALYSIS_NO_SEARCH');
  }
  if (flag === '数据指标') {
    openDataAnalysisFun(flag, 'SIMULATION_PERFORMANCE_ANALYSIS_NO_SEARCH');
  }
  if (flag === '模型文件') {
    openDataAnalysisFun(flag, 'RESULT_MODEL_NO_SEARCH');
  }
  if (flag === '仿真报告') {
    openDataAnalysisFun(flag, 'RESULT_REPORT_NO_SEARCH');
  }
  if (flag === '计算文件') {
    openDataAnalysisFun(flag, 'RESULT_FILE_NO_SEARCH');
  }
  if (flag === '结果曲线') {
    displayCompareFun('结果曲线');
  }
  if (flag === '结果云图') {
    displayCompareFun('结果云图');
  }
};

const compareListVisible = ref(false);
const compareTableRef = ref();
// 查看对比池
const showCompareListFun = () => {
  for (let i = 0; i < compareList.value.length; i++) {
    let compareName: any = '';
    if (currentModel.value === '仿真任务') {
      compareName = compareList.value[i].taskName;
    } else if (currentModel.value === '仿真算例') {
      compareName = compareList.value[i].runName;
    } else if (currentModel.value === '数据指标') {
      compareName = compareList.value[i].performanceName;
    } else if (currentModel.value === '模型文件') {
      compareName = compareList.value[i].originalName;
    } else {
      compareName = compareList.value[i].fileName || compareList.value[i].originalName;
    }
    compareList.value[i].compareName = compareName;
    compareList.value[i].compareType = currentModel.value;
  }
  compareListVisible.value = true;
  nextTick(() => {
    compareTableRef.value?.setDataFun(compareList.value);
  });
};

const closeCompareListFun = () => {
  compareListVisible.value = false;
};

// 删除对比元素
const deleteCompareDataFun = (data: any) => {
  compareList.value = compareList.value.filter((item: any) => {
    return item.id != data.id;
  });
  tableRef.value?.tableRef?.clearCheckboxRow();
  tableDataChangeFun();
  // 弹窗表格数据更新
  nextTick(() => {
    compareTableRef.value?.setDataFun(compareList.value);
  });
};
const deleteMulcompareDataFun = () => {
  // 从compareList中删除selectedDeleteRowsInCompareTable中的元素
  selectedDeleteRowsInCompareTable.value.forEach((item: any) => {
    compareList.value = compareList.value.filter((compareItem: any) => {
      return compareItem.id != item.id;
    });
  });
  tableRef.value?.tableRef?.clearCheckboxRow();
  tableDataChangeFun();
  // 弹窗表格数据更新
  nextTick(() => {
    compareTableRef.value?.setDataFun(compareList.value);
  });
};
const selectedDeleteRowsInCompareTable = ref<any>([]);
const compareTableCheckboxChangeFun = () => {
  selectedDeleteRowsInCompareTable.value = compareTableRef.value?.tableRef?.getCheckboxRecords();
};

const currentTaskInfo = ref({ id: '', uuid: '' });
const showTaskDetailFun = (row: any) => {
  showTaskDetailDialog.value = true;
  currentTaskInfo.value = row;
};

const currentRunInfo = ref({ id: '', uuid: '' });
const showRunDetailFun = (row: any) => {
  showRunDetailDialog.value = true;
  currentRunInfo.value = row;
};

const currentRow = ref();
const previewVisible = ref(false);
const previewFileFun = (row: any) => {
  currentRow.value = row;
  previewVisible.value = true;
};

const updatePerformanceFun = async (data: any) => {
  showPerformanceInfoDialog.value = false;
  const res: any = await editPerformanceApi(data);
  if (res && res.code === 200) {
    ElMessage.success('操作成功');
    tableRef.value.getTableDataFun();
  }
};

const cmpareActionList = ref([
  {
    title: '删除',
    type: 'danger',
    click: (row: any) => {
      deleteCompareDataFun(row);
    },
  },
]);

onMounted(() => {
  getProjectOptionsFun();
});

const curveCompareRef = ref();
const exportCurvePdfFun = () => {
  ElMessage.success('文件正在导出，请稍后');
  exportToPdf(curveCompareRef.value, `结果曲线对比_${dayjs().format('YYYYMMDDHHmm')}`);
};

const cloudCompareRef = ref();
const exportCloudPdfFun = () => {
  ElMessage.success('文件正在导出，请稍后');
  exportToPdf(cloudCompareRef.value, `结果云图对比_${dayjs().format('YYYYMMDDHHmm')}`);
};
</script>

<style lang="scss" scoped>
.gl-page-content-full {
  .content {
    height: 100%;
  }
  .table {
    height: 100%;
    .options {
      display: flex;
      align-items: center;
      .chose-mode {
        width: 120px;
        margin-right: 12px;
      }
      .btn {
        position: relative;
        margin: 0 12px;
        .num {
          position: absolute;
          top: -5px;
          right: -5px;
          background-color: var(--el-color-error);
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 20px;
          min-width: 20px;
          border-radius: 10px;
          font-size: 12px;
        }
      }
    }
  }
}
.compare-container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  .compare-container-left {
    height: 100%;
    width: 49%;
    .compare-container-left-options {
      display: flex;
      align-items: center;
      & > span {
        white-space: nowrap;
      }
    }
  }
  .compare-container-right {
    height: 100%;
    width: 50%;
    .image-number-input {
      width: 30px;
    }
    .chart-container {
      height: 100%;
      width: 100%;
      // overflow-y: auto;
      // display: grid;
      .chart-box {
        height: 350px;
        width: 100%;
      }
      .chart-box-png {
        height: 50%;
        width: 100%;
        .png-container {
          height: 100%;
          width: 100%;
          display: flex;
          flex-direction: column;
          .png-title {
            margin-bottom: 12px;
            width: 100%;
          }
          .png-image {
            flex: 1;
            width: 100%;
            .el-image {
              height: 100%;
              width: 100%;
            }
          }
        }
      }
    }
  }
}

.compare-content {
  width: 100%;
  height: 100%;
}

.image-number-input {
  width: 50px;
}
.compare-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.compare-header {
  text-align: right;
  padding-bottom: 10px;
}
.compare-flex-item {
  height: 0;
  flex: 1;
}
</style>
