<template>
  <div class="alarm-center-1">
    <el-card>
      <div class="action-bar">
        <el-space wrap :size="30">
          <div class="search-input" v-if="!isStation">
            <span class="lable">风场：</span>
            <el-select
              v-model="wpvalue"
              clearable
              placeholder="请选择"
              popper-class="select"
            >
              <el-option
                v-for="item in wpoptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="search-input">
            <span class="lable">开始日期：</span>
            <el-date-picker
              v-model="startdate"
              type="date"
              placeholder="选择日期"
              popper-class="date-select"
            >
            </el-date-picker>
          </div>
          <div class="search-input">
            <span class="lable">结束日期：</span>
            <el-date-picker
              v-model="enddate"
              type="date"
              placeholder="选择日期"
              popper-class="date-select"
            >
            </el-date-picker>
          </div>
          <div class="query-item">
            <span class="lable">规则：</span>
            <el-cascader
              popper-class="search-select"
              :options="cascaderOptions"
              :props="cascaderProps"
              v-model="cascaderSel"
              collapse-tags
              :clearable="true"
            ></el-cascader>
          </div>
          <el-button class="btn green" type="primary" @click="searchData"
            >查询</el-button
          >
          <!-- <el-button class="btn green" type="primary" @click="searchTree"
              >筛选</el-button
            > -->
        </el-space>
      </div>
      <panel-3 class="table-panel">
        <table-3 :data="tableData" :height="'75vh'">
          <template v-for="(item, i) in column" :key="i" #[item]="scope">
            <div class="bar" @click="showChart(scope)">
              <div
                class="bar-percent"
                :style="{
                  width:
                    (scope.data?.count /
                      (scope.data?.count + scope.data?.time)) *
                      100 +
                    'px',
                }"
              ></div>
              <span class="value">{{ scope.data?.count }} 次数</span>
            </div>
            <div class="bar" @click="showChart(scope)">
              <div
                class="bar-percent"
                :style="{
                  width:
                    (scope.data?.time /
                      (scope.data?.count + scope.data?.time)) *
                      100 +
                    'px',
                }"
              ></div>
              <span class="value">{{ timeFifter(scope.data?.time) }} 分钟</span>
            </div>
          </template>
        </table-3>
      </panel-3>
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="70%"
        top="10vh"
        custom-class="modal"
        :close-on-click-modal="false"
      >
        <div class="searchForm">
          <div class="choose">
            <el-button @click="export2Excel">导出</el-button>
            <!-- <button :class="chooseStatus?'btn green':'btn'" @click="switchChange(1,'original')">原始数据</button> -->
          </div>
          <el-select
            v-if="!chooseStatus"
            @change="switchChange(selectValue)"
            class="inputs"
            v-model="selectValue"
            placeholder="请选择"
          >
            <el-option
              v-for="item in timeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <multiple-y-line-chart-normal
          height="500px"
          :list="Analysis"
          :yAxises="AnalysisYAxises"
          :showLegend="true"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
Date.prototype.formatDate = function (fmt) {
  let o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (let k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
import Panel3 from "/@/components/warningCom/panel3.vue";
import Table3 from "/@/components/warningCom/table3.vue";
import MultipleYLineChartNormal from "/@/components/warningCom/multiple-y-line-chart-normal.vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import {
  getStationinfoAll,
  warning_query_new,
  warning_detail,
} from "/@/api/api.js";
import { outExportExcel } from "/@/utils/exportExcel"; //引入文件
export default {
  components: { Panel3, Table3, MultipleYLineChartNormal },
  data() {
    return {
      dialogTitle: "",
      chooseStatus: false,
      dialogVisible: false,
      chooseTime: [],
      wpvalue: "",
      wpid: "",
      wtId: "",
      descName: "",
      AnalysisName: "",
      AnalysisUnit: "",
      Analysis: [
        {
          title: "",
          yAxisIndex: 0, // 使用单位
          value: [],
        },
      ],
      AnalysisYAxises: [],
      selectValue: "600",
      timeoptions: [
        {
          value: "60",
          label: "一分钟",
        },
        {
          value: "300",
          label: "五分钟",
        },
        {
          value: "600",
          label: "十分钟",
        },
        {
          value: "1800",
          label: "三十分钟",
        },
        {
          value: "3600",
          label: "一小时",
        },
        {
          value: "86400",
          label: "一天",
        },
      ],
      wpoptions: [],
      options: [],
      cascaderOptions: [],
      cascaderSel: [],
      cascaderProps: { multiple: true },
      column: [],
      columnObj: [],
      startdate: dayjs(
        new Date(new Date() - 1 * 24 * 60 * 60 * 1000)
      ).format("YYYY-MM-DD"),
      enddate: dayjs(new Date()).format("YYYY-MM-DD"),
      tableData: {
        column: [
          { name: "风机编号", field: "name" },
          {
            name: "主轴温度温差大于8度",
            field: "v1",
            align: "left",
            slot: true,
          },
          { name: "浆叶角过小", field: "v2", align: "left", slot: true },
        ],
        data: [{ name: "MG01_01", v1: { count: 12, time: 0 } }],
      },
    };
  },
  created() {
    this.$nextTick(() => {
      this.search();
    });
  },
  computed: {
    stationList() {
      return this.$store.state.stationList;
    },
    isStation() {
      return this.$store.getters.isStation;
    },
  },
  methods: {
    // 批量导出
    async export2Excel() {
      ElMessage.success(`导出成功!`);
      let tableHeader = ["时间"];
      let tableKey = ["time"];
      let data = [];
      let timeList = this.Analysis[0]?.data.map((e) => {
        return e.ts;
      });
      this.Analysis.forEach((e, index) => {
        tableHeader.push(e.name);
        tableKey.push(e.name);
        if (index == 0) {
          e.data.forEach((k) => {
            let obj = {};
            obj["time"] = k.ts;
            obj[e.name] = k.doubleValue;
            data.push(obj);
          });
        } else {
          e.data.forEach((k) => {
            data.forEach((v) => {
              if (k.ts == v.time) {
                v[e.name] = k.doubleValue;
              }
            });
          });
        }
      });
      data.forEach((e) => {
        e.time = dayjs(e.time).format("YYYY-MM-DD HH:mm:ss");
      });
      outExportExcel(tableHeader, tableKey, data, "导出excel");
    },
    timeFifter(v) {
      return v?.toFixed(2);
    },
    //对比
    showChart(column) {
      let that = this;
      that.dialogTitle = column.column.name;
      that.wtId = column.row.name;
      that.descName = column.column.name;

      that.requestDetailData(
        that.wpvalue,
        that.startdate,
        that.enddate,
        600,
        column.row.name,
        column.column.name
      );
    },
    async requestDetailData(station, startTs, endTs, interval, wtId, name) {
      const res = await warning_detail({
        station: station,
        startTs: dayjs(startTs).valueOf(),
        endTs: dayjs(endTs).valueOf(),
        interval: interval,
        wtId: wtId,
        name: name,
      });
      this.dialogVisible = true;
      this.Analysis = res.data;

      res.data.forEach((e) => {
        let obj = {
          name: e.name,
          min: 0,
          max: null,
          unit: e.name,
          position: "left",
        };
        this.AnalysisYAxises.push(obj);
      });
      this.AnalysisYAxises = res.data.map((v) => {
        return v.name;
      });
    },
    //切换数据类型
    switchChange(interval, status) {
      if (status === "interval") {
        this.chooseStatus = false;
        this.selectValue = "60";
      } else if (status === "original") {
        this.chooseStatus = true;
      }
      this.requestDetailData(
        this.wpvalue,
        this.startdate,
        this.enddate,
        interval,
        this.wtId,
        this.descName
      );
    },
    //获取场站
    async search() {
      const { data } = await getStationinfoAll();
      this.wpoptions = data;
      this.wpvalue = data[0].id;
      this.searchData();
    },

    async searchData() {
      if (this.cascaderSel.length > 0) {
        let arr = [];
        let columnObj = [
          {
            name: "风机编号",
            field: "name",
            minWidth: "100px",
          },
        ];
        this.cascaderSel.forEach((e) => {
          let obj = {
            name: Array.isArray(e) ? e[1] : e,
            field: Array.isArray(e) ? e[1] : e,
            align: "left",
            slot: true,
            sortable: true,
            minWidth: "200px",
          };
          columnObj.push(obj);

          arr.push(Array.isArray(e) ? e[1] : e);
        });
        this.columnObj = columnObj;
        this.column = arr;
      } else {
        this.columnObj = [
          {
            name: "风机编号",
            field: "name",
            width: "100px",
            minWidth: "100px",
          },
          {
            name: "收桨不到位",
            field: "收桨不到位",
            align: "left",
            slot: true,
            sortable: true,
            minWidth: "200px",
          },
          {
            name: "齿轮箱轴承温升超过40度",
            field: "齿轮箱轴承温升超过40度",
            align: "left",
            slot: true,
            sortable: true,
            minWidth: "200px",
          },
          {
            name: "三相电流不平衡",
            field: "三相电流不平衡",
            align: "left",
            slot: true,
            sortable: true,
            minWidth: "200px",
          },
          {
            name: "风向突变",
            field: "风向突变",
            align: "left",
            slot: true,
            sortable: true,
            minWidth: "200px",
          },
          {
            name: "风速突变",
            align: "left",
            field: "风速突变",
            slot: true,
            sortable: true,
            minWidth: "200px",
          },
        ];
        this.column = [
          "收桨不到位",
          "齿轮箱轴承温升超过40度",
          "三相电流不平衡",
          "风向突变",
          "风速突变",
        ];
      }
      const data = await warning_query_new({
        stationid: this.wpvalue,
        startdate: dayjs(this.startdate).format("YYYY-MM-DD"),
        enddate: dayjs(this.enddate).format("YYYY-MM-DD"),
        windturbineid: "",
      });
      ////////
      const resData = data.data;
      // const resData =this.resdata;
      const column = this.columnObj;
      let dataAll = []; // 总数据集合
      // resData.forEach((e) => {
      //   let obj = {
      //     name: Object.keys(e)[0],
      //   };
      //   let wpid = Object.keys(e)[0];
      //   this.wpid = wpid;

      //   e[wpid].forEach((k) => {
      //     column.forEach((c) => {
      //       if (k.alertText == c.name) {
      //         let obj1 = {
      //           count: k.count,
      //           time: k.time,
      //         };
      //         obj[k.alertText] = obj1;
      //       }
      //     });
      //   });
      //   dataAll.push(obj);
      // });

      ///////////////////// 获取规则list
      const map = {};
      var windNum = [];
      for (let i in resData) {
        for (let k in resData[i]) {
          map[k] = resData[i][k];
        }
      }
      // nmap为新的map 整理数据结构
      const nmap = {};
      for (let kv in map) {
        var nchildMap = {};
        var childrenMap = map[kv];
        for (var ckv in childrenMap) {
          var cckey = childrenMap[ckv].alertText;
          var ccvalue = childrenMap[ckv];
          nchildMap[cckey] = ccvalue;
        }
        nmap[kv] = nchildMap;
      }
      windNum = Object.keys(nmap);
      var cascaderOptions = [];
      var root = {}; // 原始根节点
      var clumnsOnes = nmap[windNum[0]];
      for (let k in clumnsOnes) {
        let f = clumnsOnes[k].relatePartsText
          ? clumnsOnes[k].relatePartsText
          : "其他";
        let fvalue = clumnsOnes[k].relateParts ? clumnsOnes[k].relateParts : "";

        if (root[f]) {
          // 已经存在此子节点
          if (!root[f].children[k]) {
            // 不存在子节点
            root[f].children[k] = {};
            root[f].children[k].value = root[f].children[k].label = k;
            root[f].fobj.children.push(root[f].children[k]);
          }
        } // 不存在子节点
        else {
          root[f] = {};
          // root[f].value = fvalue;
          // root[f].label = f;
          root[f].children = {};
          root[f].children[k] = {};
          root[f].children[k].value = root[f].children[k].label = k;

          // 将对象放入 cascaderOptions
          let childrenArray = [];
          childrenArray.push(root[f].children[k]);
          let fobj = {};
          fobj.value = fvalue;
          fobj.label = f;
          fobj.children = childrenArray;
          cascaderOptions.push(fobj);
          root[f].fobj = fobj;
        }
      }
      this.cascaderOptions = cascaderOptions;

      // set1.针对如果表格前几列没有数据的话则以表格数据第一条为基准遍历所有数据并把有数据的列挪至前排的需求增加的代码
      if (!this.cascaderSel.length) {
        let missNum = 0;
        for (let i = 0; i < column.length; i++) {
          let ele = column[i];
          if (ele.field !== "name") {
            column.splice(i, 1);
            missNum++;
            i--;
          }
        }
        if (missNum) {
          let newColumn = [];
          for (let key in resData[0]) {
            let first = resData[0][key];
            first.forEach((ele) => {
              if (ele.count && missNum) {
                column.push({
                  field: ele.alertText,
                  name: ele.alertText,
                  slot: true,
                  sortable: true,
                  align: "left",
                });
                newColumn.push(ele.alertText);
                this.cascaderSel.push(ele.alertText);
              }
            });
            this.column = newColumn;
          }
        }
      }

      resData.forEach((e) => {
        let obj = {
          name: Object.keys(e)[0],
        };
        let wpid = Object.keys(e)[0];
        this.wpid = wpid;

        e[wpid].forEach((k) => {
          column.forEach((c) => {
            if (k.alertText == c.name) {
              let obj1 = {
                count: k.count,
                time: k.time,
              };
              obj[k.alertText] = obj1;
            }
          });
        });
        dataAll.push(obj);
      });
      // set1.到此为止

      this.tableData.column = column;
      this.tableData.data = dataAll;
    },
  },
};
</script>

<style lang="less" scoped>
.alarm-center-1 {
  .action-bar {
    margin-bottom: 20px;
  }

  .table-panel {
    width: 100%;
    background: transparent;
    padding: 0;

    .bar {
      display: flex;
      align-items: center;
      height: 16px;
      margin: 8px 0;

      .bar-percent {
        height: 100%;
        background: #6198ff;
        margin-right: 8px;
      }
    }
  }

  .searchForm {
    display: flex;
    margin-left: 36px;
    flex-direction: row-reverse;

    .inputs {
      width: 15%;
      margin-right: 18px;
    }
  }
}
</style>
