<!--
 * @Author: your name
 * @Date: 2024-05-29 09:14:23
 * @LastEditTime: 2024-09-30 16:11:40
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/performance/components/EditAnalysis.vue
-->
<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" label-width="120px">
      <el-collapse v-model="activeNames">
        <el-collapse-item title="基础筛选：" name="1">
          <el-row class="flex-wrap-row" :gutter="5">
            <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="5">
              <el-form-item label="分析类型" prop="configAnalysis">
                <el-select
                  v-model="form.configAnalysis"
                  placeholder="请选择分析类型"
                  size="small"
                  clearable
                  @change="handleAnalysisType"
                >
                  <el-option
                    v-for="(item, indAns) in analysisTypeList"
                    :key="item.analysisTypeCode + indAns"
                    :label="item.analysisTypeName"
                    :value="item.analysisTypeCode"
                  ></el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="5" prop="turbines">
              <el-form-item label="机组名称">
                <el-select
                  clearable
                  v-model="form.turbines"
                  placeholder="请选择机组名称"
                  size="small"
                >
                  <el-option
                    v-for="(item, indWind) in windEngineGroupList"
                    :key="item.engineCode + indWind"
                    :label="item.engineName"
                    :value="item.engineCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item class="searchFrom">
                <el-button type="primary" @click="onSubmit" size="small"
                  >查询</el-button
                >
                <!-- <el-button type="primary" @click="" size="small"
                  >一键下载分析结果</el-button
                > -->
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <el-empty
      v-if="noData"
      description="暂无分析任何数据,无法进行手动分析描述"
    ></el-empty>
    <el-card v-if="!noData" shadow="always" class="box-card">
      <el-row class="assetssConent">
        <!-- {{ generalFilesData }} -->
        <el-col
          :span="24"
          v-if="form.configAnalysis === 'yaw_error' && this.csvData.length > 0"
          ><div class="left">
            <el-table
              max-height="550"
              :data="csvData"
              border
              style="width: 100%"
              align="center"
            >
              <el-table-column prop="engine_name" label="风机名称">
              </el-table-column>
              <el-table-column prop="yaw_error1" label="误差值">
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col
          :span="24"
          v-if="form.configAnalysis === '发电效能评价数字化指标分析'"
          ><div class="left">
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              align="center"
            >
              <el-table-column prop="date" label="风电机组可利用率">
              </el-table-column>
              <el-table-column prop="name" label="能量利用率">
              </el-table-column>
              <el-table-column prop="name" label="应发电量"> </el-table-column>
              <el-table-column prop="name" label="实发电量"> </el-table-column>
              <el-table-column prop="name" label="停机损失电量">
              </el-table-column>
              <el-table-column prop="name" label="停机损失电量百分比">
              </el-table-column>
              <el-table-column prop="name" label="欠发损失电量">
              </el-table-column>
              <el-table-column prop="name" label="欠发损失电量百分比">
              </el-table-column>
              <el-table-column prop="name" label="限电损失电量">
              </el-table-column>
              <el-table-column prop="name" label="限电损失电量百分比">
              </el-table-column>
              <el-table-column prop="name" label="功率曲线未达标损失电量">
              </el-table-column>
              <el-table-column prop="name" label="功率曲线未达标损失电量百分比">
              </el-table-column>
              <el-table-column
                prop="name"
                label="功率散点不同水平功率带分布宽度"
              >
              </el-table-column>
              <el-table-column
                prop="name"
                label="功率散点水平平均功率带分布平均宽度"
              >
              </el-table-column>
              <el-table-column prop="name" label="功率散点分布异常特征值">
              </el-table-column>
              <el-table-column prop="name" label="平均风速"> </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col :span="24" v-if="form.configAnalysis === '故障统计'"
          ><div class="left">
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              align="center"
            >
              <el-table-column prop="date" label="故障次数（次）">
              </el-table-column>
              <el-table-column prop="name" label="故障时长（秒）">
              </el-table-column>
              <el-table-column prop="name" label="损失电量（KW/h）">
              </el-table-column>
            </el-table>
          </div>
        </el-col>

        <!-- 其他类型展示的 图表 ，只展示图表不必要展示表格 -->

        <template v-if="form.configAnalysis === 'power_curve'">
          <el-col :span="24">
            <div
              style="font-weight: 700; font-size: 16px; margin: 20px 0"
              v-if="generalFilesData.length > 0 || powerHtmlZongData.length > 0"
            >
              分析总图:
            </div>
          </el-col>
          <template
            v-if="generalFilesData[0] !== null && generalFilesData.length !== 0"
          >
            <template
              v-for="(powerCurveDom, ind) in generalFilesData"
              :style="{ marginTop: '50px' }"
            >
              <!-- <el-row style="height: 600px"> -->
              <el-col
                :key="ind + 'zongleftCharts'"
                :span="12"
                style="height: 600px"
                v-if="
                  form.configAnalysis === 'power_curve'
                  // ||
                  // form.configAnalysis === 'cp'
                "
                ><div class="left">
                  <el-button
                    @click="
                      downLoadCsv(
                        powerCurveDom && powerCurveDom.powerCurveTableData
                      )
                    "
                    >导出表格数据</el-button
                  >

                  <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
                style="height: 600px"
                :key="ind + 'zongrightCharts'"
                v-loading="htmlLoading"
                v-if="form.configAnalysis === 'power_curve'"
                :span="12"
              >
                <div class="right">
                  <PlotlyCharts
                    :ref="`charts-${ind}`"
                    :inds="`zong${ind}`"
                    :lineMarkerData="powerCurveDom.chartsData"
                    :comType="'generalDrawing'"
                  ></PlotlyCharts>
                </div>
              </el-col>
              <!-- </el-row> -->
            </template>
          </template>
          <template v-if="powerHtmlZongData.length > 0">
            <template
              v-for="(file, index) in powerHtmlZongData"
              :style="{ marginTop: '50px' }"
            >
              <!-- <div style="margin: 20px 0">11</div> -->
              <el-col
                class="col_content"
                :key="index + file.fileAddr + file.createTime"
                :span="24"
              >
                <iframe
                  v-if="getFileType(file.fileAddr) === 'html'"
                  :src="file.fileAddr"
                  :ref="'iframe' + index"
                  frameborder="0"
                  @load="iframeLoad(index + powerHtmlZongData.length)"
                  style="width: 100%; height: 100%"
                ></iframe>
              </el-col>
              <!-- <div style="margin: 20px 0">12</div> -->
            </template>
          </template>
          <el-col :span="24">
            <span
              style="font-weight: 700; font-size: 16px; margin: 20px 0"
              v-if="graphFilesData.length > 0 || powerHtmlFenData.length > 0"
            >
              分析分图:
            </span>
          </el-col>
          <el-col :span="24">
            <template
              v-if="graphFilesData[0] !== null && graphFilesData.length !== 0"
            >
              <template v-for="(powerCurveDom, ind) in graphFilesData">
                <el-row>
                  <el-col
                    v-loading="htmlLoading"
                    v-if="form.configAnalysis === 'power_curve'"
                    :span="12"
                  >
                    <div class="left">
                      <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-loading="htmlLoading"
                    v-if="form.configAnalysis === 'power_curve'"
                    :span="12"
                  >
                    <div class="right">
                      <PlotlyCharts
                        :lineMarkerData="powerCurveDom.chartsData"
                        :comType="'graph'"
                        :inds="`fen${ind}`"
                      ></PlotlyCharts>
                    </div>
                  </el-col>
                </el-row>
              </template>
            </template>
          </el-col>
          <template v-if="powerHtmlFenData.length > 0">
            <template v-for="(file, index) in powerHtmlFenData">
              <el-col
                :key="index + file.fileAddr + file.createTime"
                :span="24"
                class="col_content"
                :style="{
                  display:
                    getFileType(file.fileAddr) === 'html' ? 'block' : 'none',
                }"
              >
                <iframe
                  v-if="getFileType(file.fileAddr) === 'html'"
                  :src="file.fileAddr"
                  :ref="'iframe' + index"
                  frameborder="0"
                  @load="iframeLoad(index + powerHtmlFenData.length)"
                  width="100%"
                  height="100%"
                ></iframe>
              </el-col>
            </template>
          </template>
        </template>
        <template v-else>
          <!-- <el-col :span="24" v-if="form.configAnalysis !== 'yaw_error'"> -->
          <!-- <div class="left">
              <div>
                <span>机组名称：</span>
                <el-select
                  v-model="engineCode"
                  placeholder="请选择机组名称"
                  size="small"
                  clearable
                  @change="handleEngineCode"
                >
                  <el-option
                    v-for="(item, indWind) in windEngineGroupList"
                    :key="item.engineCode + indWind"
                    :label="item.engineName"
                    :value="item.engineCode"
                  ></el-option>
                </el-select>
              </div>
              <div>
                1.额定容量：{{
                  windDetail.ratedCapacity ? windDetail.ratedCapacity : 0
                }}
                <span> (kW)</span>
              </div>
              <div>2.风机编号:{{ windDetail.engineCode }}</div>
              <div>3.经度（Longitude）：{{ windDetail.longitude }}</div>
              <div>4.维度（Dimensionality）：{{ windDetail.latitude }}</div>
              <div>
                5.海拔高度（Altitude）：{{
                  windDetail.elevationHeight ? windDetail.elevationHeight : 0
                }}
                <span>(米)</span>
              </div>
              <div>6.风机名称：{{ windDetail.engineName }}</div>
              <div>
                7.是否标杆（Benchmarking or not）：{{
                  windDetail.sightcing == 1 ? "是" : "否"
                }}
              </div>
              <div>8.风场编号：{{ windDetail.fieldCode }}</div>
              <div>
                9.轮毂高度：{{
                  windDetail.hubHeight ? windDetail.hubHeight : 0
                }}
                <span>(米)</span>
              </div>
              <div>10.机型编号：{{ windDetail.millTypeCode }}</div>
              <div>
                11.切入风速：{{
                  windDetail.ratedCutInWindspeed
                    ? windDetail.ratedCutInWindspeed
                    : 0
                }}<span>(m/s)</span>
              </div>
              <div>
                12.切出风速：{{
                  windDetail.ratedCutOutWindspeed
                    ? windDetail.ratedCutOutWindspeed
                    : 0
                }}<span>(m/s)</span>
              </div>
            </div> -->
          <!-- </el-col> -->
          <template
            v-if="
              form.configAnalysis !== 'yaw_error' &&
              form.configAnalysis !== 'power_curve'
            "
          >
            <el-col :span="24">
              <div
                style="font-weight: 700; font-size: 16px"
                v-if="generalFiles.length > 0"
              >
                分析总图:
              </div>
            </el-col>
            <template v-for="(file, index) in generalFiles">
              <el-col
                :key="index + file.fileAddr + file.createTime"
                :span="24"
                class="col_content"
                :style="{
                  display:
                    getFileType(file.fileAddr) === 'html' ? 'block' : 'none',
                }"
              >
                <iframe
                  v-if="getFileType(file.fileAddr) === 'html'"
                  :src="file.fileAddr"
                  :ref="'iframe' + index"
                  frameborder="0"
                  @load="iframeLoad(index + generalFiles.length)"
                  width="100%"
                  height="100%"
                ></iframe>
              </el-col>
            </template>

            <el-col :span="24">
              <div
                style="font-weight: 700; font-size: 16px"
                v-if="diagramRelations.length > 0"
              >
                分析分图:
              </div>
            </el-col>
            <template v-for="(file, index) in diagramRelations">
              <el-col
                :key="index + file.fileAddr + file.createTime"
                :span="24"
                :style="{
                  display:
                    getFileType(file.fileAddr) === 'html' ? 'block' : 'none',
                }"
                class="col_content"
              >
                <iframe
                  v-if="getFileType(file.fileAddr) === 'html'"
                  :src="file.fileAddr"
                  :ref="'iframe' + index + diagramRelations.length"
                  frameborder="0"
                  width="100%"
                  height="100%"
                  @load="iframeLoad(index + diagramRelations.length)"
                ></iframe>
              </el-col>
            </template>
          </template>
        </template>
      </el-row>
    </el-card>
    <el-empty :image-size="200" v-if="flage"></el-empty>
    <div class="abalysisType" v-else-if="!flage && !noData">
      <el-tabs
        v-model="editableTabsValue"
        type="card"
        editable
        @edit="handleTabsEdit"
      >
        <el-tab-pane
          :key="item.commentTypeCode"
          v-for="(item, index) in editableTabs"
          :label="item.commentTypeName"
          :name="item.commentTypeCode"
        >
          <tinymce-editor
            ref="editor"
            v-model="item.comment"
            :disabled="disabled"
            @input="handleEditorInput(index, $event)"
            @onClick="onClick"
          >
          </tinymce-editor>
        </el-tab-pane>
      </el-tabs>
      <div style="margin-top: 20px; display: flex; justify-content: end">
        <el-button type="primary" @click="handleComment"
          >提交分析编辑描述</el-button
        >
      </div>
    </div>
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :inline="true"
        ref="formInline"
        :model="formInline"
        :rules="rules"
        class="demo-form-inline"
      >
        <el-form-item label="类型名称" prop="commentTypeName">
          <el-input
            v-model="formInline.commentTypeName"
            placeholder="请输入类型名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAnalysisNameFn('formInline')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  analysisDetail,
  delAnalysisCommentType,
  addAnalysisCommentType,
  analysisCommentEdit,
  queryAnalysisedType, //查询分析类型
  queryAnalysisedEngine, //查询机组
} from "@/api/performance";
import { getWindEngineGroup } from "@/api/ledger";
import TinymceEditor from "@/components/Tinymce.vue";
import PlotlyCharts from "./PlotlyCharts.vue";
import { downLoadCsvFile } from "@/utils/common";
import Papa from "papaparse";
import axios from "axios";
import { style } from "plotly.js-with-locales/lib/bar";
export default {
  components: {
    TinymceEditor,
    PlotlyCharts,
  },
  props: {
    activeName: String,
  },
  data() {
    return {
      tableData: [],
      noData: false,
      htmlLoading: false,
      loading: false,
      engineCode: null, //台账机组编号
      windDetail: {},
      flage: false,
      csvData: [], // 解析后的数据
      csvHeaders: [], // CSV 表头
      rules: {
        commentTypeName: {
          required: true,
          message: "请输入类型名称",
          trigger: "blur",
        },
      },
      generalFiles: [], //总图数组
      diagramRelations: [], //分图数组
      value4: "",
      value1: "",
      form: {
        configAnalysis: "",
        turbines: "",
      },
      activeNames: ["1"],
      msg: "",
      disabled: false,
      value: "",
      options: [],
      editableTabsValue: "",
      formInline: {
        commentTypeName: "",
      },
      dialogVisible: false,
      editableTabs: [],
      analysisTypeList: [],
      windEngineGroupList: [],
      formData: { content: "<p>Hello, Tinymce!</p>" },
      tabIndex: 2,
      powerCurveTableData: [],
      generalFilesData: [],
      graphFilesData: [],
      powerHtmlZongData: [],
      powerHtmlFenData: [],
    };
  },
  watch: {
    activeName: {
      handler(newVal, oldVal) {
        if (newVal === "second" && this.form.configAnalysis === "") {
          this.getWindCodeList();
        }
      },
    },
  },
  created() {
    //获取分析 分析类型、机组编号 列表
    // this.getWindCodeList();
  },
  methods: {
    iframeLoad() {
      this.htmlLoading = false;
    },
    async handleAnalysisType(e) {
      this.csvData = []; // 解析后的数据
      this.csvHeaders = [];
      const resEngineList = await queryAnalysisedEngine({
        batchCode: this.$route.query.batchCode,
        analysisTypeCode: e,
      });
      this.windEngineGroupList = resEngineList.data;
      this.form.turbines =
        resEngineList.data !== null && resEngineList.data.length > 0
          ? resEngineList.data[0].engineCode
          : null;
      this.engineCode =
        resEngineList.data !== null && resEngineList.data.length > 0
          ? resEngineList.data[0].engineCode
          : null;
      if (resEngineList.data.length > 0) {
        //获取台账机组编号
        this.getWindEngList();
      }
      this.getDetailInfo();
    },
    async handleComment() {
      this.loading = true;
      try {
        await analysisCommentEdit({
          batchCode: this.$route.query.batchCode,
          analysisTypeCode: this.form.configAnalysis,
          commentList: this.editableTabs.map((item) => {
            return {
              commentTypeCode: item.commentTypeCode,
              comment: item.comment,
            };
          }),
        });
        this.$message({
          type: "success",
          message: "保存成功",
        });
        this.loading = false;
        this.getDetailInfo();
      } catch (e) {
        console.error(e);
        this.loading = false;
      }
    },
    handleEditorInput(index, newVal) {
      // 更新对应的 comment 值
      this.$set(this.editableTabs, index, {
        ...this.editableTabs[index],
        comment: newVal,
      });
    },
    handleEngineCode(e) {
      this.engineCode = e;
      this.getWindEngList();
    },
    async getWindEngList() {
      try {
        const res = await getWindEngineGroup({
          engineCode: this.engineCode,
        });
        this.windDetail = res.data;
      } catch (error) {
        console.error(error);
      }
    },
    async getDetailInfo() {
      const formData = new FormData();
      formData.append("batchCode", this.$route.query.batchCode);
      formData.append("analysisTypeCode", this.form.configAnalysis);
      formData.append("fieldEngineCode", this.form.turbines);
      //获取详情信息
      this.loading = true;
      try {
        const response = await analysisDetail(formData);
        if (response.data.length === 0 || response.data === null) {
          this.flage = true;
        } else {
          this.flage = false;
        }
        this.generalFiles = [];
        this.generalFiles =
          (response.data &&
            response.data.length > 0 &&
            response.data[0].generalFiles) ||
          [];

        this.diagramRelations = [];
        this.diagramRelations =
          (response.data &&
            response.data.length > 0 &&
            response.data[0].diagramRelations) ||
          [];
        if (
          response.data.length > 0 &&
          response.data[0].commentTypeRelations &&
          response.data[0].commentTypeRelations.length > 0
        ) {
          this.editableTabs = this.mergeData(
            response.data[0].commentDescriptionVos,
            response.data[0].commentTypeRelations
          );
          this.editableTabsValue =
            this.editableTabs.length > 0
              ? this.editableTabs[0].commentTypeCode
              : "";
        }
        if (this.form.configAnalysis === "yaw_error") {
          this.getCsvData(response.data[0].generalFiles[0].fileAddr);
        }
        //有功功率的数据处理
        if (this.form.configAnalysis === "power_curve") {
          try {
            this.generalFilesData = [];
            this.graphFilesData = [];
            const generalFiles = response.data[0]?.generalFiles || [];
            this.powerHtmlZongData = [];
            this.powerHtmlFenData = [];
            // 处理 generalFiles 并获取每个文件的数据
            const generalFilesData = await this.filterJsonData(
              generalFiles,
              "总图"
            );
            //分图数据
            const graphChartData = await this.filterJsonData(
              response.data[0].diagramRelations,
              "分图"
            );
            // 过滤掉 null 或没有 chartsData 的项
            this.generalFilesData = generalFilesData.filter(
              (item) => item && item.chartsData
            );
            this.graphFilesData = graphChartData.filter(
              (item) => item && item.chartsData
            );
          } catch (error) {
            console.error("Error processing power curve data:", error);
          } finally {
            // 无论请求成功与否，都设置 loading = false
            this.loading = false;
          }
        } else {
          // 如果 configAnalysis 不是 "power_curve"，直接设置 loading = false
          this.loading = false;
        }
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    async filterJsonData(generalFiles, type) {
      return Promise.all(
        generalFiles.map(async (item, ind) => {
          const types = this.getFileType(item.fileAddr);
          if (types !== "html" && types !== "image") {
            try {
              const resultChartsData = await axios.get(item.fileAddr);
              // 更新表格数据，并返回数据对象
              if (type === "总图") {
                return {
                  chartsData: {
                    ...resultChartsData.data,
                  },
                  powerCurveTableData: this.creatPowerCurveTableData(
                    resultChartsData.data
                  ).filter((val) => val !== undefined),
                  // .filter(
                  //   (item) => item[0]?.enginCode === this.form.turbines
                  // ),
                };
              } else if (type === "分图") {
                return {
                  chartsData: {
                    ...resultChartsData.data,
                    formInfoFieldEngineCode: this.form.turbines,
                  },
                  powerCurveTableData: this.creatPowerCurveTableData(
                    resultChartsData.data
                  )
                    .filter((val) => val !== undefined)
                    .filter(
                      (item) =>
                        item?.enginName === this.form.turbines ||
                        item?.enginCode === this.form.turbines
                    ),
                };
              }
            } catch (error) {
              console.error(
                `Error fetching chart data for file: ${item.fileAddr}`,
                error
              );
              return null; // 如果出错，返回 null 以避免中断
            }
          } else {
            if (type === "总图") {
              this.powerHtmlZongData.push(item);
            } else if (type === "分图") {
              this.powerHtmlFenData.push(item);
            }
          }
          // 如果文件类型不匹配，返回一个空对象
          return 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;
          }
        });
      // console.log(
      //   powerCurveTableData.flat(),
      //   "powerCurveTableDatapowerCurveTableData"
      // );
      return powerCurveTableData.flat();
    },
    getCsvData(url) {
      // 使用 axios 获取 CSV 文件
      axios
        .get(url, { responseType: "blob" }) // 确保数据以 blob 格式返回
        .then((response) => {
          const reader = new FileReader();
          reader.onload = (e) => {
            const csvText = e.target.result;
            Papa.parse(csvText, {
              header: true, // 使用 CSV 第一行作为键
              complete: (result) => {
                this.csvHeaders = Object.keys(result.data[0]);
                this.csvData = result.data.filter(
                  (row) => Object.keys(row).length
                ); // 过滤空行
              },
              error: (error) => {
                console.error("CSV 解析错误：", error);
              },
            });
          };
          reader.readAsText(response.data); // 读取 blob 数据
        })
        .catch((error) => {
          console.error("无法获取 CSV 文件：", error);
        });
    },
    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, "风机有功功率数据");
    },
    mergeData(arr, brr) {
      // 创建一个新的结果数组
      const result = [];
      // 遍历 brr 数组
      brr.forEach((brrItem) => {
        // 在 arr 中寻找具有相同 commentTypeCode 的项
        const foundItem = arr.find(
          (arrItem) => arrItem.commentTypeCode === brrItem.commentTypeCode
        );
        if (foundItem) {
          // 如果找到了相同的项，就合并它们
          result.push({
            ...foundItem,
            ...brrItem,
          });
        } else {
          // 如果没有找到相同的项，就将 brrItem 添加到结果数组中
          result.push(brrItem);
        }
      });
      // 返回结果数组
      return result;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //修改赋值
    async getWindCodeList() {
      this.loading = true;
      try {
        const resAnalysisedType = await queryAnalysisedType({
          batchCode: this.$route.query.batchCode,
        });
        if (resAnalysisedType.data && resAnalysisedType.data.length > 0) {
          this.noData = false;
          const resEngineList = await queryAnalysisedEngine({
            batchCode: this.$route.query.batchCode,
            analysisTypeCode: resAnalysisedType.data[0].analysisTypeCode,
          });
          this.analysisTypeList = resAnalysisedType.data;
          this.windEngineGroupList = resEngineList.data;
          this.form.configAnalysis = resAnalysisedType.data[0].analysisTypeCode;
          this.form.turbines =
            resEngineList.data !== null && resEngineList.data.length > 0
              ? resEngineList.data[0].engineCode
              : null;
          this.engineCode =
            resEngineList.data !== null && resEngineList.data.length > 0
              ? resEngineList.data[0].engineCode
              : null;
          this.getDetailInfo();
          if (resEngineList.data.length > 0) {
            //获取台账机组编号
            this.getWindEngList();
          }
        } else {
          this.noData = true;
        }
        this.loading = false;
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    },
    // 鼠标单击的事件
    onClick(e, editor) {},
    onSubmit() {
      this.getDetailInfo();
    },
    //新增分析结果类型
    addAnalysisNameFn(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            await addAnalysisCommentType({
              batchCode: this.$route.query.batchCode,
              analysisTypeCode: this.form.configAnalysis,
              commentTypeName: this.formInline.commentTypeName,
            });
            this.$refs[formName].resetFields();
            this.dialogVisible = false;
            this.loading = false;
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.getWindCodeList();
          } catch (e) {
            console.error(e);
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    handleTabsEdit(targetName, action) {
      if (action === "add") {
        this.dialogVisible = true;
        this.formInline.commentTypeName = "";
      }
      if (action === "remove") {
        const obj = this.editableTabs.filter(
          (item) => item.commentTypeCode === targetName
        )[0];
        if (
          obj.commentTypeName === "分析内容与可视化分析" ||
          obj.commentTypeName === "现象描述" ||
          obj.commentTypeName === "原因描述" ||
          obj.commentTypeName === "排查建议"
        ) {
          this.$message({
            type: "error",
            message:
              "分析内容与可视化分析、现象描述、原因描述、排查建议 分析类型不可删除！",
          });
          return;
        }
        this.$confirm("此操作将永久删除该评价类型, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            this.loading = true;
            try {
              const formData = new FormData();
              formData.append("commentTypeCode", targetName);
              await delAnalysisCommentType(formData);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.editableTabsValue =
                this.editableTabs.length > 0
                  ? this.editableTabs[0].commentTypeCode
                  : "";
              this.getWindCodeList();
              this.loading = false;
            } catch (error) {
              console.error(error);
              this.loading = false;
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
  },
};
</script>
<style scoped lang="scss">
.box-card {
  margin: 10px 0;
  // box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  width: 100%;
  font-size: 14px;
  .el-card__body {
    width: 100%;
    .left {
      > div {
        line-height: 3;
      }
    }
  }
}
::v-deep .searchFrom {
  .el-form-item__content {
    display: flex !important;
    justify-content: end !important;
    align-items: center !important;
    i {
      margin-left: 10px;
      font-size: 20px;
    }
  }
}
::v-deep.el-input--small .el-input__inner {
  width: 200px !important;
}
::v-deep .el-table th.el-table__cell > .cell {
  display: block !important;
}
.demo-input-suffix {
  display: flex !important;
}
::v-deep.demo-input-suffix .el-input--small {
  width: 100px !important;
}
::v-deep.demo-input-suffix .el-input--small .el-input__inner {
  width: 90px !important;
}
.abalysisType {
  margin-top: 30px;
}
.col_content {
  height: 600px;
}
</style>
