<!--
 * @Author: your name
 * @Date: 2025-01-09 18:10:08
 * @LastEditTime: 2025-02-13 11:21:00
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/overview/components/power_curve/index.vue
-->

<template>
  <div class="type-variable">
    <!-- 有功功率曲线分析 -->
    <div class="left">
      <FilterChart
        :windList="windEngineGroupList"
        @getEnfineList="getEnfineList"
        @handlePrevious="handlePrevious"
        @handleNext="handleNext"
      ></FilterChart>
      <el-alert type="info" :closable="false">
        <template v-slot:title>
          <div style="display: flex; align-items: center">
            <i
              class="el-icon-info"
              style="font-size: 20px; margin-right: 5px"
            ></i>
            <h3>分析说明:</h3>
          </div>
        </template>
        <div style="font-size: 12px; margin-top: 10px">
          在风力发电机组中，功率曲线散点图是一种展示在不同风速下风机产生的功率的工具。这种图表通常以风速为横坐标，以发电机的功率输出为纵坐标。在理想情况下，这些散点应当形成一条清晰的曲线，反映出风速与发电机功率之间的关系。功率曲线是风力发电机性能的关键指标，可以用来评估风机在不同风速条件下的表现。
        </div>
      </el-alert>
      <!-- 总图 -->
      <div class="titleCharts">分析总图 :</div>
      <div v-if="graphFilesData && graphFilesData.length > 0">
        <template
          v-for="(powerCurveDom, ind) in generalFilesData"
          :style="{ marginTop: '50px' }"
        >
          <el-row class="charts">
            <el-col :span="24" :key="ind + 'leftTable'">
              <div class="leftTable">
                <el-button
                  @click="
                    downLoadCsv(
                      powerCurveDom && powerCurveDom.powerCurveTableData
                    )
                  "
                  >导出功率曲线数据</el-button
                >
                <!-- <el-table
                  :data="powerCurveDom.powerCurveTableData"
                  border
                  max-height="500"
                  style="width: 100%"
                  align="center"
                >
                  <el-table-column prop="enginName" label="风机名称">
                  </el-table-column>
                  <el-table-column prop="engineTypeName" label="风机机型">
                  </el-table-column>
                  <el-table-column prop="xData" label="风速(m/s)">
                  </el-table-column>
                  <el-table-column prop="yData" label="实际功率(kWh)">
                  </el-table-column>
                  <el-table-column
                    prop="contractPowerCurve"
                    label="合同功率(kWh)"
                  >
                  </el-table-column>
                </el-table> -->
              </div>
            </el-col>
            <el-col :span="24" :key="ind + 'rightTable'">
              <div class="rightTable">
                <PlotlyCharts
                  :lineMarkerData="powerCurveDom.chartsData"
                  :comType="'generalDrawing'"
                  :inds="`${new Date().getTime()}` + `zong${ind}`"
                ></PlotlyCharts>
              </div>
            </el-col>
          </el-row>
        </template>
      </div>
      <el-empty v-else description="暂无总图"></el-empty>
      <!-- 分图 -->
      <div class="titleCharts">分析分图 :</div>
      <template v-if="graphFilesData && graphFilesData.length > 0">
        <div
          class="graphFilesData"
          v-for="(powerCurveDom, ind) in graphFilesData"
        >
          <el-row class="charts">
            <el-col
              v-if="
                powerCurveDom && powerCurveDom.powerCurveTableData.length > 0
              "
              :key="ind + 'powerCurveDom' + 'rightTable'"
              :span="24"
            >
              <div class="rightTable">
                <PlotlyCharts
                  :lineMarkerData="powerCurveDom.chartsData"
                  :comType="'graph'"
                  :inds="`${new Date().getTime()}` + `fen${ind}`"
                ></PlotlyCharts>
              </div>
            </el-col>
            <el-col
              :span="24"
              :key="ind + 'powerCurveDom' + 'leftTable'"
              v-if="
                powerCurveDom && powerCurveDom.powerCurveTableData.length > 0
              "
            >
              <!-- <div class="leftTable">
                <el-table
                  :data="powerCurveDom && powerCurveDom.powerCurveTableData"
                  border
                  max-height="500"
                  style="width: 100%"
                  align="center"
                >
                  <el-table-column prop="enginName" label="风机名称">
                  </el-table-column>
                  <el-table-column prop="engineTypeName" label="风机机型">
                  </el-table-column>
                  <el-table-column prop="xData" label="风速"> </el-table-column>
                  <el-table-column prop="yData" label="实际功率">
                  </el-table-column>
                  <el-table-column prop="contractPowerCurve" label="合同功率">
                  </el-table-column>
                </el-table>
              </div> -->
            </el-col>

            <el-col v-else :span="24">
              <el-empty description="暂无分图"></el-empty>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-empty v-else description="暂无分图"></el-empty>

      <el-dialog
        v-if="isShowDescription"
        title="添加评论"
        :visible="isShow"
        width="30%"
        v-dialogDrag
        :modal="false"
        :lock-scroll="false"
        :modal-append-to-body="false"
        @close="handleClose"
      >
        <el-tabs value="first">
          <el-tab-pane label="意见描述" name="first">
            <TinymceEditor
              ref="editor"
              v-model="comment"
              @input="handleEditorInput($event)"
              @onClick="onClick"
            >
            </TinymceEditor>
          </el-tab-pane>
        </el-tabs>
        <el-row
          type="flex"
          class="row-bg"
          justify="end"
          style="margin: 20px 60px 0 0"
        >
          <el-col :span="2">
            <el-button type="primary" size="small" @click="handleComment"
              >提交评论</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
    </div>
    <div class="right" v-if="isShowTinymceEditorCom">
      <DicCard
        :batchCode="initBatchCode"
        :analysisTypeCode="analysisTypeCode"
        :commentDescriptionVos="commentDescriptionVos"
      >
      </DicCard>
    </div>
  </div>
</template>
<script>
import DicCard from "@/views/overview/components/dicCard/index.vue";
import FilterChart from "@/views/overview/components/filterChart/index.vue";
import TinymceEditor from "@/components/Tinymce.vue";
import {
  analysisDetail,
  queryAnalysisedEngine,
  analysisCommentEdit,
} from "@/api/performance";
import PlotlyCharts from "@/views/performance/components/PlotlyCharts.vue";
import { downLoadCsvFile } from "@/utils/common";
import { saveAs } from "file-saver";
import JSZip from "jszip";
import Papa from "papaparse";
import axios from "axios";
export default {
  name: "powerCurve",
  components: {
    DicCard,
    FilterChart,
    PlotlyCharts,
    TinymceEditor,
  },
  props: {
    initBatchCode: {
      default: "",
      type: String,
    },
    isShowTinymceEditorCom: {
      default: true,
      type: Boolean,
    },
    isShow: {
      default: false,
      type: Boolean,
    },
    analysisTypeCode: {
      default: "",
      type: String,
    },
    batchCodeList: {
      default: "",
      type: Array,
    },
  },
  data() {
    return {
      form: {
        value2: "",
      },
      windEngineGroupList: [], //批次风机列表
      fieldEngineCodes: [], //选中风机
      comment: "",
      options: [],
      generalFilesData: [],
      graphFilesData: [],
      commentDescriptionVos: [], //评论列表
      editableTabs: [],
      isShowDescription: false,
    };
  },
  watch: {
    initBatchCode(newVal) {
      if (newVal) {
        this.fetchData(); // 调用合并后的函数
      }
    },
    analysisTypeCode(newVal) {
      if (newVal) {
        this.fetchData(); // 调用合并后的函数
      }
    },
    isShow() {
      if (this.isShow) {
        if (!this.isShowDescription) {
          this.$message({
            message: "当前分析类型暂无分析，不能进行评论操作",
            type: "warning",
          });
          this.$emit("setIsShow");
        }
      }
    },
  },
  mounted() {
    if (this.initBatchCode && this.analysisTypeCode) {
      this.fetchData(); // 调用合并后的函数
    }
  },
  methods: {
    handleClose() {
      //关闭评论弹框
      this.$emit("setIsShow");
    },
    async handleComment() {
      try {
        await analysisCommentEdit({
          batchCode: this.initBatchCode,
          analysisTypeCode: this.analysisTypeCode,
          commentList: this.editableTabs.map((item) => {
            return {
              commentTypeCode: item.commentTypeCode,
              comment: item.commentTypeName === "分析评论" ? this.comment : "",
            };
          }),
        });
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.comment = "";
        this.getAnalysisDetail();
        this.$emit("setIsShow");
      } catch (e) {
        console.error(e);
        this.loading = false;
      }
    },
    onSubmit() {
      console.log("submit!");
    },
    // 合并后的函数，处理数据请求
    async fetchData() {
      try {
        console.log(
          this.initBatchCode,
          this.analysisTypeCode,
          "请求详情 分钟级"
        );
        // 获取分析详情
        await this.getAnalysisDetail();

        // 获取风机列表
        await this.getWindEnfineList(this.initBatchCode, this.analysisTypeCode);
      } catch (err) {
        console.error("Failed to fetch data:", err);
      }
    },
    // 获取分析详情接口
    async getAnalysisDetail() {
      try {
        const result = await analysisDetail({
          batchCode: this.initBatchCode,
          analysisTypeCode: this.analysisTypeCode,
          fieldEngineCodes:
            this.fieldEngineCodes.length === 0
              ? undefined
              : this.fieldEngineCodes.join(","),
        });
        if (result.data.length > 0) {
          this.isShowDescription = true;
        }
        if (
          result.data &&
          result.data[0] &&
          result.data[0].commentTypeRelations
        ) {
          this.editableTabs = result.data[0].commentTypeRelations;
        }
        //当前评论展示获取
        if (
          result.data &&
          result.data[0] &&
          result.data[0].commentDescriptionVos
        ) {
          this.commentDescriptionVos = result.data[0].commentDescriptionVos;
        }
        this.generalFilesData = [];
        this.graphFilesData = [];
        const generalFiles = result.data[0]?.generalFiles || [];
        const generalFilesData = await this.filterJsonData(
          generalFiles,
          "总图"
        );
        //分图数据
        this.graphFilesData = await this.filterJsonData(
          result.data[0]?.diagramRelations || [],
          "分图"
        );

        // 过滤掉 null 或没有 chartsData 的项
        this.generalFilesData = generalFilesData.filter(
          (item) => item && item.chartsData
        );
        console.log(this.generalFilesData, "总图");
        console.log(this.graphFilesData, "分图");
      } catch (err) {
        console.error("Failed to fetch analysis details:", err);
      }
    },
    //有功功率数据处理
    async filterJsonData(generalFiles, type) {
      return Promise.all(
        generalFiles.map(async (item, ind) => {
          const types = this.getFileType(item.fileAddr);
          if (types !== "html" && types !== "image") {
            //就是json 数据
            try {
              const resultChartsData = await axios.get(item.fileAddr);

              // 更新表格数据
              if (type === "总图") {
                return {
                  chartsData: {
                    ...resultChartsData.data,
                  },
                  powerCurveTableData: this.creatPowerCurveTableData(
                    resultChartsData.data
                  ).filter((val) => val !== undefined),
                };
              } else if (type === "分图") {
                return {
                  chartsData: {
                    ...resultChartsData.data,
                    formInfoFieldEngineCode: item.fieldEngineCode,
                  },
                  powerCurveTableData: this.creatPowerCurveTableData(
                    resultChartsData.data
                  )
                    .filter((val) => val !== undefined)
                    .filter(
                      (items) => items?.enginCode === item.fieldEngineCode
                    ),
                };
              }
            } catch (error) {
              console.error("Error fetching chart data:", error);
              return null; // 如果有错误，返回 null
            }
          }
        })
      );
    },
    getFileType(url) {
      // 使用 URL 对象解析 URL
      // 获取路径名部分
      let pathname = url.split("/").pop();
      // 截取路径名，去除加密乱码字符部分
      const index = pathname.indexOf(".html");
      if (index !== -1) {
        pathname = pathname.slice(0, index + 5); // '.html' 的长度是 5
      } else {
        pathname = pathname.slice(0, pathname.indexOf(".png") + 4); // '.png' 的长度是 4
      }
      // 正则表达式匹配图片扩展名
      const imageExtensions = /\.(png|jpg|jpeg|gif|bmp|svg)$/i;
      // 正则表达式匹配 HTML 扩展名
      const htmlExtensions = /\.html?$/i;

      if (imageExtensions.test(pathname)) {
        return "image";
      } else if (htmlExtensions.test(pathname)) {
        return "html";
      } else {
        return "unknown";
      }
    },
    creatPowerCurveTableData(data) {
      // 风机名称\风机机型\风速\合同功率\实际功率
      // xData--风速
      // yData--实际功率
      // 合同功率曲线[...]---合同功率
      // enginName--风机名称
      // engineTypeName--风机机型
      const contractPowerCurve =
        data && data.data.filter((item) => item.enginName === "合同功率曲线");
      const powerCurveTableData =
        data &&
        data.data.map((item, ind) => {
          if (item.enginName !== "合同功率曲线") {
            const childData = item.xData.map((child, childInd) => {
              // 检查是否所有需要的数据都存在
              if (
                item.yData[childInd] !== undefined &&
                contractPowerCurve[0].yData[childInd] !== undefined
              ) {
                return {
                  xData: child,
                  yData:
                    item.yData[childInd] !== null ? item.yData[childInd] : 0.0,
                  contractPowerCurve: contractPowerCurve[0].yData[childInd],
                  enginName: item.enginName,
                  enginCode: item.enginCode,
                  engineTypeName: data.engineTypeName,
                };
              }
            });

            return childData;
          }
        });

      return powerCurveTableData.flat();
    },
    downLoadCsv(tableDatas) {
      const headers = ["风机名称", "风机机型", "风速", "实际功率", "合同功率"]; // CSV 文件的标题
      const data = tableDatas.map((item) => {
        return [
          item.enginName,
          item.engineTypeName,
          item.xData,
          item.yData,
          item.contractPowerCurve,
        ];
      });
      // 将标题和数据组合成 CSV 格式
      const csvContent = [
        headers.join(","),
        ...data.map((row) => row.join(",")),
      ].join("\n");

      downLoadCsvFile(csvContent, "风机有功功率数据");
      // downLoadCsvFile(csvContent, fileName[0].engineName);
    },
    // 请求风机列表
    async getWindEnfineList(batchCode, analysisTypeCode) {
      // console.log("请求风机列表 分钟级");
      const resEngineList = await queryAnalysisedEngine({
        batchCode: batchCode,
        analysisTypeCode,
      });
      this.windEngineGroupList = resEngineList.data;
    },
    handleEditorInput(index, newVal) {
      // 更新对应的 comment 值
      // 如果该功能没有实现，可以删除这个方法
    },
    //获取选中风机list
    getEnfineList(data) {
      this.fieldEngineCodes = data;
      this.getAnalysisDetail();
    },
    //下一条
    handleNext() {
      const index = this.batchCodeList.findIndex(
        (item) => item === this.initBatchCode
      );
      if (index === this.batchCodeList.length - 1) {
        this.$message.warning("已经是最后一个分析结果了");
        return;
      }
      this.$emit("setInitBathCode", this.batchCodeList[index + 1]);
    },
    //上一条
    handlePrevious() {
      const index = this.batchCodeList.findIndex(
        (item) => item === this.initBatchCode
      );
      if (index === 0) {
        this.$message.warning("没有上一条了");
        return;
      }
      this.$emit("setInitBathCode", this.batchCodeList[index - 1]);
    },
    onClick() {},
  },
};
</script>

<style scoped lang="scss">
.type-variable {
  display: flex;
  height: 90%;
  overflow: hidden;
  .left {
    width: 30%;
    height: 100%;
    overflow: auto;
    padding: 20px;
    flex: 1;

    /* 滚动条整体样式 */
    &::-webkit-scrollbar {
      width: 6px; /* 滚动条宽度 */
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
      background: #f5f7fa;
      border-radius: 3px;
    }

    /* 滚动条滑块 */
    &::-webkit-scrollbar-thumb {
      background: #c0c4cc;
      border-radius: 3px;
    }

    /* 滚动条滑块悬停时 */
    &::-webkit-scrollbar-thumb:hover {
      background: #909399;
    }
  }
  .right {
    width: 250px;
    height: 100%;
    overflow: hidden;
  }
}
.el-dialog__wrapper {
  position: relative !important;
}
::v-deep .el-dialog {
  position: fixed !important;
  z-index: 999 !important;
  top: 50%;
  left: 50%;
  transform: translate(0, -50%);
}
.rightTable {
  width: 100%;
}
.charts {
  margin: 10px 0;
}
.titleCharts {
  font-size: 16px;
  font-weight: 500;
  margin-top: 20px;
}
</style>
