<template>
  <div class="totalCurveChartBox">
    <div class="l">
      <el-tree
        v-if="currentNodeKey"
        accordion
        highlight-current
        node-key="id"
        :data="treeData"
        :props="{
          children: 'children',
          label: 'label',
        }"
        @node-click="nodeClick"
        :default-expanded-keys="defaultTreeData"
        :default-checked-keys="defaultTreeData"
        :current-node-key="currentNodeKey"
      />
    </div>
    <div class="r">
      <CurrentScatterChart
        width="100%"
        height="90%"
        :xAxisData="xAxisData"
        :yAxisData="{ splitLine: { show: false } }"
        :seriesData="seriesData"
        :showLegend="true"
        :brushSelected="true"
        @getSelected="getSelected"
      />
    </div>
    <el-dialog
      top="100px"
      :title="wtId + (tableData.length ? ' (' + tableData.length + '条)' : '')"
      custom-class="modal"
      v-model="showDialog"
      width="80%"
      @closed="
        (res) => {
          showDialog = false;
          tableData = [];
          lassoTable = [];
          gzlx = '';
          gzItem = null;
        }
      "
    >
      <div class="chartDialogBox">
        <div class="l">
          <el-table
            :data="tableData"
            style="width: 100%; height: 600px; overflow-y: scroll"
            height="250"
            border
          >
            <el-table-column
              prop="sj"
              label="时间"
              width="200px"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="fs"
              label="风速(m/s)"
              sortable
              align="center"
            ></el-table-column>
            <el-table-column
              prop="gl"
              label="功率(kw)"
              sortable
              align="center"
            ></el-table-column>
          </el-table>
        </div>
        <div class="r">
          <el-table
            :data="lassoTable"
            style="width: 100%; height: 600px; overflow-y: scroll"
            height="250"
            border
            row-key="value"
          >
            <el-table-column prop="label" label="故障分类" width="130" />
            <el-table-column prop="warntime" label="故障时间" align="center" />
            <el-table-column prop="warndes" label="故障描述" align="center" />
            <el-table-column
              prop="model"
              label="机型"
              align="center"
              width="100"
            />
          </el-table>
          <el-table
            :data="lassoTable"
            style="width: 100%; height: 600px; overflow-y: scroll"
            height="250"
            border
            v-if="false"
          >
            <el-table-column type="expand">
              <template #default="props">
                <el-table
                  :data="props.row.children"
                  style="width: 100%"
                  height="250"
                  border
                >
                  <el-table-column
                    prop="warntime"
                    label="故障时间"
                    align="center"
                  />
                  <el-table-column
                    prop="warndes"
                    label="故障描述"
                    align="center"
                  />
                  <el-table-column prop="model" label="机型" align="center" />
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="label" label="故障类型" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <span class="gzlxTitle" :class="!gzlx ? 'twinkle' : ''"
            >故障类型：</span
          >
          <el-select
            style="width: 150px"
            v-model="gzlx"
            clearable
            placeholder="请选择"
            popper-class="select"
            @change="gzlxChange"
          >
            <el-option
              v-for="item in gzlxArray"
              :key="item.id"
              :value="item._index"
              :label="item.name"
            >
            </el-option>
          </el-select>
          <el-button
            class="btn green"
            type="success"
            style="margin-left: 12px"
            @click="save"
            :disabled="!gzlx && !gzItem"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import CurrentScatterChart from "../../components/chart/scatter/current-scatter-chart.vue";
import axios from "axios";
export default {
  components: {
    CurrentScatterChart,
  },
  data() {
    return {
      treeData: [],
      defaultTreeData: [], //默认选中数据
      xAxisData: [],
      seriesData: [],
      station: "",
      wtId: "",
      time: "",
      showDialog: false,
      tableData: [],
      gzlx: "",
      gzlxArray: [],
      gzItem: null,
      currentNodeKey: "",
      lassoTimeArray: [],
      lassoTable: [],
    };
  },
  created() {
    this.getTree();
    this.getGzlx();
  },
  methods: {
    getLassoData() {
      const that = this;
      that.API.requestData({
        method: "POST",
        baseURL: "http://192.168.10.5:9002/",
        subUrl: "powercurve/lasso",
        data: {
          station: "NSS_FDC",
          wtid: "NG01_70",
          time: that.lassoTimeArray.toString(),
        },
        success(res) {
          let lassoTable = res.data.data;
          lassoTable.forEach((pEle) => {
            if (pEle.children?.length) {
              pEle.sortNum = pEle.children.length;
              pEle.label += `(${pEle.children.length}条)`;
            } else {
              pEle.sortNum = 0;
              pEle.label += "(0条)";
            }
            pEle.children.forEach((cEle) => {
              cEle.label = "---";
            });
          });
          lassoTable.sort((a, b) => {
            return b.sortNum - a.sortNum;
          });
          that.lassoTable = lassoTable;
        },
      });
    },
    // 选择故障类型
    gzlxChange(idx) {
      let gzItem = this.gzlxArray.find((ele) => {
        return ele._index === idx;
      });
      this.gzItem = gzItem;
    },
    // 获取树形数据
    getTree() {
      const that = this;
      that.API.requestData({
        method: "GET",
        baseURL: "http://192.168.1.18:9002/",
        subUrl: "powercurve/tree",
        success(res) {
          that.treeData = that.addLabelToTreeData(res.data);
          // 初始化第一条
          that.defaultTreeData.push(res.data[0].id);
          that.defaultTreeData.push(res.data[0].children[0].id);
          that.defaultTreeData.push(res.data[0].children[0].children[0].id);
          that.defaultTreeData.push(
            res.data[0].children[0].children[0].children[0].id
          );
          let getFirstTreeData = that.getFirstTreeData(res.data[0]);
          that.currentNodeKey = getFirstTreeData.id;
          that.station = getFirstTreeData.stationen;
          that.wtId = getFirstTreeData.windturbineid;
          that.time = getFirstTreeData.time;
          that.getChartData();
        },
      });
    },

    // 获取树形数据
    getGzlx() {
      const that = this;
      that.API.requestData({
        method: "GET",
        baseURL: "http://192.168.1.18:9002/",
        subUrl: "know/fault/type/all",
        success(res) {
          res.data.forEach((ele, index) => {
            ele._index = index;
          });
          that.gzlxArray = res.data;
        },
      });
    },

    // 树形结构点击处理
    nodeClick(res) {
      if (!res.children) {
        this.station = res.stationen;
        this.wtId = res.windturbineid;
        this.time = res.time;
        this.getChartData();
      }
    },

    // 获取树状结构内第一个节点内的第一条数据
    getFirstTreeData(treeData) {
      if (treeData?.children) {
        return this.getFirstTreeData(treeData.children[0]);
      } else {
        return treeData;
      }
    },

    // 给树状结构最后一层添加label字段
    addLabelToTreeData(treeData) {
      for (let i = 0; i < treeData.length; i++) {
        const item = treeData[i];
        if (Array.isArray(item?.children)) {
          this.addLabelToTreeData(item.children);
        } else {
          treeData.forEach((ele) => {
            ele.label = ele.windturbineid;
          });
        }
      }
      return treeData;
    },

    // 获取图表数据
    getChartData() {
      const that = this;
      that.API.requestData({
        method: "POST",
        baseURL: "http://192.168.1.18:9002/",
        subUrl: "scatter/list",
        showLoading: true,
        data: {
          station: that.station,
          wtId: that.wtId,
          time: that.time,
        },
        success(res) {
          if (
            !res.data.lineactual?.length &&
            !res.data.lineoptimal?.length &&
            !res.data.scatter?.length
          ) {
            that.BASE.showMsg({
              type: "success",
              msg: "所选风机暂无图表数据，请更换风机后尝试",
            });
          }
          let sjgl = [];
          let zygl = [];
          let fsgl = [];
          let xAxisData = [];

          res.data.lineactual.forEach((ele, index) => {
            sjgl.push(ele[1]);
            xAxisData.push(index);
          });

          res.data.lineoptimal.forEach((ele) => {
            zygl.push(ele[1]);
          });

          res.data.scatter.forEach((ele) => {
            if (ele[1] >= 0) fsgl.push(ele);
          });

          that.seriesData = [
            {
              name: "风速功率",
              type: "effectScatter",
              showEffectOn: "emphasis",
              symbolSize: 5,
              data: fsgl,
              xAxisIndex: 1,
            },
            {
              name: "实际功率",
              type: "line",
              symbol: "circle", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: sjgl,
              itemStyle: {
                normal: {
                  color: "#05bb4c",
                  lineStyle: {
                    color: "#05bb4c",
                  },
                },
              },
              xAxisIndex: 0,
            },
            {
              name: "最优功率",
              type: "line",
              symbol: "circle", //设定为实心点
              symbolSize: 0, //设定实心点的大小
              smooth: true, //这个是把线变成曲线
              data: zygl,
              itemStyle: {
                normal: {
                  color: "#f8de5b",
                  lineStyle: {
                    color: "#f8de5b",
                  },
                },
              },
              xAxisIndex: 0,
            },
          ];

          that.xAxisData = xAxisData;
        },
      });
    },

    // 获取图表框选结果
    getSelected(res) {
      const seriesIndex = res[0]?.selected[0]?.seriesIndex;
      const selected = res[0]?.selected[0]?.dataIndex;
      let lassoTimeArray = [];
      if (selected?.length) {
        let tableData = [];
        selected?.forEach((seleIndex) => {
          const item = this.seriesData[seriesIndex].data[seleIndex];
          tableData.push({
            fs: item[0],
            gl: item[1],
            sj: item[2],
          });
          lassoTimeArray.push(item[2]);
        });
        this.lassoTimeArray = lassoTimeArray;
        this.getLassoData();
        this.tableData = tableData;
        this.showDialog = true;
      }
    },

    // 保存
    save() {
      const that = this;
      let data = [];
      that.tableData.forEach((ele) => {
        data.push({
          tag: "0",
          windturbineid: that.wtId,
          faulttype: that.gzItem.name,
          faultcode: that.gzItem.code,
          starttime: ele.sj,
          stationen: that.station,
          category: "1",
        });
      });
      this.BASE.showLoading();
      axios({
        method: "post",
        url: "http://192.168.1.18:9002/case/fault/insert",
        data,
        header: {
          "Content-Type": "application/json",
        },
      }).then((res) => {
        if (res.data.code === 200) {
          let lassoData = [];

          this.lassoTable.forEach((pEle) => {
            pEle.children.forEach((cEle) => {
              lassoData.push(cEle);
            });
          });

          axios({
            method: "post",
            url: "http://192.168.10.5:9002/case/warning/insert",
            data: lassoData,
            header: {
              "Content-Type": "application/json",
            },
          }).then((res) => {
            if (res.data.code === 200) {
              that.showDialog = false;
              that.BASE.showMsg({
                type: "success",
                msg: "保存成功",
              });
              that.BASE.closeLoading();
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.totalCurveChartBox {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  height: 100%;

  .l {
    width: 15%;
    height: 100%;
    .el-tree {
      height: 100%;
    }
  }

  .r {
    width: 85%;
    height: 100%;
    margin-left: 20px;
  }

  .gzlxTitle {
    color: rgb(179, 189, 192);
    transition: 0.2s;
  }

  .gzlxTitle.twinkle {
    animation: twinkle 0.75s infinite;
  }

  @keyframes twinkle {
    0% {
      color: rgb(179, 189, 192);
    }
    50% {
      color: #f25656;
    }
    100% {
      color: rgb(179, 189, 192);
    }
  }

  .chartDialogBox {
    width: 100%;
    display: flex;
    justify-content: start;
    align-items: center;

    .l,
    .r {
      width: 50%;
    }
  }
}
</style>

<style lang="less">
.totalCurveChartBox {
  .el-dialog__body {
    max-height: 620px;
    overflow: hidden;
  }
  .el-table__expand-icon {
    color: #b3bdc0;
  }
}
</style>