<template>
  <el-dialog
    width="70%"
    @open="opened"
    @closed="closed"
    :fullscreen="true"
    :show-close="true"
    class="dialogs"
  >
    <template #title>
      <div class="showTitles currentShowTitles">
        <div class="titles">预警查询</div>
      </div>
    </template>
    <div class="body">
      <div class="searchTitle">
        <div class="search">
          <div class="lable">风场：</div>
          <div class="search-input">
            <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>
        <div class="search">
          <div class="date">日期:</div>
          <el-date-picker
            class="pickers"
            @change="changes"
            v-model="timeValue"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <div class="search">
          <div class="lable">规则：</div>
          <el-cascader
            style="width: 240px"
            size="mini"
            popper-class="search-select"
            :options="cascaderOptions"
            :props="cascaderProps"
            v-model="cascaderSel"
            collapse-tags
            :clearable="true"
          ></el-cascader>
        </div>

        <div class="buttons" @click="searchData()">搜索</div>
        <div class="buttons" @click="searchTree()">筛选</div>
        <!-- <div class="buttons" @click="fx()">分析</div> -->
      </div>
      <panel-3 class="table-panel">
        <table-3 :data="tableData" :height="'82vh'">
          <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?.countStyle }"
              ></div>
              <span class="value">{{ scope?.data?.count }} 次数</span>
            </div>

            <div class="bar" @click="showChart(scope)">
              <div
                class="bar-percent"
                :style="{ width: scope?.data?.timeStyle }"
              ></div>
              <span class="value">{{ scope?.data?.time }} 分钟</span>
            </div>
          </template>
        </table-3>
      </panel-3>
    </div>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="70%"
      top="10vh"
      custom-class="modal"
      :close-on-click-modal="false"
    >
      <div class="model">
        <div class="selects">
          <el-select
            @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>
        <div class="choose">
          <!-- <div class="interval_on">等间隔</div> -->
          <!-- <div class="original_on" @click="switchChange">原始数据</div> -->
        </div>
      </div>

      <!-- <div class="searchForm">
       <el-select
        @change="searchTime(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 class="choose">
        <button class="btn"
          @click="switchChange(60)"
        >
          等间隔
        </button>
        <button class="btn"
          @click="switchChange(0)"
        >
          原始数据
        </button>
      </div>
    </div> -->

      <multiple-y-line-chart-normal
        height="500px"
        :list="Analysis"
        :yAxises="AnalysisYAxises"
        :showLegend="true"
      />
    </el-dialog>
    <!-- <el-dialog
      :title="dialogTitleFX"
      v-model="dialogVisibleFX"
      width="70%"
      top="10vh"
      custom-class="modal"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <FX :date="startdate" :wpid="wpvalue" />
    </el-dialog> -->
  </el-dialog>
</template>

<script>
import Panel3 from "../panel/panel3.vue";
import Table3 from "../table/table3.vue";
import dayjs from "dayjs";
import api from "api/index";
import MultipleYLineChartNormal from "./multiple-y-line-chart-normal.vue";
export default {
  components: {
    Panel3,
    Table3,
    MultipleYLineChartNormal,
    // FX,
  },
  data() {
    return {
      dialogTitleFX: "",
      dialogVisibleFX: false,
      dialogTitle: "",
      chooseStatus: false,
      dialogVisible: false,
      chooseTime: [],
      timeValue: [],
      wpvalue: "",
      wpid: "",
      wtId: "",
      descName: "",
      AnalysisName: "",
      AnalysisUnit: "",
      Analysis: [
        {
          title: "",
          yAxisIndex: 0, // 使用单位
          value: [],
        },
      ],
      AnalysisYAxises: [
        {
          name: "",
          min: "",
          max: "",
          unit: "",
          position: "left",
        },
        {
          name: "",
          min: "",
          max: "",
          unit: "",
          position: "right",
        },
      ],
      selectValue: "60",
      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: [
        "风机偏航过程震动",
        "齿轮箱轴承温升超过40度",
        "三相电流不平衡",
        "断轴或联轴器打滑",
        "风速突变",
      ],
      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",
        },
      ],
      startdate: dayjs(
        new Date(new Date().setDate(new Date().getDate() - 1))
      ).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: [
        ],
      },
    };
  },
  methods: {
    opened() {
      this.timeValue[0] = new Date(new Date().toDateString()).getTime()- 86400000;
      this.timeValue[1] = new Date(new Date().toDateString()).getTime();
      this.$nextTick(() => {
        this.search();
      });
    },
    //对比
    showChart(column) {
      let that = this;
      that.dialogTitle = column.column.name;
      that.wtId = column.row.name;
      that.descName = column.column.name;

      that.requestDetailData(
        that.wpvalue,
        this.timeValue[0],
        this.timeValue[1],
        60,
        column.row.name,
        column.column.name
      );
    },
    requestDetailData(station, startTs, endTs, interval, wtId, name) {
      api
        .analysisDetail({
          station: station,
          startTs: startTs,
          endTs: endTs,
          interval: interval,
          wtId: wtId,
          name: name,
        })
        .then((res) => {
          if (res.data.data.length == 1) {
            this.dialogVisible = true;
            let yaxises = [
              {
                name: "",
                min: 0,
                max: null,
                unit: "",
                position: "left",
              },
            ];
            // yaxises.name = res.data[0].name;
            yaxises.unit = res.data.data[0].unit;
            this.AnalysisYAxises = yaxises;
            let aKey1 = ["doubleValue"];
            let aList1 = [
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
            ];
            aKey1.forEach((keyEle, keyIndex) => {
              aList1[keyIndex].title = res.data.data[keyIndex].name;
              res.data.data[keyIndex].data.forEach((rEle) => {
                aList1[keyIndex].value.push({
                  text: dayjs(rEle.ts).format("hh:mm"),
                  value: rEle.doubleValue,
                });
              });
            });
            this.Analysis = aList1;
          } else if (res.data.data.length == 2) {
            this.dialogVisible = true;
            let aKey2 = ["doubleValue", "doubleValue"];
            let aList2 = [
              {
                title: "",
                //  yAxisIndex:"",
                smooth: true,
                value: [],
              },
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
            ];
            let yaxises1 = [
              {
                name: "",
                min: 0,
                max: null,
                unit: "",
                position: "left",
              },
              {
                name: "",
                min: 0,
                max: null,
                unit: "",
                position: "right",
              },
            ];
            yaxises1.forEach((aEle, aIndex) => {
              res.data.data.forEach((rEle) => {
                // aEle.name = rEle.name;
                aEle.unit = rEle.unit;
              });
            });
            this.AnalysisYAxises = yaxises1;
            aKey2.forEach((keyEle, keyIndex) => {
              aList2[keyIndex].title = res.data.data[keyIndex].name;
              res.data.data[keyIndex].data.forEach((rEle) => {
                aList2[keyIndex].value.push({
                  text: dayjs(rEle.ts).format("hh:mm"),
                  value: rEle.doubleValue,
                });
              });
            });
            // res.data.forEach((rEle,rIndex)=>{
            // })
            // aKey2.forEach((keyEle, keyIndex) => {
            //   res.data.forEach((rEle) => {
            //     // alist2[keyIndex].yAxisIndex = keyIndex;
            //     aList2[keyIndex].title = res.data[keyIndex].name;
            //     rEle.data.forEach((tEle,tIndex) => {
            //       aList2[keyIndex].value.push({
            //         text: new Date(tEle.ts).formatDate("hh:mm"),
            //         // value: tEle[keyEle],
            //         // value:res.data[keyIndex].data[tIndex].doubleValue

            //       });
            //     });
            //   });
            // });

            this.Analysis = aList2;
          } else if (res.data.data.length == 4) {
            this.dialogVisible = true;
            let aKey4 = [
              "doubleValue",
              "doubleValue",
              "doubleValue",
              "doubleValue",
            ];
            let aList4 = [
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
              {
                title: "",
                // yAxisIndex:"",
                smooth: true,
                value: [],
              },
            ];
            let yaxises2 = [
              {
                name: "",
                min: 0,
                max: null,
                unit: "",
                position: "left",
              },
              {
                name: "",
                min: 0,
                max: null,
                unit: "",
                position: "right",
              },
            ];
            yaxises2.forEach((aEle, aIndex) => {
              res.data.data.forEach((rEle) => {
                // aEle.name = rEle.name;
                aEle.unit = rEle.unit;
              });
            });
            this.AnalysisYAxises = yaxises2;
            aKey4.forEach((keyEle, keyIndex) => {
              aList4[keyIndex].title = res.data.data[keyIndex].name;
              res.data.data[keyIndex].data.forEach((rEle) => {
                aList4[keyIndex].value.push({
                  text: dayjs(rEle.ts).format("hh:mm"),
                  value: rEle.doubleValue,
                });
              });
            });
            this.Analysis = aList4;
          } else if (res.data.data.length == 0) {
            this.dialogVisible = false;
          }
        });
    },
    //切换数据类型
    switchChange(interval, status) {
      if (status === "interval") {
        this.chooseStatus = false;
        this.selectValue = "60";
      } else if (status === "original") {
        this.chooseStatus = true;
      }
      this.requestDetailData(
        this.wpvalue,
        this.timeValue[0],
        this.timeValue[1],
        interval,
        this.wtId,
        this.descName
      );
    },

    async search() {
      let stationList = this.$store.state.stationList;
      this.wpvalue = stationList[0].id;
      this.wpoptions = stationList;
      this.searchData();
    },

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

        arr.push(e[1]);
      });
      this.columnObj = columnObj;
      this.column = arr;
      this.searchData();
    },

    async searchData() {
      // const { data } = Yujing;
     await api.alarmCountQuery({
          stationid: this.wpvalue,
          startdate: dayjs(this.timeValue[0]).format("YYYY-MM-DD"),
          enddate: dayjs(this.timeValue[1]).format("YYYY-MM-DD"),
      }).then(res =>{
        let data = res.data
        this.tableData = [];
      const resData = data;
      // const resData =this.resdata;
      const column = this.columnObj;
      let dataAll = []; // 总数据集合
      resData.data.forEach((e) => {
        let obj = {
          name:e[Object.keys(e)[0]][0].code,
        };
        let wpid = Object.keys(e)[0];
        this.wpid = wpid;

        e[wpid].forEach((k) => {
          column.forEach((c) => {
            if (k.alertText == c.name) {
              const countStyle = k.count / (k.count + k.time);
              const timeStyle = k.time / (k.count + k.time);
              let obj1 = {
                count: k.count,
                countStyle: countStyle ? countStyle * 100 + "px" : "0",
                time: k.time,
                timeStyle: timeStyle ? timeStyle * 100 + "px" : "0",
              };
              obj[k.alertText] = obj1;
            }
          });
        });
        dataAll.push(obj);
      });

      this.tableData.column = column;
      this.tableData.data = dataAll;

      ///////////////////// 获取规则list
      const map = {};
      var windNum = [];
      for (let i in resData.data) {
        for (let k in resData.data[i]) {
          map[k] = resData.data[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;
      })  
    },
    fx() {
      this.timeValue[0] = dayjs(this.timeValue[0]).format("yyyy-MM-dd");
      this.dialogTitleFX = "预警分析";
      this.dialogVisibleFX = true;
    },
  },
};
</script>
<style lang="less" scoped>
.body {
  background-color: #000000;
  height: 90vh;
  width: 102%;
  margin-left: -1%;
  margin-top: -40px;
}
.searchTitle {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 3vw;
  padding-top: 10px;
  color: #ffffff;
  height: 55px;
}
.search {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-right: 50px;
}

.table-panel {
  width: 97%;
  background: transparent;
  padding: 0;
  margin-left: 3vw;

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

    .bar-percent {
      height: 100%;
      background: #05bb4c;
      margin-right: 8px;
    }
  }
}
.searchForm {
  display: flex;
  margin-left: 36px;
  flex-direction: row-reverse;

  .inputs {
    width: 15%;
    margin-right: 18px;
  }
}
.model {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  color: rgba(240, 240, 240, 1);
  font-size: 12px;
}

.el-switch {
  width: 453px;
}

.el-switch__label {
  color: #999999 !important;
}

.el-switch__label.is-active {
  color: rgba(37, 116, 219, 1) !important;
}

.selects {
  margin-right: 16px;
}

.choose {
  width: 160px;
  height: 25px;
  display: flex;
  flex-direction: row;
  align-items: center;
  color: #ffffff;
}

.interval {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(77, 77, 77, 1);
  border-top-left-radius: 12.5px;
  border-bottom-left-radius: 12.5px;
}

.interval_on {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(29, 106, 235, 1);
  border: 1px solid rgba(29, 106, 235, 1);
  border-top-left-radius: 12.5px;
  border-bottom-left-radius: 12.5px;
}

.original {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(77, 77, 77, 1);
  border-top-right-radius: 12.5px;
  border-bottom-right-radius: 12.5px;
}

.original_on {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(29, 106, 235, 1);
  border: 1px solid rgba(29, 106, 235, 1);
  border-top-right-radius: 12.5px;
  border-bottom-right-radius: 12.5px;
}

.inputs {
  border: none;
  width: 110px !important;
}
.el-table__body-wrapper{
  background-color: #000000 !important;
}
</style>