<!-- 关键结果 -->

<template>
  <div class="result-page">
    <div class="tab-title-box">
      <el-radio-group v-model="currentDirName" @change="runResultDirChangeFun">
        <el-radio v-for="item in runDirNameList" :key="item.id" :value="item.id">{{
          item.name
        }}</el-radio>
      </el-radio-group>
    </div>

    <div class="dir-content" v-if="currentDirName === 'performance'">
      <taskPerformance
        :full-height="true"
        :show-save-button="true"
        :param-type="'run'"
        :run-info="currentRunIfno"
      ></taskPerformance>
    </div>
    <div class="dir-content" v-else-if="runDirNameList.length && currentDirName">
      <BaseTable
        showIndex
        ref="baseTableRef"
        :tableName="tableName"
        :show-checkbox="true"
        :api="queryDirDataFun"
        :params="apiParam"
        :full-height="true"
        :action-list="actionList"
      >
        <template #leftOptions>
          <el-button @click="ArchiveRunDataFun">归档</el-button>
          <el-button type="primary" v-if="getdirNameFun() != '报告结果'" @click="viewFun"
            >查看</el-button
          >
          <el-button @click="openFun">上传文件</el-button>
          <!-- <el-upload :show-file-list="false" :before-upload="beforeUploadFun">
            <el-button>上传文件</el-button>
          </el-upload> -->
        </template>
      </BaseTable>
    </div>
    <FilePreview v-model="previewVisible" :fileId="currentRow?.fileId" />
  </div>
  <el-drawer
    v-model="visible"
    title="编辑文件"
    :size="600"
    :close-on-click-modal="false"
    @close="closeFun"
  >
    <TableForm
      ref="tableFormRef"
      :tableName="tableName"
      :show-disabled="currentFileInfo?.uuid || isCsv"
      @change="chnageFun"
    />
    <el-form :model="uploadFIleFormData" labelPosition="right" labelWidth="90">
      <el-form-item label="物理量" v-if="getdirNameFun() === '图片结果'">
        <el-select
          v-model="uploadFIleFormData.quantityType"
          filterable
          @change="getQuantityUnitFun('quantityType', 'unitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单位" v-if="getdirNameFun() === '图片结果'">
        <el-select v-model="uploadFIleFormData.units" filterable>
          <el-option
            v-for="item in uploadFIleFormData.unitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="x轴物理量" v-if="getdirNameFun() === '曲线结果'">
        <el-select
          v-model="uploadFIleFormData.xQuantityType"
          filterable
          @change="getQuantityUnitFun('xQuantityType', 'xUnitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="x轴结果单位" v-if="getdirNameFun() === '曲线结果'">
        <el-select v-model="uploadFIleFormData.xUnits" filterable>
          <el-option
            v-for="item in uploadFIleFormData.xUnitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="y轴物理量" v-if="getdirNameFun() === '曲线结果'">
        <el-select
          v-model="uploadFIleFormData.yQuantityType"
          filterable
          @change="getQuantityUnitFun('yQuantityType', 'yUnitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="y轴结果单位" v-if="getdirNameFun() === '曲线结果'">
        <el-select v-model="uploadFIleFormData.yUnits" filterable>
          <el-option
            v-for="item in uploadFIleFormData.yUnitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option> </el-select
      ></el-form-item>
      <el-form-item label="当前文件" v-if="fileList?.length">
        <div class="file-list">
          <div class="file-content" v-for="item in fileList" :key="item.id">
            <div class="file-name" :title="item.originalName">
              <el-icon class="icon-style"><Document /></el-icon> {{ item.originalName }}
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="closeFun">关闭</el-button>
        <el-button type="primary" @click="submitFun">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <Dialog
    v-model="diaPngVisible"
    diaTitle="云图对比"
    :width="'90%'"
    :height="'90%'"
    :confirm-closable="false"
    :zIndex="100"
  >
    <div class="compare-container">
      <div class="compare-container-left">
        <BaseTable
          ref="tableComparePngRef"
          tableName="RUN_RESULT_IMAGE_TABLE"
          showIndex
          showCheckbox
          hidePagination
          :full-height="true"
          @checkbox-change="checkBoxPngChangeFun"
        >
          <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.name }}</div>
              <div class="png-image">
                <el-image :src="item.url" fit="scale-down" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="closePngFun">关闭</el-button>
      </div>
    </template>
  </Dialog>

  <Dialog
    v-model="diaVisible"
    diaTitle="曲线对比"
    :width="'90%'"
    :height="'90%'"
    :confirm-closable="false"
    :zIndex="100"
  >
    <div class="compare-container">
      <div class="compare-container-left">
        <BaseTable
          ref="tableCompareRef"
          tableName="RUN_RESULT_CANVAS_TABLE"
          showIndex
          showCheckbox
          hidePagination
          @checkbox-change="checkBoxChangeFun"
          @checkbox-all="checkBoxChangeFun"
          :full-height="true"
        >
          <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"
          v-show="showChart"
          :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>
    <template #footer>
      <div>
        <el-button @click="canvasCloseFun">关闭</el-button>
      </div>
    </template>
  </Dialog>
  <Dialog
    v-model="uploadFileVisible"
    diaTitle="上传文件"
    :width="'70%'"
    :height="'70%'"
    :zIndex="101"
    @close="closeFun"
    show-footer
  >
    <BaseTable
      v-if="uploadFileVisible"
      :tableName="tableName"
      ref="baseUploadTableRef"
      :actionList="uploadActionList"
      :hidePagination="true"
      :full-height="true"
    >
      <template #leftOptions>
        <el-upload
          :show-file-list="false"
          :accept="accept"
          multiple
          :before-upload="beforeUploadFun"
        >
          <el-button>上传文件</el-button>
        </el-upload>
      </template>

      <template #quantityType="{ row }">
        <el-select
          v-model="row.quantityType"
          filterable
          @change="getQuantityUnitFun2(row, 'quantityType', 'unitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </template>
      <template #units="{ row }">
        <el-select v-model="row.units" filterable>
          <el-option
            v-for="item in row.unitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </template>
      <template #max="{ row }">
        <el-input v-model="row.max"></el-input>
      </template>
      <template #min="{ row }">
        <el-input v-model="row.min"></el-input>
      </template>
      <template #description="{ row }">
        <el-input v-model="row.description"></el-input>
      </template>
      <template #xQuantityType="{ row }">
        <el-select
          v-model="row.xQuantityType"
          filterable
          @change="getQuantityUnitFun2(row, 'xQuantityType', 'xUnitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </template>
      <template #xquantityType="{ row }">
        <el-select
          v-model="row.xquantityType"
          filterable
          @change="getQuantityUnitFun2(row, 'xquantityType', 'xunitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </template>
      <template #xUnits="{ row }">
        <el-select v-model="row.xUnits" filterable>
          <el-option
            v-for="item in row.xUnitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </template>
      <template #xunits="{ row }">
        <el-select v-model="row.xunits" filterable>
          <el-option
            v-for="item in row.xunitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </template>
      <template #yQuantityType="{ row }">
        <el-select
          v-model="row.yQuantityType"
          filterable
          @change="getQuantityUnitFun2(row, 'yQuantityType', 'yUnitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </template>
      <template #yquantityType="{ row }">
        <el-select
          v-model="row.yquantityType"
          filterable
          @change="getQuantityUnitFun2(row, 'yquantityType', 'yunitsList')"
        >
          <el-option
            v-for="item in quantityTypeList"
            :key="item.id"
            :label="item.label"
            :value="item.name"
          ></el-option>
        </el-select>
      </template>
      <template #yUnits="{ row }">
        <el-select v-model="row.yUnits" filterable>
          <el-option
            v-for="item in row.yUnitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </template>
      <template #yunits="{ row }">
        <el-select v-model="row.yunits" filterable>
          <el-option
            v-for="item in row.yunitsList"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          ></el-option>
        </el-select>
      </template>
    </BaseTable>

    <template #footer>
      <div>
        <el-button @click="closeFun">关闭</el-button>
        <el-button type="primary" @click="submitFun2">确定</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {
  queryRunDirApi,
  listSimulationKeyResultApi,
  addSimulationKeyResultApi,
  deleteSimulationKeyResultApi,
  editSimulationKeyResultApi,
  listQuantitiesApi,
  listUnitsApi,
  syncKeyResultToTaskApi,
} from '@/api/project/run';
import { ref, watch, nextTick, onMounted, reactive } from 'vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { ElMessage } from 'element-plus';
import { FILE_TYPE } from '@/utils/enum/file';
import TableForm from '@/components/common/table/tableForm.vue';
import FilePreview from '@/components/common/filePreview/index.vue';
import { downloadFileById } from '@/utils/file';
import Dialog from '@/components/common/dialog/index.vue';
import { groupBy } from 'lodash-es';
import { getFileBaseInfoApi } from '@/api/data/data';
import EchartCard from '@/components/common/echartCard/index.vue';
import taskPerformance from '@/components/taskDetail/taskPerformance.vue';
import { getCSVDataApi } from '@/api/data/dataAnalysis';

const env = import.meta.env;

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

const uploadFIleFormData = reactive<any>({
  quantityType: '',
  units: '',
  xQuantityType: '',
  xUnits: '',
  yQuantityType: '',
  yUnits: '',
});

const baseTableRef = ref();
const tableFormRef = ref();
const visible = ref(false);
const runInfo = ref<any>({});
const currentDirName = ref<any>();
const currentFileInfo = ref<any>({});
const diaPngVisible = ref(false);
const columnPngData = ref<number>(1);
const comparePngData = ref<any>([]);
const tableComparePngRef = ref();
const runDirs = ref<any>([]);
const runDirNameList = ref<any>([]);
const showPage = ref(false);
const diaVisible = ref(false);
const columnData = ref<number>(1);
const tableCompareRef = ref();
const isCsv = ref(false);
const uploadFileVisible = ref(false);
const baseUploadTableRef = ref();

const getRunInfoDirsFun = async () => {
  showPage.value = false;
  const res: any = await queryRunDirApi({
    uuid: runInfo.value.uuid,
    size: 10,
    current: 1,
  });
  if (res && res.code === 200) {
    runDirs.value =
      res.data?.data.filter((item: any) => {
        // '报告结果'
        return item.dataType === 1 && ['图片结果', '曲线结果'].includes(item.originalName);
      }) || [];
    runDirNameList.value =
      runDirs.value.map((item: any) => {
        return { name: item.originalName, id: item.id };
      }) || [];

    runDirNameList.value.unshift({
      name: '数值结果',
      id: 'performance',
    });

    if (runDirNameList.value.length) {
      currentDirName.value = runDirNameList.value[0].id;
    }
  }
  showPage.value = true;
};

const queryDirDataFun = async (param: any) => {
  const res: any = await listSimulationKeyResultApi({
    ...param,
  });
  if (res && res.code === 200) {
    return res;
  }
};

const apiParam = ref<any>({
  runId: '',
  keyResultType: '1',
});

const reloadFun = () => {
  if (baseTableRef.value) {
    baseTableRef.value.resetFun();
  }
};
const tableName = ref('RUN_RESULT_IMAGE_TABLE');

const fileType = ref(FILE_TYPE.PNG_FILE);
const runResultDirChangeFun = () => {
  const name = runDirNameList.value.find((item: any) => {
    return item.id === currentDirName.value;
  })?.name;

  if (name === '图片结果') {
    tableName.value = 'RUN_RESULT_IMAGE_TABLE';
    apiParam.value.keyResultType = '1';
    accept.value = '.jpg,.jpeg,.png,.gif';
    fileType.value = FILE_TYPE.PNG_FILE;
  }
  if (name === '曲线结果') {
    tableName.value = 'RUN_RESULT_CANVAS_TABLE';
    apiParam.value.keyResultType = '2';
    accept.value = '.csv';
    fileType.value = FILE_TYPE.CANVAS_FILE;
  }
  if (name === '报告结果') {
    tableName.value = 'RUN_RESULT_REPORT_TABLE';
    apiParam.value.keyResultType = '3';
    accept.value = '.ppt(x),.pptx,.doc(x),.docx,.pdf';
    fileType.value = FILE_TYPE.REPORT_FILE;
  }
};

const accept = ref<any>('.jpg,.jpeg,.png,.gif');
const getFileType = () => {
  let type: any = FILE_TYPE.CALCULATION_FILE;
  const dirName = runDirNameList.value.find((item: any) => {
    return item.id === currentDirName.value;
  })?.name;

  if (dirName === '图片结果') {
    type = FILE_TYPE.PNG_FILE;
  }

  if (dirName === '曲线结果') {
    type = FILE_TYPE.CANVAS_FILE;
  }

  if (dirName === '报告结果') {
    type = FILE_TYPE.REPORT_FILE;
  }

  return type;
};

const closeFun = () => {
  visible.value = false;
  isCsv.value = false;
  uploadFileVisible.value = false;
};

const openFun = () => {
  // visible.value = true;
  currentFileInfo.value = {};
  // nextTick(() => {
  //   tableFormRef.value.resetFun();

  //   for (const key in uploadFIleFormData) {
  //     uploadFIleFormData[key] = '';
  //   }
  // });
  tableData.value = [];
  uploadFileVisible.value = true;
};

const submitFun = async () => {
  if (currentFileInfo.value?.uuid) {
    const fromData = tableFormRef.value.getFormDataFun();
    const paramData: any = {};

    const fileList: any = fromData.uploadFile || [];

    if (fileList.length > 1) {
      ElMessage.warning('只允许更新一个文件!');
      return;
    }

    for (const key in fromData) {
      if (key != 'extras' && key != 'uploadFile' && key != 'X_ROW_KEY') {
        paramData[key] = fromData[key];
      }
    }

    for (const key in uploadFIleFormData) {
      if (!getparamListFUn().includes(key)) {
        delete uploadFIleFormData[key];
      }
    }

    const param = {
      ...paramData,
      ...uploadFIleFormData,
    };

    if (fileList.length) {
      const file = fromData.uploadFile[0].raw;

      // const name = file.name;
      // param.fileName = name;
      // param.name = name;
      // param.dirId = currentDirName.value;
      param.file = file;
      // param.fileType = getFileType();
      // param.keyResultType = keyResultType.value;
      // param.runId = runInfo.value.uuid;
      param.dirId = currentDirName.value;
    }

    param.quantityType = quantityTypeList.value.find((item: any) => {
      return item.name === uploadFIleFormData.quantityType;
    })?.label;
    param.xQuantityType = quantityTypeList.value.find((item: any) => {
      return item.name === uploadFIleFormData.xQuantityType;
    })?.label;
    param.yQuantityType = quantityTypeList.value.find((item: any) => {
      return item.name === uploadFIleFormData.yQuantityType;
    })?.label;
    param.xquantityType = param.xQuantityType;
    param.xunits = param.xUnits;
    param.yquantityType = param.yQuantityType;
    param.yunits = param.yUnits;

    delete param.xUnitsList;
    delete param.yunitsList;

    const res: any = await editSimulationKeyResultApi(param);
    if (res && res.code === 200) {
      ElMessage.success('操作成功');
      visible.value = false;
      reloadFun();
    }
  }

  isCsv.value = false;
};

const deleteFile = async (data: any) => {
  const res: any = await deleteSimulationKeyResultApi({
    uuid: data.uuid,
    fileId: data.fileId,
  });
  if (res && res.code === 200) {
    ElMessage.success('删除成功');
    reloadFun();
  } else {
    ElMessage.error('删除失败');
  }
};

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

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

const actionList = ref([
  {
    title: '编辑',
    type: 'primary',
    click: (row: any) => {
      visible.value = true;
      currentFileInfo.value = row;
      nextTick(async () => {
        tableFormRef.value.setFormDataFun(currentFileInfo.value);
        fileList.value = [];
        for (const key in uploadFIleFormData) {
          uploadFIleFormData[key] = currentFileInfo.value[key];
        }
        uploadFIleFormData.xQuantityType = currentFileInfo.value?.xquantityType;
        uploadFIleFormData.xUnits = currentFileInfo.value?.xunits;
        uploadFIleFormData.yQuantityType = currentFileInfo.value?.yquantityType;
        uploadFIleFormData.yUnits = currentFileInfo.value?.yunits;

        const res: any = await getFileBaseInfoApi({ fileId: row.fileId });
        if (res && res.code === 200) {
          fileList.value = [res.data];
        }
      });
    },
  },
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      previewFileFun(row);
    },
  },
  {
    title: '下载',
    type: 'primary',
    click: (row: any) => {
      downloadFileById(row.fileId);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '确认删除吗？',
    click: (row: any) => {
      deleteFile(row);
    },
  },
]);

const chnageFun = async (data: any) => {
  const name = runDirNameList.value.find((item: any) => {
    return item.id === currentDirName.value;
  })?.name;

  if (data.key === 'uploadFile' && name === '曲线结果') {
    isCsv.value = true;
    const file: any = data.val.raw;
    const { name } = file;
    const res: any = await addSimulationKeyResultApi({
      file,
      dirId: currentDirName.value,
      fileName: name,
      name: name,
      fileType: getFileType(),
      keyResultType: apiParam.value.keyResultType,
      runId: runInfo.value.uuid,
      onlyFile: true,
    });

    if (res && res.code === 200) {
      const fromData = tableFormRef.value.getFormDataFun();
      fromData.max = res.data.max;
      fromData.min = res.data.min;
      fromData.unit = res.data.unit;
    }
  }
};
const quantityTypeList = ref<any>([]);

const getQuantityTypeFun = async () => {
  const res: any = await listQuantitiesApi();
  if (res && res.code === 200) {
    quantityTypeList.value = res.data;
  }
};

const getQuantityUnitFun = async (name: any, flag: any) => {
  if (name) {
    const res: any = await listUnitsApi({ quantityType: uploadFIleFormData[name] });
    if (res && res.code === 200) {
      uploadFIleFormData[flag] = res.data;
    } else {
      uploadFIleFormData[flag] = [];
    }
  } else {
    uploadFIleFormData[flag] = [];
  }
};

const getQuantityUnitFun2 = async (row: any, name: any, flag: any) => {
  if (name) {
    const res: any = await listUnitsApi({ quantityType: row[name] });
    if (res && res.code === 200) {
      row[flag] = res.data;
    } else {
      row[flag] = [];
    }
  } else {
    row[flag] = [];
  }
};

const getdirNameFun = () => {
  const name: any = runDirNameList.value.find((item: any) => {
    return item.id === currentDirName.value;
  })?.name;

  return name;
};

const getparamListFUn = () => {
  const name = getdirNameFun();

  if (name === '图片结果') {
    return ['quantityType', 'units'];
  } else if (name === '曲线结果') {
    return ['xQuantityType', 'xUnits', 'yQuantityType', 'yUnits'];
  } else {
    return ['description'];
  }
};

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

const viewFun = () => {
  viewFiles.value = baseTableRef.value.tableRef.getCheckboxRecords();
  if (viewFiles.value.length) {
    const name = getdirNameFun();
    const data = viewFiles.value.map((item: any) => {
      return {
        ...item,
        imageNumber: 1,
      };
    });
    if (name === '图片结果') {
      diaPngVisible.value = true;

      nextTick(() => {
        tableComparePngRef.value.setDataFun(data);
      });
    } else if (name === '曲线结果') {
      diaVisible.value = true;
      nextTick(() => {
        tableCompareRef.value.setDataFun(data);
      });
    }
  } else {
    ElMessage.warning('请选择文件进行对比查看');
  }
};

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.fileId}`;
  });
};

const closePngFun = () => {
  diaPngVisible.value = false;
};

const canvasCloseFun = () => {
  diaVisible.value = false;
  showChart.value = false;
};

const showChart = ref(false);
const changeImageNumberFun = () => {
  setChartFun();
};
const checkBoxChangeFun = () => {
  setChartFun();
};
const compareData = ref<any>({});
const projectStorageSpaceStatisticsRef = ref<any>({});
// 初始化图表chart-1
const initProjectTaskAchievementStatistics = async ({ dom, seriesData, 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: 'category',
    },
    yAxis: {
      type: 'value',
    },
    series: seriesData,
  };
  dom.commonChartRef.initChart();
};

const setChartFun = () => {
  const selectedRows = tableCompareRef.value?.tableRef?.getCheckboxRecords();
  if (selectedRows.length) {
    showChart.value = true;
  } else {
    showChart.value = false;
  }
  if (selectedRows.length) {
    compareData.value = groupBy(selectedRows, 'imageNumber');
    nextTick(() => {
      for (const key in compareData.value) {
        getCSVDataApi({
          fileId: compareData.value[key].map((item: any) => item.fileId).join(','),
        }).then((res: any) => {
          const seriesData: any = [];
          const titleList: 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]];
              });
              const title = compareData.value[key][index].name;
              titleList.push(title);
              seriesData.push({
                name: title,
                type: 'line',
                stack: 'Total',
                data,
              });
            });
          }

          initProjectTaskAchievementStatistics({
            dom: projectStorageSpaceStatisticsRef.value[`chart-${key}`],
            seriesData,
            titleList,
            key,
          });
        });
      }
    });
  }
};

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

const uploadActionList = ref([
  {
    title: '删除',
    type: 'danger',
    click: (row: any) => {
      tableData.value = tableData.value.filter((item: any) => {
        return item.id != row.id;
      });

      baseUploadTableRef.value.setDataFun(tableData.value);
    },
  },
]);

const num = ref(1);
const beforeUploadFun = async (file: any) => {
  num.value++;
  const { name, size } = file;

  const obj: any = {
    name: name,
    fileName: name,
    fileSize: size,
    size,
    file,
    id: new Date().getTime() + num.value,
    quantityType: '',
    units: '',
    max: '',
    min: '',
    description: '',
    xQuantityType: '',
    xquantityType: '',
    xUnits: '',
    xunits: '',
    yQuantityType: '',
    yquantityType: '',
    yUnits: '',
    yunits: '',
    fileType: fileType.value,
    keyResultType: apiParam.value.keyResultType,
  };

  if (getdirNameFun() === '曲线结果') {
    const res: any = await addSimulationKeyResultApi({
      file,
      dirId: currentDirName.value,
      fileName: name,
      name: name,
      fileType: getFileType(),
      keyResultType: apiParam.value.keyResultType,
      runId: runInfo.value.uuid,
      onlyFile: true,
    });

    if (res && res.code === 200) {
      obj.xQuantityType = res.data.xPhysics;
      obj.xquantityType = res.data.xPhysics;
      obj.yQuantityType = res.data.yPhysics;
      obj.yquantityType = res.data.yPhysics;
      obj.max = res.data.max;
      obj.min = res.data.min;
      obj.xUnits = res.data.xUnit;
      obj.xunits = res.data.xUnit;
      obj.yUnits = res.data.yUnit;
      obj.yunits = res.data.yUnit;
    }
  }

  tableData.value.push(obj);

  nextTick(() => {
    baseUploadTableRef.value.setDataFun(tableData.value);
  });
};

const submitFun2 = async () => {
  let isSubmit: any = true;
  for (let i = 0; i < tableData.value.length; i++) {
    const file = tableData.value[i].file;
    const name = file.name;
    const paramData: any = {};

    for (const key in tableData.value[i]) {
      if (key != '_X_ROW_KEY' && key != 'unitsList') {
        paramData[key] = tableData.value[i][key];
      }
    }

    const params: any = {
      fileName: name,
      name: name,
      dirId: currentDirName.value,
      file: file,
      fileType: getFileType(),
      keyResultType: apiParam.value.keyResultType,
      runId: runInfo.value.uuid,
      ...paramData,
    };

    const paramQuantityType = quantityTypeList.value.find((item: any) => {
      return item.name === tableData.value[i].quantityType;
    })?.label;

    const paramXQuantityType = quantityTypeList.value.find((item: any) => {
      return item.name === tableData.value[i].xQuantityType;
    })?.label;

    const paramYQuantityType = quantityTypeList.value.find((item: any) => {
      return item.name === tableData.value[i].yQuantityType;
    })?.label;

    if (paramQuantityType) {
      params.quantityType = paramQuantityType;
    }
    if (paramXQuantityType) {
      params.xQuantityType = paramXQuantityType;
    }
    if (paramYQuantityType) {
      params.yQuantityType = paramYQuantityType;
    }

    delete params.xUnitsList;
    delete params.yunitsList;
    delete params.xunitsList;

    console.log(params, 'params');

    await addSimulationKeyResultApi(params).then((res: any) => {
      if (res.code === 200) {
      } else {
        isSubmit = false;
      }
    });
  }

  if (isSubmit) {
    ElMessage.success('上传成功');
    reloadFun();
  }

  uploadFileVisible.value = false;
};

const ArchiveRunDataFun = async () => {
  const list = baseTableRef.value.tableRef?.getCheckboxRecords() || [];
  if (list.length) {
    const keyResultIdList = list.map((item: any) => {
      return item.uuid;
    });

    const param = {
      keyResultIdList,
      runId: props.currentRunIfno.uuid,
    };

    try {
      const res: any = await syncKeyResultToTaskApi(param);
      if (res && res.code === 200) {
        ElMessage.success('归档成功');
      } else {
        ElMessage.warning('归档未成功');
      }
    } catch (error) {
      console.error(error);
    }
  } else {
    ElMessage.warning('请选择文件进行归档');
  }
};

watch(
  () => props.currentRunIfno,
  async (newVal) => {
    if (newVal) {
      runInfo.value = newVal;
      apiParam.value.runId = runInfo.value.uuid;
      nextTick(async () => {
        await getRunInfoDirsFun();
      });
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(async () => {
  await getQuantityTypeFun();
});
</script>

<style lang="scss" scoped>
.result-page {
  width: 100%;
  height: 100%;

  .tab-title-box {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .dir-content {
    width: 100%;
    height: calc(100% - 50px);
  }
}
:deep(.el-form-item__label) {
  width: 90px !important;
}

.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: 50px;
    }
    .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%;
            }
          }
        }
      }
    }
  }
}

.file-list {
  width: 100%;

  .file-content {
    width: 100%;
    height: 32px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .file-name {
      width: 80%;
      display: flex;
      align-items: center;
      text-overflow: ellipsis;
      /* 当内容溢出容器时显示省略号 */
      overflow: hidden;
      /* 隐藏溢出容器的内容 */
      white-space: nowrap;
      color: #606266;

      .icon-style {
        margin-right: 5px;
        color: #606266;
      }
    }

    .file-operate {
      display: none;
      cursor: pointer;
      padding-right: 10px;
    }
  }

  .file-content:hover {
    background-color: #f5f7fa;

    .file-operate {
      display: block;
    }
  }
}
</style>
