<template>
  <div class="task-performance-page">
    <div class="task-curve-page-left">
      <BaseTable
        tableName="TASK_CANVAS_FILE"
        ref="baseTableRef"
        :api="getSimulationTaskFilesApi"
        :params="apiParam"
        :show-checkbox="true"
        :full-height="true"
        :actionList="actionList"
      >
        <template v-if="showLeftOptions" #leftOptions>
          <el-upload
            :show-file-list="false"
            :accept="accept"
            multiple
            :before-upload="beforeUploadFun"
          >
            <el-button>上传文件</el-button>
          </el-upload>
          <el-button class="ml12" type="primary" @click="showTableDataCurveFun">显示曲线</el-button>
          <el-button type="primary" @click="downLoadFun">下载文件</el-button>
        </template>
        <template #type="{ row }">
          <span>{{ getfileType(row) }}</span>
        </template>
        <template #fileSize="{ row }">
          <span>{{ row.formatFileSize }}</span>
        </template>
        <!-- <template #num="{ row, column }">
          图 <el-input class="w50" v-model="row[column.field]"></el-input>
        </template> -->
      </BaseTable>
    </div>
    <div class="task-curve-page-right" v-if="showCsv">
      <div class="task-curve-right-operate">
        <span>列数：</span>
        <el-input
          class="input-style"
          size="small"
          v-model="filterForm.lineNum"
          @change="handleChangeNumFun"
        />
      </div>

      <div class="task-curve-right-content">
        <div
          class="img-item"
          :style="{
            width: `calc((100% / ${filterForm.lineNum}) - 20px)`,
            height: `calc((100% / ${filterForm.lineNum}) - 20px)`,
          }"
          v-for="item in curveNumData"
          :key="item"
        >
          <!-- <img class="task-img" :src="item.url" alt=""> -->
          <div class="task-img" :id="'chart_' + item"></div>
          <div class="img-title">{{ '图' + item }}</div>
        </div>
      </div>
    </div>
    <FilePreview v-model="previewVisible" :fileId="currentRow?.id" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { batchAddFileInfoApi } from '@/api/data/data';
import { initEcharts } from '../common/echartCard/echartsOptions';
import { FILE_TYPE } from '@/utils/enum/file';
import BaseTable from '@/components/common/table/baseTable.vue';
import {
  downloadFileById,
  downloadFileByStream,
  getFileUploadAcceptFun,
  queryFileIdByNodeIdFun,
} from '@/utils/file';
import { dataOverViewDeleteSimulationNodeFilesApi } from '@/api/data/dataOverView';
import FilePreview from '@/components/common/filePreview/index.vue';
import emitter from '@/utils/eventBus';
import { getCSVDataApi, getSimulationTaskFilesApi } from '@/api/data/dataAnalysis';
import { NODE_TYPE } from '@/utils/enum/node';

const props = defineProps({
  taskId: {
    type: String,
    default: '',
  },
  showLeftOptions: {
    type: Boolean,
    default: true,
  },
});
const runTreeData = ref<any>([]);
const curveList = ref<any>([]);
const baseTableRef = ref();
const showCsv = ref(false);
const nodeFIleId = ref<any>('');
const accept = ref<any>('');
const filterForm = reactive<any>({
  lineNum: 2,
});

const getTaskRunDataFun = () => {
  runTreeData.value = [
    {
      label: '当前任务',
      id: props.taskId,
      // disabled: true,
      children: [],
    },
  ];
};

const getfileType = (data: any) => {
  const fileType = data.originalName.split('.').pop();
  return fileType;
};

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

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

const actionList = ref([
  {
    title: '下载',
    type: 'primary',
    click: (row: any) => {
      downloadFileById(row.id);
    },
  },
  {
    title: '预览',
    type: 'primary',
    click: (row: any) => {
      previewFileFun(row);
    },
  },
  {
    title: '删除',
    type: 'danger',
    needConfirm: true,
    confirmTip: '删除后不可恢复，确认删除吗？',
    click: (row: any) => {
      deleteFun(row);
    },
    hide: () => {
      return !props.showLeftOptions;
    },
  },
]);

const deleteFun = async (row: any) => {
  const param = {
    deleteId: row.id,
    dataType: 2,
  };

  try {
    const res: any = await dataOverViewDeleteSimulationNodeFilesApi(param);
    if (res && res.code === 200) {
      baseTableRef.value.resetFun();
    }
  } catch {}
};

const showTableDataCurveFun = () => {
  showCsv.value = false;
  const { tableData } = baseTableRef.value.tableRef.getTableData();

  curveList.value = tableData.map((item: any, index: any) => {
    return {
      ...item,
      num: index + 1,
    };
  });

  curveList.value = curveList.value.filter((item: any) => {
    return item.originalName.endsWith('.csv');
  });

  if (curveList.value.length) {
    showCsv.value = true;
    const list = curveList.value.map((item: any) => item.num);
    curveNumData.value = Array.from(new Set(list));
    getCommonNumCurveFun();
  }
};

const handleChangeNumFun = () => {
  const list = curveList.value.map((item: any) => Number(item.num));
  curveNumData.value = Array.from(new Set(list));

  getCommonNumCurveFun();
};

const curveTypeData = ref<any>([]);
const getCommonNumCurveFun = async () => {
  curveTypeData.value = [];
  const list = curveList.value.map((item: any) => Number(item.num));
  curveNumData.value = Array.from(new Set(list));

  for (let i = 0; i < curveNumData.value.length; i++) {
    const arr: any = [];
    for (let j = 0; j < curveList.value.length; j++) {
      if (curveNumData.value[i] === Number(curveList.value[j].num)) {
        arr.push(curveList.value[j]);
      }
    }
    curveTypeData.value.push({ num: curveNumData.value[i], data: arr });
  }

  for (let i = 0; i < curveTypeData.value.length; i++) {
    await getCSVDataFun(curveTypeData.value[i].data, curveTypeData.value[i].num);
  }
};

const getCSVDataFun = async (data: any, num: any) => {
  const ids = data
    .map((item: any) => {
      return item.id;
    })
    .join(',');
  const res: any = await getCSVDataApi({ fileId: ids });
  if (res && res.code === 200) {
    getCsvFormatDataFun(res.data, num);
  }
};

// 获取csv数据并转换为图表数据
const getCsvFormatDataFun = (data: any, num: any) => {
  const selectDatas = curveTypeData.value.find((item: any) => {
    return item.num === num;
  });
  const title = selectDatas.data.map((item: any) => item.originalName);

  const seriesData: any = [];

  for (let i = 0; i < data.xData.length; i++) {
    const obj: any = {
      name: title[i],
      type: 'line',
      showSymbol: false,
      smooth: true,
      clip: true,
    };
    const newArr: any = [];
    for (let j = 0; j < data.xData[i].length; j++) {
      newArr.push([data.xData[i][j], data.yData[i][j]]);
    }
    obj.data = newArr;
    seriesData.push(obj);
  }

  const options: any = {
    series: seriesData,
    legend: {
      data: title,
      top: '5%',
    },
    grid: {
      top: '8%',
      bottom: '5%',
      left: '5%',
      righ: '5%',
    },
    xAxis: {
      name: 'x',
      minorTick: {
        show: true,
      },
      minorSplitLine: {
        show: true,
      },
    },
    yAxis: {
      name: 'y',
      minorTick: {
        show: true,
      },
      minorSplitLine: {
        show: true,
      },
    },
  };

  const elementId = 'chart_' + num;
  initEcharts(elementId, elementId, 'lineChart', options);
};

const beforeUploadFun = async (file: any) => {
  // const { name } = file;
  // const params = {
  //   fileName: name,
  //   dirId: nodeFIleId.value,
  //   file: file,
  //   fileType: FILE_TYPE.CANVAS_FILE,
  // };

  // dataOverViewUploadSimulationNodeFilesApi(params).then((res: any) => {
  //   if (res.code === 200) {
  //     ElMessage.success('上传成功');
  //     baseTableRef.value.resetFun();
  //   }
  // });

  const { name, size } = file;

  const sourceFiles = [
    {
      fileName: name,
      size: size,
      raw: file,
      fileType: FILE_TYPE.CANVAS_FILE,
    },
  ];

  const params = {
    sourceFiles,
    uploadTaskId: new Date().getTime(),
    dirId: nodeFIleId.value,
    projectId: null,
    type: 0,
  };

  await batchAddFileInfoApi(params).then((res: any) => {
    if (res.code === 200) {
      baseTableRef.value.resetFun();
      res.data.forEach((item: any) => {
        emitter.emit('ADD_UPLOAD_FILE', {
          file: file,
          data: {
            ...item,
            isApprove: 0,
            taskType: 1,
          },
        });
      });
    }
  });

  return false;
};

const downLoadFun = async () => {
  const data: any = baseTableRef.value.tableRef.getCheckboxRecords() || [];
  if (data.length) {
    for (let i = 0; i < data.length; i++) {
      downloadFileByStream(data[i].id);
    }
  }
};

const apiParam = ref<any>({});
watch(
  () => props.taskId,
  (newVal) => {
    if (newVal) {
      apiParam.value = {
        uuid: newVal,
        fileBizType: FILE_TYPE.CANVAS_FILE,
        fileName: '',
        startTime: '',
        endTime: '',
        type: NODE_TYPE.TASK,
      };
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(async () => {
  getTaskRunDataFun();
  accept.value = await getFileUploadAcceptFun('CANVAS_FILE_FORMAT');
  nodeFIleId.value = await queryFileIdByNodeIdFun(props.taskId);
});
</script>

<style lang="scss" scoped>
.task-performance-page {
  width: 100%;
  height: 100%;
  overflow: auto;
  // display: flex;
  // align-items: center;
  // justify-content: space-between;

  // :deep(.is-disabled) {
  //   display: none;
  // }

  .task-curve-page-left {
    width: 100%;
    // height: 400px;
    height: 100%;
    overflow: auto;

    .task-run-box {
      width: 100%;
      height: 200px;
      margin-bottom: 10px;
      overflow: auto;
    }

    .task-curve-box {
      width: 100%;
      height: calc(100% - 210px);

      .current-box-title {
        width: 100%;
        height: 30px;
        display: flex;
        align-items: center;
        padding-left: 10px;
      }

      .curve-list {
        width: 100%;
        height: calc(100% - 30px);
        padding-left: 40px;
        overflow: auto;

        .curve-list-item {
          width: 100%;
          height: 30px;
          background-color: white;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }

  .task-curve-page-right {
    // width: calc(65% - 10px);
    width: 100%;
    height: 100%;
    padding-left: 20px;

    .task-curve-right-operate {
      width: 100%;
      height: 40px;

      display: flex;
      align-items: center;
    }

    .task-curve-right-content {
      width: 100%;
      height: calc(100% - 50px);
      display: flex;
      flex-wrap: wrap;
      overflow: auto;

      .img-item {
        margin-right: 10px;
        margin-bottom: 10px;
        min-height: 100px;

        .task-img {
          width: 100%;
          height: 100%;
          border: 1px solid #ddd;
        }

        .img-title {
          width: 100%;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .input-style {
    width: 50px;
    margin-left: 5px;
    margin-right: 10px;
  }

  .w50 {
    width: 50px;
  }

  .ml12 {
    margin-left: 12px;
  }
}
</style>
