<template>
  <el-dialog
    v-model="showDialog"
    custom-class="modal"
    id="report"
    width="50%"
    top="5vh"
    :show-close="false"
    center
  >
    <div class="exportPDF">
      <el-button type="primary" size="small" @click="savePdf">导出PDF</el-button>
    </div>
    <div class="reportMain">
      <p class="mainTitle">故障诊断报告</p>
      <!-- 诊断概述 -->
      <div class="reportTitle">
        <el-row class="titleRwo">
          <el-col :span="16" class="titleCol">
            <p>模型名称：</p>
            <span>{{ reportMssage.name }}</span>
          </el-col>
          <el-col :span="8" class="titleCol">
            <p>故障时间：</p>
            <span>{{ reportMssage.time }}</span>
          </el-col>
        </el-row>
        <el-row class="titleRwo">
          <el-col :span="16" class="titleCol">
            <p>训练次数：</p>
            <span>{{ reportMssage.many }}次</span>
          </el-col>
          <el-col :span="8" class="titleCol">
            <p>故障风机名称：</p>
            <span>{{ reportMssage.windname }}</span>
          </el-col>
        </el-row>
        <div class="reportMsg">
          <p class="title">检测结论</p>
          <div class="mssage titleCol">
            <p>本检测结果所使用的模型为：</p>
            <span>{{ reportMssage.model }};</span>
            <p class="msgStyle">可信度为：</p>
            <span>{{ reportMssage.beleve }};</span>
            <p class="msgStyle">检测结果为：</p>
            <span>{{ reportMssage.result }}。</span>
          </div>
        </div>
      </div>
      <!-- 报警详情 -->
      <div class="reporttreeDDA">
        <div id="main" class="charttreeStyle"></div>
      </div>
      <!-- 测点权重柱状图 -->
      <div class="reportCharts">
        <div id="reportChart" class="chartStyle"></div>
      </div>
      <!-- 测点权重曲线图 -->
      <div class="reportLine">
        <div id="reportLineChart" class="chartsSty"></div>
      </div>
      <!-- 测点权重梯度曲线图 -->
      <div class="reportLine" v-show="showRemark">
        <div id="reportLinetiduChart" class="chartsSty"></div>
      </div>
      <div class="reportTable">
        <el-table :data="reportTable" style="width: 100%" border stripe>
          <el-table-column prop="index" align="center" />
          <el-table-column prop="precision" label="精确度" align="center" />
          <el-table-column prop="recall" label="回归" align="center" />
          <el-table-column prop="f1-score" label="F值" align="center" />
          <el-table-column prop="support" label="可支持数据" align="center" />
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { getAllReportMsg } from "@api/api.js";
import * as echarts from "echarts";
import Get_PDF from "@tools/htmlToPdf.js";
import BASE from "@tools/basicTool.js";
export default {
  data() {
    return {
      showDialog: false,
      reportTable: [],
      reportChartsData: [],
      reportMssage: {
        name: "",
        time: "",
        many: "",
        windname: "",
        beleve: "",
        model: "",
        result: "",
      },
      autoHeight: "",
      allcheckName: [],
      curveLineData: {},
      treeData: {},
      showRemark: true,
    };
  },
  methods: {
    init(row) {
      this.showDialog = true;
      this.getReportDetail(row);
    },
    savePdf() {
      Get_PDF.downloadPDF(
        document.querySelector(".reportMain"),
        "故障诊断报告" + new Date()
      );
    },
    // 获取诊断报告详情
    async getReportDetail(row) {
      const { data } = await getAllReportMsg({
        id: row.id,
      });
      console.log(data);

      if (data) {
        if (data.alarm) {
          this.treeData = JSON.stringify(data.alarm);
          this.getTreeLiness(this.treeData, data.alarm.count);
        }
        if (data.fault && data.info) {
          if (data.fault.remark) {
            this.showRemark = true;
          } else {
            this.showRemark = false;
          }
          this.reportMssage = {
            name: data.info.name,
            time: data.fault.starttime,
            many: 200,
            windname: data.fault.windturbineid,
            beleve: (data.info.accuracy * 1).toFixed(2) * 100 + "%",
            model: data.fault.model,
            result: data.fault.diagnosetype,
          };
          if (data.info.indicators) {
            this.reportTable = JSON.parse(data.info.indicators);
          }
          if (data.info.pointweight) {
            this.reportChartsData = JSON.parse(data.info.pointweight);
            let YaxData = [];
            let sericeData = [];
            let barSericesData = [];
            this.allcheckName = [];
            if (this.reportChartsData && this.reportChartsData.length > 0) {
              this.reportChartsData.forEach((item, index) => {
                if (Number(item.importance).toFixed(2) >= 1) {
                  let sericeDataObj = {
                    name: item.measuring_point,
                    value: (item.importance * 1).toFixed(2),
                    itemStyle: {
                      color: "#24bbcb",
                    },
                  };
                  YaxData.unshift(item.measuring_point);
                  if (index < 4) {
                    this.allcheckName.push(item.measuring_point);
                  }
                  // sericeData.unshift((item.importance*1).toFixed(2))
                  sericeData.unshift(sericeDataObj);
                }
              });
              let ServiceDataObj = {
                name: "测点权重",
                barWidth: 20, //最小柱高
                type: "bar",
                label: {
                  normal: {
                    show: true,
                    position: "right",
                    textStyle: {
                      color: "#b3bdc0",
                      fontSize: 14,
                    },
                    formatter: "{c}", //c后面加单位
                  },
                },
                barCategoryGap: 30,
                data: sericeData,
              };
              barSericesData.push(ServiceDataObj);
            }

            this.getAccuracyBar(
              "reportChart",
              YaxData,
              barSericesData,
              "测点权重"
            );
          }
        }
        if (data.curve) {
          this.curveLineData = data.curve;
          this.changeLineChartsData(data.curve);
        }
        if (data.curve && data.fault) {
          if (data.fault.remark) {
            this.changeLinetiduData(data.fault, data.curve);
          }
        }
      } else {
        this.showDialog = false;
        BASE.showMsg({
          type: "error",
          msg: "服务返回失败",
        });
      }
    },
    // 处理测点权重曲线
    changeLineChartsData(data) {
      let that = this;
      let lengedData = this.allcheckName;
      let xAxis = [];
      let servData = [];

      let markLineDate = "";
      for (let item in data) {
        if (item === this.allcheckName[0]) {
          data[item].forEach((itv, index) => {
            // xAxis.push(index.toString())
            xAxis.push(this.getTime(new Date(itv.ts)));
          });
          markLineDate = that.getTime(
            new Date(data[this.allcheckName[0]][0].ts + 10 * 60 * 1000)
          );
        }
        if (lengedData.includes(item)) {
          let serviceData = [];
          data[item].forEach((itv, index) => {
            serviceData.push(Number(itv.doubleValue).toFixed(4));
          });
          // let savNum = Math.max.apply(null, serviceData)
          let serviceobj = {
            name: item,
            // data: serviceData.map( item =>{ return (item/savNum).toFixed(4)})
            data: serviceData,
          };
          servData.push(serviceobj);
        }
      }
      this.changeServeAndYData(
        "reportLineChart",
        servData,
        xAxis,
        lengedData,
        markLineDate
      );
    },
    // 折线图service数据与Y轴数据处理
    changeServeAndYData(names, servData, xAxis, lengedData, markLineDate) {
      let yAxis = [];
      let allServce = [];
      servData.forEach((iten, index) => {
        let seriesObj = {
          name: iten.name,
          type: "line",
          // stack: '总量',
          smooth: true,
          data: iten.data,
          symbol: "none",
          yAxisIndex: index,
          markLine: {
            lineStyle: {
              width: 2,
              color: "#f7b500",
            },
            data: [
              {
                name: "X 轴值为 10min 的竖直线",
                xAxis: markLineDate,
              },
            ],
          },
        };
        allServce.push(seriesObj);
        let yaxisObj = {
          boundaryGap: ["20%", "20%"],
          axisLine: {
            show: true,
            lineStyle: {
              color:
                index === 0
                  ? "#9bbb59"
                  : index === 1
                  ? "#0B438B"
                  : index === 2
                  ? "#4141F1"
                  : index === 3
                  ? "#F81945"
                  : index === 4
                  ? "#4bacc6"
                  : "#F89E19",
            },
          },

          type: "value",
          name: iten.name,
          position: index % 2 === 0 ? "left" : "right", //Y轴位置
          offset: index < 2 ? 20 : 60 + 20, //坐标轴移动
          // offset: index === 0 ? 20 : index === 1 ? 20 : index === 2 ? 60+20 : 60+20,//坐标轴移动
          axisLabel: {
            formatter: function (value, index) {
              return value;
            },
            textStyle: {
              color: "#999", // 测点权重曲线 Y 轴内容文字颜色
            },
          },
          splitLine: {
            show: false,
          },
          nameLocation: "middle",
          nameGap: 30,
          axisTick: {
            show: true,
            inside: "false",
            length: 10,
          },
        };
        yAxis.push(yaxisObj);
      });
      this.getLine(names, xAxis, lengedData, allServce, yAxis);
    },
    // 处理测点梯度曲线
    changeLinetiduData(obj, data) {
      let objremark = {};
      let remarkData = [];
      let lengedData = [];
      let xaxis = [];
      let serviceData = [];
      let markLineDate = "";
      if (obj.remark) {
        // objremark = JSON.parse(obj.remark)
        objremark = eval("(" + obj.remark + ")");
        for (let item in objremark) {
          for (let itn in data) {
            if (objremark[item] === itn) {
              let obj = {
                name: itn,
                data: data[itn],
              };
              remarkData.push(obj);
            }
          }
        }
        remarkData.forEach((itxc, index) => {
          lengedData.push(itxc.name);
          let service = [];
          itxc.data.forEach((itv, index) => {
            service.push(Number(itv.doubleValue).toFixed(4));
          });
          let serviceobj = {
            name: itxc.name,
            data: service,
          };
          serviceData.push(serviceobj);
        });
        if (remarkData.length > 0) {
          remarkData[0].data.forEach((itbb) => {
            xaxis.push(this.getTime(new Date(itbb.ts)));
            markLineDate = this.getTime(
              new Date(remarkData[0].data[0].ts + 10 * 60 * 1000)
            );
          });
        }
      }
      this.changeServeAndYData(
        "reportLinetiduChart",
        serviceData,
        xaxis,
        lengedData,
        markLineDate
      );
    },
    getAccuracyBar(item, yaxis, seriesFn, name) {
      let myChart = echarts.init(document.getElementById(item));
      let that = this;
      that.autoHeight = "";
      seriesFn[0].data.forEach((item) => {
        item.itemStyle.color = "#24bbcb";
      });
      if (that.allcheckName.length > 0) {
        seriesFn[0].data.forEach((item) => {
          that.allcheckName.forEach((itv) => {
            if (item.name === itv) {
              item.itemStyle.color = "#409eff";
            }
          });
        });
      }
      let option = {
        title: {
          // top: 20,
          left: 20,
          text: name,
          textStyle: {
            fontSize: 14,
            color: "#b3bdc0",
          },
        },
        // legend: {
        //     top: 20,
        // },
        grid: {
          top: "10%",
          left: "10%",
          right: "10%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
          splitLine: {
            show: true,
            lineStyle: {
              type: "dotted",
              color: "#aaa",
            },
          },
        },
        yAxis: {
          type: "category",
          data: yaxis,
          axisLabel: {
            //y轴文字的配置
            textStyle: {
              color: "#b3bdc0", //Y轴内容文字颜色
            },
          },
        },
        series: seriesFn,
      };
      // 基于准备好的dom，初始化echarts实例
      myChart.setOption(option);
      that.autoHeight = yaxis.length * 35 + 50;
      myChart.getDom().style.height = that.autoHeight + "px";
      myChart.getDom().childNodes[0].style.height = that.autoHeight + "px";
      myChart
        .getDom()
        .childNodes[0].childNodes[0].setAttribute("height", that.autoHeight);
      myChart.getDom().childNodes[0].childNodes[0].style.height =
        that.autoHeight + "px";
      myChart.resize();
      //解除绑定事件
      myChart.off("click");
      //点击事件
      myChart.on("click", function (params) {
        if (that.allcheckName.length === 0) {
          that.allcheckName.push(params.name);
        } else {
          that.allcheckName.forEach((itvc, index) => {
            if (that.allcheckName.includes(params.name)) {
              if (itvc === params.name) {
                if (that.allcheckName.length > 1) {
                  that.allcheckName.splice(index, 1);
                }
              }
            } else {
              if (that.allcheckName.length < 4) {
                that.allcheckName.push(params.name);
              }
            }
          });
        }
        if (that.allcheckName.length === 4) {
          BASE.showMsg({
            type: "warning",
            msg: "最多可查看四个测点权重曲线",
          });
        }
        console.log(that.allcheckName);
        that.getAccuracyBar(item, yaxis, seriesFn, name, "no");
        that.changeLineChartsData(that.curveLineData);
      });
    },
    getLine(item, xaxis, legendFn, seriesFn, yAxis) {
      // 绘制图表
      let option = {
        title: {
          top: 20,
          left: 20,
          text:
            item === "reportLineChart" ? "测点权重曲线" : "测点权重梯度曲线",
          textStyle: {
            fontSize: 14,
            color: "#b3bdc0",
          },
        },
        tooltip: {
          trigger: "axis",
        },
        color: [
          "#9bbb59",
          "#0B438B",
          "#4141F1",
          "#F81945",
          "#4bacc6",
          "#F89E19",
        ],
        legend: {
          data: legendFn,
          textStyle: {
            color: "#b3bdc0", //字体颜色
          },
        },
        grid: {
          // left: '3%',
          // right: '4%',
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          splitNumber: 6,
          data: xaxis,
          axisLabel: {
            textStyle: {
              color: "#999", // 测点权重曲线 Y 轴内容文字颜色
            },
          },
          // name: '秒'
        },
        // yAxis: {
        //     type: 'value',
        //     // name: '米/秒(m/s)'
        // },
        yAxis: yAxis,
        series: seriesFn,
      };
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById(item));
      myChart.setOption(option, true);
      myChart.resize();
      // setTimeout(function (){
      //     window.onresize = function () {
      //         myChart.resize();
      //     }
      // },200)
    },
    getTreeLiness(data, value) {
      let alldata = JSON.parse(data);
      let domHeight = document.getElementById("main");
      domHeight.style.height = "";
      let autoHeight = "";
      autoHeight = value * 15 + 300 + "px";
      domHeight.style.height = autoHeight;
      if (domHeight.children.length > 0) {
        domHeight.children[0].style.height = autoHeight;
        domHeight.children[0].children[0].style.height = autoHeight;
      }
      // 绘制图表
      let option = {
        title: {
          top: 20,
          left: 20,
          text: "报警详情",
          textStyle: {
            fontSize: 14,
            color: "#b3bdc0",
          },
        },
        tooltip: {
          trigger: "item",
          triggerOn: "mousemove",
        },
        series: [
          {
            type: "tree",
            id: 0,
            name: "tree1",
            data: [alldata],
            // top: '10%',
            left: "8%",
            // bottom: '22%',
            right: "30%",
            symbolSize: 7,
            edgeShape: "polyline",
            edgeForkPosition: "50%",
            initialTreeDepth: 3,
            lineStyle: {
              width: 2,
            },
            label: {
              backgroundColor: "rgb(18,29,28)",
              position: "left",
              verticalAlign: "middle",
              align: "right",
              color: "#fff",
            },
            leaves: {
              label: {
                position: "right",
                verticalAlign: "middle",
                align: "left",
              },
            },
            emphasis: {
              focus: "descendant",
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750,
          },
        ],
      };
      // 基于准备好的dom，初始化echarts实例
      let myChart2 = echarts.init(document.getElementById("main"));
      //解除绑定事件
      myChart2.off("click");
      //点击事件
      myChart2.on("click", function (params) {
        // myChart2.clear()
      });
      myChart2.setOption(option, true);
      myChart2.resize();
    },
    //转换时间
    getTime(date) {
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? "0" + minute : minute;
      var second = date.getSeconds();
      second = second < 10 ? "0" + second : second;
      return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
    },
  },
};
</script>

<style lang="less">
.modal {
  .el-dialog__body {
    max-height: 600px;
    overflow-y: scroll;
  }
}

.el-dialog {
  // margin-top: 5vh !important;
  .el-dialog__header {
    .el-dialog__title {
      font-size: 20px;
      font-weight: 600;
      margin-top: 50px;
    }
  }
  .el-dialog__body {
    .exportPDF {
      position: absolute;
      right: 50px;
      z-index: 100;
    }
    .reportMain {
      padding: 0px 50px;
      .mainTitle {
        margin: 30px 0;
        font-size: 20px;
        font-weight: 600;
        text-align: center;
        color: #b3bdc0;
      }
      .titleCol {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: #b3bdc0;
        p {
          width: 120px;
          font-size: 14px;
          font-weight: 600;
        }
      }
      .reportTitle {
        .titleRwo {
          margin-top: 10px;
        }
        .reportMsg {
          margin: 20px 0;
          margin-bottom: 10px;
          .title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #b3bdc0;
          }
          .mssage {
            span {
              color: red;
            }
          }
          .msgStyle {
            margin-left: 20px;
          }
        }
      }

      .reporttreeDDA {
        .charttreeStyle {
          width: 100%;
          // height: 400px;
        }
      }
      .reportCharts {
        .chartStyle {
          width: 100%;
          // min-height: 500px;
        }
      }
      .reportLine {
        margin-top: 20px;
        .chartsSty {
          width: 100%;
          height: 400px;
        }
      }
      .reportTable {
        margin: 10px 0;
      }
    }
  }
}
</style>