<!--
 * @Author: your name
 * @Date: 2025-01-10 09:24:14
 * @LastEditTime: 2025-01-21 14:50:01
 * @LastEditors: bogon
 * @Description: In User Settings Edit
 * @FilePath: /performance-test/src/views/overview/components/yaw_error/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">
          静态偏航误差过大，导致风轮不能精准对风，会造成发电损失，例如10°的静态偏航误差导致2.6%的发电损失，且风速较低的风场往往出现更多的发电损失；此外静态偏航误差过大，不仅会影响机组的功率输出，还会引起叶片气动弹性波动，增加机组的额外载荷。因此，定期检测机组的静态偏航误差，并及时校正，对于改善机组发电性能和机组运行安全都有很重要的意义。
        </div>
      </el-alert>
      <div class="titleCharts">分析分图 :</div>
      <div v-if="zongFaultCsvData.length > 0">
        <FaultAll
          :faultTypes="
            zongFaultCsvData &&
            zongFaultCsvData[0] &&
            zongFaultCsvData[0].data.map((item) => item.engine_name)
          "
          :faultCounts="
            zongFaultCsvData &&
            zongFaultCsvData[0] &&
            zongFaultCsvData[0].data.map((item) => item.count)
          "
          :faultDurations="
            zongFaultCsvData &&
            zongFaultCsvData[0] &&
            zongFaultCsvData[0].data.map((item) => item.fault_time_sum)
          "
          :zongFaultCsvData="zongFaultCsvData"
        ></FaultAll>
      </div>
      <el-empty description="暂无分析记录" v-else></el-empty>

      <div class="titleCharts">分析总图 :</div>
      <div v-if="zongFaultCsvData.length > 0">
        <template v-for="(itemCsv, indCsv) in zongFaultCsvData">
          <el-table
            :key="indCsv + 'indCsv'"
            :data="filteredData(itemCsv)"
            border
            style="width: 100%"
            max-height="500"
            align="center"
          >
            <el-table-column prop="engine_name" label="风机名称">
            </el-table-column>
            <el-table-column prop="yaw_error1" label="误差值">
            </el-table-column>
            <el-table-column align="right">
              <template slot="header" slot-scope="scope">
                <el-input
                  v-model="search"
                  size="mini"
                  placeholder="输入风机名称关键字搜索"
                />
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <el-empty description="暂无分析记录" v-else></el-empty>

      <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">
        <el-col :span="2" style="margin: 20px">
          <el-button type="primary" size="small" @click="handleComment"
            >提交评论</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="right">
      <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 FaultAll from "@/views/performance/components/chartsCom/FaultAll.vue";
import TinymceEditor from "@/components/Tinymce.vue";
import {
  analysisDetail,
  queryAnalysisedEngine,
  analysisCommentEdit,
} from "@/api/performance";
import Papa from "papaparse";
import axios from "axios";
export default {
  name: "yaw_error",
  components: {
    DicCard,
    FilterChart,
    FaultAll,
    TinymceEditor,
  },
  props: {
    initBatchCode: {
      default: "",
      type: String,
    },
    analysisTypeCode: {
      default: "",
      type: String,
    },
    batchCodeList: {
      default: "",
      type: Array,
    },
  },
  data() {
    return {
      search: "",
      form: {
        value2: "",
      },
      windEngineGroupList: [], //批次风机列表
      fieldEngineCodes: [], //选中风机
      comment: "",
      options: [],
      zongFaultCsvHeader: [],
      zongFaultCsvData: [],
      fenFaultCsvHeader: [],
      fenFaultCsvData: [],
      commentDescriptionVos: [], //评论列表
      editableTabs: [],
    };
  },
  computed: {
    // 根据搜索关键字过滤数据
    filteredData() {
      return (itemCsv) => {
        // 如果有搜索关键词，则过滤数据
        if (this.search) {
          return itemCsv.data.filter((item) => {
            return item.engine_name
              .toLowerCase()
              .includes(this.search.toLowerCase());
          });
        }
        // 没有搜索关键词时返回所有数据
        return itemCsv.data;
      };
    },
    filteredFenData() {
      return (itemCsv) => {
        // 如果有搜索关键词，则过滤数据
        if (this.searchFen) {
          return itemCsv.data.filter((item) => {
            return item.wind_turbine_name
              .toLowerCase()
              .includes(this.searchFen.toLowerCase());
          });
        }
        // 没有搜索关键词时返回所有数据
        return itemCsv.data;
      };
    },
  },
  watch: {
    initBatchCode(newVal) {
      if (newVal) {
        this.fetchData(); // 调用合并后的函数
      }
    },
    analysisTypeCode(newVal) {
      if (newVal) {
        this.fetchData(); // 调用合并后的函数
      }
    },
  },
  mounted() {
    if (this.initBatchCode && this.analysisTypeCode) {
      this.fetchData(); // 调用合并后的函数
    }
  },
  methods: {
    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();
      } catch (e) {
        console.error(e);
        this.loading = false;
      }
    },
    onSubmit() {
      console.log("submit!");
    },
    // 封装的获取 CSV 数据方法
    fetchCsvData(analysisType, url) {
      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) => {
                // 根据分析类型设置不同的数据
                if (analysisType === "yaw_error") {
                  if (Object.keys(result.data[0]).includes("engine_name")) {
                    //总图
                    this.zongFaultCsvHeader.push(Object.keys(result.data[0]));
                    this.zongFaultCsvData.push({
                      data: result.data
                        .filter((row) => Object.keys(row).length)
                        .slice(0, result.data.length - 1),
                    });
                  } else {
                    //分
                    this.fenFaultCsvHeader.push(Object.keys(result.data[0]));
                    this.fenFaultCsvData.push({
                      data: result.data
                        .filter((row) => Object.keys(row).length)
                        .slice(0, result.data.length - 1),
                    });
                  }
                }
              },
              error: (error) => {
                console.error("CSV 解析错误：", error);
              },
            });
          };
          reader.readAsText(response.data); // 读取 blob 数据
        })
        .catch((error) => {
          console.error("无法获取 CSV 文件：", error);
        });
    },
    // 合并后的函数，处理数据请求
    async fetchData() {
      try {
        // 获取分析详情
        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 &&
          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;
        }

        if (result.data && result.data[0] && result.data[0].generalFiles) {
          result.data[0].generalFiles.map((item) => {
            if (item.fileAddr) {
              this.zongFaultCsvHeader = [];
              this.zongFaultCsvData = [];
              this.fetchCsvData("yaw_error", item.fileAddr);
            }
          });
        } else {
          this.zongFaultCsvHeader = [];
          this.zongFaultCsvData = [];
        }
        if (result.data && result.data[0] && result.data[0].diagramRelations) {
          result.data[0].diagramRelations.map((item) => {
            if (item.fileAddr) {
              this.fenFaultCsvHeader = [];
              this.fenFaultCsvData = [];
              this.fetchCsvData("yaw_error", item.fileAddr);
            }
          });
        } else {
          this.fenFaultCsvHeader = [];
          this.fenFaultCsvData = [];
        }
      } catch (err) {
        console.error("Failed to fetch analysis details:", err);
      }
    },
    // 请求风机列表
    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;
  }
}
.titleCharts {
  font-size: 16px;
  font-weight: 500;
  margin-top: 20px;
}
</style>
