<template>
  <Dialog
    v-model="visible"
    diaTitle="生成报告"
    :width="'80%'"
    :height="'80%'"
    @close="handleCloseFun"
  >
    <div class="page-content">
      <el-form>
        <el-form-item label="图片选择：">
          <div class="img-content">
            <template v-for="item in resultImgList" :key="item.id">
              <div class="img-item" v-if="item.show">
                <el-checkbox v-model="item.checkImg" class="check-style" size="large" />
                <!-- :preview-src-list="[item.url]" -->
                <el-image
                  class="img-style"
                  title="点击预览图片"
                  :src="item.url"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  show-progress
                  :initial-index="4"
                  fit="cover"
                  :preview-src-list="[item.url]"
                />
              </div>
            </template>
          </div>
        </el-form-item>
        <el-form-item label="云图选择：">
          <div class="img-content">
            <div class="csv-content" v-for="item in resultCsvList" :key="item.fileId">
              <div class="csv-content-chart" :id="`chart_${item.fileId}`">
                <EchartCard
                  title=""
                  :ref="(el) => (projectStorageSpaceStatisticsRef[`chart-${item.fileId}`] = el)"
                  :charts-id="'chart-' + item.fileId"
                  :bar-type="'lineChart'"
                >
                </EchartCard>
              </div>
              <div class="csv-content-name">
                <el-checkbox v-model="item.check" :label="item.name" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="指标选择：">
          <taskPerformance
            ref="taskPerformanceRef"
            :task-info="runIfno"
            :run-info="runIfno"
            :param-type="'run'"
          ></taskPerformance>
        </el-form-item>
        <el-form-item label="结论建议：">
          <el-input v-model="formData.conclusion" type="textarea"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseFun">取消</el-button>
        <el-button type="primary" @click="createSuccessFun" :disabled="isLoading">确认</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import { cloneDeep } from 'lodash-es';
import { getUserData } from '@/utils/user';
import dayjs from 'dayjs';
import taskPerformance from '@/components/taskDetail/taskPerformance.vue';
import { generateNewReportApi, listSimulationKeyResultApi } from '@/api/project/run';
import EchartCard from '@/components/common/echartCard/index.vue';
import { getCSVDataApi } from '@/api/data/dataAnalysis';
import html2canvas from 'html2canvas';
import { dataUploadAvatarApi } from '@/api/data/data';
import { ElMessage } from 'element-plus';

const props = defineProps({
  runIfno: {
    type: Object,
    default: () => {},
  },
});
const emits = defineEmits(['close']);
const visible = ref(true);
const taskPerformanceRef = ref();
const env = import.meta.env;

const formData = reactive<any>({
  Project: '',
  Phase: '',
  Task: '',
  UserName: '',
  Date: '',
  conclusion: '',
});
const runData = ref<any>({});
const selectImg = ref<any>({
  key: '云图',
  type: 'img',
  value: [],
});
const selectCsv = ref<any>({
  key: '曲线图',
  type: 'img',
  value: [],
});
const tableData = ref<any>({
  type: 'table',
  key: '数值结果表',
  value: [],
  head: ['序号', '指标名称', '指标编号', '分析值', '达标方式', '目标值', '单位'],
});
const tableData2 = ref<any>({
  type: 'table',
  key: '仿真参数表',
  value: [],
  head: ['序号', '状态类别', '详细描述'],
});

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

const isLoading = ref(false);
const createSuccessFun = async () => {
  const list: any = [];
  isLoading.value = true;
  ElMessage.success('报告生成中。。。');
  for (const key in formData) {
    list.push({
      key,
      type: 'text',
      value: formData[key],
    });
  }
  list.push(tableData2.value);
  tableDataFun(list);
  selectImgFun(list);
  await selectCsvFun(list);

  const params = {
    runId: props.runIfno.uuid,
    reportContent: JSON.stringify(list),
    fileName: '算例报告_' + dayjs().format('YYYY_MM_DD') + '.docx',
  };

  try {
    const res: any = await generateNewReportApi(params);
    if (res && res.code === 200) {
      ElMessage.success('导出成功');
      isLoading.value = false;
    }
  } catch {
    ElMessage.warning('导出失败');
    isLoading.value = false;
  }

  console.log(list, 'listlist');
};

const selectCsvFun = async (list: any) => {
  selectCsv.value.value = [];
  const csvs = resultCsvList.value.filter((item: any) => {
    return item.check;
  });

  for (let i = 0; i < csvs.length; i++) {
    const obj: any = {
      title: csvs[i].name,
      path: await updatePngFun(`chart_${csvs[i].fileId}`),
    };
    selectCsv.value.value.push(obj);
  }

  list.push(selectCsv.value);
};

const selectImgFun = (list: any) => {
  selectImg.value.value = [];
  const imgs = resultImgList.value.filter((item: any) => {
    return item.checkImg;
  });

  selectImg.value.value = imgs.map((item: any) => {
    return {
      title: item.name,
      path: item.fileId,
    };
  });

  list.push(selectImg.value);
};

const tableDataFun = (list: any) => {
  tableData.value.value = [];
  const perofrmances = taskPerformanceRef.value.baseTableRef.tableRef.getCheckboxRecords() || [];

  for (let i = 0; i < perofrmances.length; i++) {
    const obj = {
      index: i + 1,
      nodeName: perofrmances[i].nodeName,
      nodeCode: perofrmances[i].nodeCode,
      targetValue: perofrmances[i].targetValue,
      method: perofrmances[i].method,
      highValue: perofrmances[i].highValue,
      unit: perofrmances[i].unit,
    };
    tableData.value.value.push(obj);
  }

  list.push(tableData.value);
};

const resultImgList = ref<any>([]);
const queryDirDataFun = async (run: any) => {
  const res: any = await listSimulationKeyResultApi({
    keyResultType: '1',
    runId: run?.uuid,
    current: 1,
    size: 999,
  });
  if (res && res.code === 200) {
    resultImgList.value = res.data.data.map((item: any) => {
      return {
        ...item,
        url: `${env.VITE_API_IMAGE_PREVIEW_URL}/data/previewImage?fileId=${item.fileId}`,
      };
    });

    showIMgFileList();
  }
};

const showIMgFileList = () => {
  for (let i = 0; i < resultImgList.value.length; i++) {
    resultImgList.value[i].checkImg = false;
    resultImgList.value[i].show = true;
  }
};

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

const getCsvFileList = async (run: any) => {
  const res: any = await listSimulationKeyResultApi({
    keyResultType: '2',
    runId: run?.uuid,
    current: 1,
    size: 999,
  });

  if (res && res.code === 200) {
    resultCsvList.value = res.data.data;

    setChartFun();
  }
};

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 = resultCsvList.value;

  if (selectedRows.length) {
    nextTick(() => {
      for (let i = 0; i < selectedRows.length; i++) {
        getCSVDataApi({
          fileId: selectedRows[i].fileId,
        }).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 = selectedRows[i].name;
              titleList.push(title);
              seriesData.push({
                name: title,
                type: 'line',
                stack: 'Total',
                data,
              });
            });
          }

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

const updatePngFun = async (id: any) => {
  try {
    const content = document.getElementById(id) as HTMLElement;
    const canvas = await html2canvas(content);
    const imgData = canvas.toDataURL('image/png');
    // 将DataURL转换为Blob对象
    const blob: any = await new Promise((resolve) => {
      const byteString = atob(imgData.split(',')[1]);
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      resolve(new Blob([ab], { type: 'image/png' }));
    });
    const file = new File([blob], name + '.png', { type: 'image/png' });
    const params = {
      avatar: file,
    };
    let avatarId: any = '';
    const res: any = await dataUploadAvatarApi(params);
    if (res && res.code === 200) {
      avatarId = res.data.avatarId;
    }
    return avatarId;
  } catch (error) {
    console.error(error);
    return '';
  }
};

watch(
  () => props.runIfno,
  async (newVal) => {
    if (newVal) {
      const projectInfo = JSON.parse(
        localStorage.getItem('CURRENT_FILTER_RUN_TASK_TREE_PARAM') as string
      );
      runData.value = cloneDeep(newVal);
      formData.Project = projectInfo.projectCodeName;
      formData.Phase = projectInfo.phaseCodeName;
      formData.Task = runData.value.parentName;
      formData.UserName = await getUserData().nickname;
      formData.Date = dayjs().format('YYYY 年 MM 月 DD');
      await queryDirDataFun(runData.value);
      await getCsvFileList(runData.value);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

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

  .el-form {
    width: 100%;
  }

  .img-content {
    width: 100%;
    min-height: 200px;
    padding: 5px;
    display: flex;
    flex-wrap: wrap;

    .img-item {
      width: 150px;
      height: 150px;
      margin-right: 20px;
      margin-bottom: 20px;
      position: relative;
      box-sizing: content-box;
      border: 1px dashed var(--el-color-primary);

      .check-style {
        position: absolute;
        top: 0px;
        left: 5px;
      }

      .img-style {
        width: 150px;
        height: 150px;
      }
    }

    .csv-content {
      width: 250px;
      margin-right: 10px;
      margin-bottom: 10px;

      .csv-content-chart {
        width: 100%;
        height: 250px;
        background-color: saddlebrown;
      }
      .csv-content-name {
        width: 100%;
        // height: calc(100% - 200px);
        min-height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
