<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-for="(item, index) in generalFilesDatas">
        <DDrawingChart
          :key="item.batchCode + index"
          :index="index + 'zong'"
          :ref="item.batchCode + index"
          :fileAddr="item.fileAddr"
        >
        </DDrawingChart>
      </div> -->

      <VirtualList
        :list="generalFilesDatas"
        keyField="batchCode"
        :itemSize="600"
        v-slot="{ item, index }"
      >
        <DDrawingChart
          :key="item.batchCode + index"
          :index="index + 'zong'"
          :ref="item.batchCode + index"
          :fileAddr="item.fileAddr"
        >
        </DDrawingChart>
      </VirtualList>

      <!-- <div class="titleCharts">分析分图 :</div> -->

      <VirtualList
        :list="diagramRelationsDatas"
        keyField="fieldEngineCode"
        :itemSize="600"
        v-slot="{ item, index }"
      >
        <TwoDMarkersChart
          v-if="getFileTypeFromUrl(item.fileAddr) === 'speed_torque'"
          :index="index + 'TwoDMarkersChart'"
          :key="item.fieldEngineCode + 'TwoDMarkersChart'"
          :ref="item.fieldEngineCode"
          :fileAddr="item.fileAddr"
        >
        </TwoDMarkersChart>
        <Time3DChart
          v-if="getFileTypeFromUrl(item.fileAddr) === '3D'"
          :key="item.fieldEngineCode + 'Time3DChart'"
          :index="index + 'fen'"
          :ref="item.fieldEngineCode + 'Time3DChart'"
          :fileAddr="item.fileAddr"
        >
        </Time3DChart>
      </VirtualList>

      <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">
      <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 DDrawingChart from "@/views/performance/components/chartsCom/3DDrawingChart.vue";
import Time3DChart from "@/views/performance/components/chartsCom/Time3DChart.vue";
import TinymceEditor from "@/components/Tinymce.vue";
import {
  analysisDetail,
  queryAnalysisedEngine,
  analysisCommentEdit,
} from "@/api/performance";
import TwoDMarkersChart from "@/views/performance/components/chartsCom/TwoDMarkersChart.vue";

export default {
  name: "speedTorque",
  components: {
    DicCard,
    FilterChart,
    DDrawingChart,
    Time3DChart,
    TinymceEditor,
    TwoDMarkersChart,
  },
  props: {
    initBatchCode: {
      default: "",
      type: String,
    },
    isShow: {
      default: false,
      type: Boolean,
    },
    analysisTypeCode: {
      default: "",
      type: String,
    },
    batchCodeList: {
      default: "",
      type: Array,
    },
  },
  data() {
    return {
      form: {
        value2: "",
      },
      windEngineGroupList: [], //批次风机列表
      fieldEngineCodes: [], //选中风机
      comment: "",
      options: [],
      generalFilesDatas: [], //总图
      diagramRelationsDatas: [], //分图,
      requestResult: [], // 请求结果
      requestRecord: [],
      commentDescriptionVos: [], //评论列表
      editableTabs: [],
      isShowDescription: false,
      diagramRelationsDatas2D: [],
      diagramRelationsDatas3D: [],
    };
  },
  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;
      }
    },
    getResult({ index, result }) {
      console.log(index, result);
      this.$set(this.requestResult, index, result);
      // this.requestResult[index] = result
      this.requestRecord[index] = result;
    },
    changeRequestNum(index) {
      if (index <= 1) {
        this.$set(this.requestRecord, index, "start");
        return;
      }
      if (index > 1) {
        if (
          this.requestRecord.every((item) =>
            ["success", "error"].includes(item)
          )
        ) {
          this.$set(this.requestRecord, index, "start");
          this.$set(this.requestResult, index, "start");
        } else {
          this.$set(this.requestRecord, index, "start");
        }
      }
    },
    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.generalFilesDatas =
          (result.data &&
            result.data[0] &&
            result.data[0].generalFiles &&
            result.data[0].generalFiles.filter((item) =>
              item.fileAddr.endsWith(".json")
            )) ||
          []; //总图数据
        console.log(this.generalFilesDatas, "总图数据");

        if (result.data && result.data[0] && result.data[0].diagramRelations) {
          const diagramRelationsDatas = result.data[0].diagramRelations.filter(
            (item) => item.fileAddr.endsWith(".json")
          );
          this.diagramRelationsDatas2D =
            diagramRelationsDatas.filter(
              (item) =>
                this.getFileTypeFromUrl(item.fileAddr) === "speed_torque"
            ) || [];
          this.diagramRelationsDatas3D =
            diagramRelationsDatas.filter(
              (item) => this.getFileTypeFromUrl(item.fileAddr) === "3D"
            ) || [];
        }
        this.diagramRelationsDatas =
          (result.data &&
            result.data[0] &&
            result.data[0].diagramRelations.filter((item) =>
              item.fileAddr.endsWith(".json")
            )) ||
          [];
      } catch (err) {
        console.error("Failed to fetch analysis details:", err);
      }
    },
    getFileTypeFromUrl(url) {
      // 判断文件名或路径是否包含关键字
      if (url.includes("3D")) {
        return "3D"; // 如果 URL 中包含 "3D" 字符串，判断为 3D 类型
      } else if (url.includes("speed_torque")) {
        return "speed_torque"; // 如果 URL 中包含 "speed_torque" 字符串，判断为 speed_torque 类型
      } else {
        return "Unknown"; // 如果都不包含，返回 Unknown 或其他提示
      }
    },
    // 请求风机列表
    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%);
}
.titleCharts {
  font-size: 16px;
  font-weight: 500;
  margin-top: 20px;
}
</style>
