/* 自定义tabs */
<template>
  <div>
    <div class="body" :style="style">
      <img class="logo" src="../../assets/img/logo.png" alt="" />
      <div class="Title">{{ title }}</div>
      <div class="content" @contextmenu="contextmenu">
        <!-- <el-scrollbar>
        <div class="scoll"> -->
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">状态异常</div>
                <span class="num">{{ statusRepair.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="statusRepair"
            ></MatrixBlock>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">故障</div>
                <span class="num">{{ faultList.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="faultList"
            ></MatrixBlock>
          </el-collapse-item>

          <el-collapse-item name="3">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">维护</div>
                <span class="num">{{ maintainList.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="maintainList"
            ></MatrixBlock>
          </el-collapse-item>

          <el-collapse-item name="4">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">离线</div>
                <span class="num">{{ offlineList.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="offlineList"
            ></MatrixBlock>
          </el-collapse-item>

          <el-collapse-item name="5">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">挂牌</div>
                <span class="num">{{ listedList.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="listedList"
            ></MatrixBlock>
          </el-collapse-item>

          <el-collapse-item name="6">
            <template v-slot:title>
              <div class="tit1">
                <div class="title">风速功率不匹配</div>
                <span class="num">{{ unpaidList.length }}</span>
              </div>
            </template>
            <MatrixBlock
              area="problem"
              @problem-click="handleClick"
              @on-click="handleDetails"
              :dataList="unpaidList"
            ></MatrixBlock>
          </el-collapse-item>
        </el-collapse>

        <!-- </div>
      </el-scrollbar> -->
      </div>
    </div>
    <WindturbineDetailPages
      v-model="dialogVisible"
      :showSvg="showSvg"
      @close="handleClose"
      :windturbine="currentWindturbine"
    ></WindturbineDetailPages>
  </div>
</template>

<script>
import BackgroundData from "utils/BackgroundData";
import MessageBridge from "utils/MessageBridge";
import WindturbineDetailPages from "../WindturbineDetailPages.vue";
import MatrixBlock from "../matrixBlock.vue";
import api from "api/index";
import { debounce } from "lodash";

import dataJson from "./dataJson.json";
export default {
  name: "gy-card",
  components: {
    WindturbineDetailPages,
    MatrixBlock,
  },
  emits: ["parentRun"],
  props: {
    title: {
      type: String,
      default: "",
      required: true,
    },
    height: {
      type: Number,
      default: 200,
    },
  },
  data() {
    return {
      activeNames: ["1", "2", "3", "4", "5", "6"],
      dialogVisible: false,
      currentWindturbine: {},
      values: [],
      lockValues: [],
      hover: false,
      big: false,
      current: 0,
      faultList: [],
      statusRepair: [],
      unpaidList: [],
      maintainList: [],
      offlineList: [],
      listedList: [],
      chooseList: [],
      currentWindturbine: {},
      windturbineList: {},
      showSvg: false,
      controlErorCodes: [
        "控制成功",
        "控制命令发送失败",
        "无效的控制地址",
        "被控设备异常",
        "无效的控制功能",
        "网络连接错误,检查场站通信",
        "控制结果读取超时",
        "未知错误",
        "控制命令错误",
        "收到无法识别数据",
        "未读取到数据包",
        "未知错误",
        "风机操作过频繁",
        "风机被挂牌",
        "风机操作与风机状态不符",
        "需要登录",
      ],
    };
  },
  computed: {
    style() {
      return `width: 100%; height: ${this.height}vh;`;
    },
    // windturbineChangeCount() {
    //   return this.$store.state.changeCount;
    // },
    // windturbinelistComp() {
    //   return this.$store.state.windturbinelist;
    // },
  },
  created() {
    this.deal();
    this.getLocks();
    // this.initData()

    // this.windturbineMessage();
    // this.intervals = setInterval(this.windturbineMessage, 3000);

    this.statusRepair = dataJson.statusRepair;
    this.faultList = dataJson.faultList;
    this.maintainList = dataJson.maintainList;
    this.offlineList = dataJson.offlineList;
    this.listedList = dataJson.listedList;
    this.unpaidList = dataJson.unpaidList;
  },
  methods: {
    // initData: function () {
    //   let mb = MessageBridge.getInstance();
    //   let windturbine = [
    //     { key: "/topic/windturbine", action: this.debounceWindturbineMessage },
    //   ];
    //   mb.register(windturbine);
    // },
    // debounceWindturbineMessage: debounce(function (msg) {
    //   this.windturbineMessage(msg);
    // }, 1000),
    windturbineMessage() {
      api.getWindturbine().then((res) => {
        this.windturbineList = res.data;
        let json = res.data;
        this.maintainList = [];
        this.offlineList = [];
        this.listedList = [];
        this.faultList = [];
        this.statusRepair = [];
        this.unpaidList = [];
        let faultRecord = [];
        let flashingList = this.$store.state.faultList || [];
        let arr = Object.keys(json).sort();
        for (let id of arr) {
          let val = json[id];
          this.chooseList.forEach((item) => {
            if (item.windturbineId === val.windturbineId) {
              val.active = true;
            }
          });
          if (val.status === 5) {
            let obj = flashingList.find(
              (fs) => fs.windturbineId === val.windturbineId
            );
            if (obj) {
              val.flashing = obj.flashing ? true : obj.flashing;
            } else {
              val.flashing = true;
            }
          }

          if (val.lockValue === 9) {
            val.lockValues = this.lockValues.filter(
              (item) => val.windturbineId === item.windturbineID
            )[0]?.value;
          }
          if (val.abnormalState === true) {
            this.statusRepair.push(val);
          }
          switch (val.status) {
            case 4:
              if (val.undeliveredStatus >= 4) {
                this.unpaidList.push(val);
              }
              break;
            case 5:
              faultRecord.push(val);
              this.faultList.push(val);
              break;
            case 6:
              this.maintainList.push(val);
              break;
            case 7:
              this.offlineList.push(val);
              break;
          }
          if (val.lockValue > 0) {
            this.listedList.push(val);
          }
        }
        this.$store.commit("faultList", faultRecord);
      });
    },
    deal() {
      let json = this.windturbineList;
      console.log(json);
      this.unpaidList = [];
      this.faultList = [];
      this.maintainList = [];
      this.statusRepair = [];
      this.offlineList = [];
      this.listedList = [];

      let arr = Object.keys(json).sort();

      for (let id of arr) {
        let val = json[id];
        this.chooseList.forEach((item) => {
          if (item.windturbineId === val.windturbineId) {
            val.active = true;
          }
        });
        if (val.abnormalState === true) {
          this.statusRepair.push(val);
        }
        switch (val.status) {
          case 4:
            if (val.undeliveredStatus >= 4) {
              this.unpaidList.push(val);
            }
            break;
          case 5:
            this.faultList.push(val);
            break;
          case 6:
            this.maintainList.push(val);
            break;
          case 7:
            this.offlineList.push(val);
            break;
        }
        if (val.lockValue > 0) {
          this.listedList.push(val);
        }
      }
    },
    getLocks() {
      api.getCustomerLock().then((res) => {
        if (res) {
          this.lockValues = res.data;
        }
      });
    },
    handleClick(values) {
      let flashingList = this.$store.state.faultList;
      if (values.flashing) {
        flashingList.filter(
          (item) => values.windturbineId === item.windturbineId
        )[0].flashing = false;
      }
      if (values.active) {
        let showIndex = null;
        this.chooseList.forEach((item, index) => {
          if (item.windturbineId === values.windturbineId) {
            showIndex = index;
          }
        });
        this.chooseList.splice(showIndex, 1);
      } else {
        this.chooseList.push(values);
      }
      let flag = false;
      this.faultList.forEach((item) => {
        if (item.windturbineId === values.windturbineId) {
          (item.active = !item.active), (flag = true);
        }
      });
      this.statusRepair.forEach((item) => {
        if (item.windturbineId === values.windturbineId) {
          (item.active = !item.active), (flag = true);
        }
      });
      flag
        ? ""
        : this.maintainList.forEach((item) => {
            if (item.windturbineId === values.windturbineId) {
              (item.active = !item.active), (flag = true);
            }
          });
      flag
        ? ""
        : this.offlineList.forEach((item) => {
            if (item.windturbineId === values.windturbineId) {
              (item.active = !item.active), (flag = true);
            }
          });
      flag
        ? ""
        : this.listedList.forEach((item) => {
            if (item.windturbineId === values.windturbineId) {
              item.active = !item.active;
            }
          });
      flag
        ? ""
        : this.unpaidList.forEach((item) => {
            if (item.windturbineId === values.windturbineId) {
              item.active = !item.active;
            }
          });
    },
    /* 右键菜单 */
    contextmenu() {
      const { remote } = require("electron");
      let that = this;
      const menuTemplate = [
        {
          label: "挂牌",
          submenu: [
            {
              label: "检修",
              click() {
                that.menuClicked({ value: "CheckLock" });
              },
            },
            {
              label: "故障维修",
              click() {
                that.menuClicked({ value: "FaultLock" });
              },
            },
            {
              label: "场内受累检修",
              click() {
                that.menuClicked({ value: "StationCheckLock" });
              },
            },
            {
              label: "场内受累故障",
              click() {
                that.menuClicked({ value: "StationFaulLock" });
              },
            },
            {
              label: "场外受累电网",
              click() {
                that.menuClicked({ value: "StationPowerLineLock" });
              },
            },
            {
              label: "场外受累天气",
              click() {
                that.menuClicked({ value: "StationWeatherLock" });
              },
            },
          ],
        },
        {
          label: "取消挂牌",
          click() {
            that.menuClicked({ value: "UnLock" });
          },
        },
      ];
      const menu = remote.Menu.buildFromTemplate(menuTemplate);

      menu.popup(remote.getCurrentWindow());
    },
    menuClicked(msg) {
      let bd = BackgroundData.getInstance();
      if (!bd.LoginUser) {
        this.$notify({
          title: "请登录",
          message: "控制风机需要先登录！",
          type: "warning",
          position: "bottom-right",
          offset: 60,
          duration: 3000,
        });
        return;
      }
      let sendList = [];
      this.chooseList.forEach((item) => {
        item.lockType = msg.value;
      });
      sendList = this.chooseList;
      if (sendList.length > 0) {
        this.chooseList = [];
        let pairs = {};
        sendList.forEach((item) => {
          let ct = {
            windturbineId: item.windturbineId,
            stationId: item.stationId,
            projectId: item.projectId,
            modelId: item.modelId,
            controlType: item.controlType,
            lockType: item.lockType,
            userName: `system_${bd.LoginUser.name}`,
            userId: 0,
          };
          pairs[ct.windturbineId] = ct;
        });
        api.windturbControlLock(pairs).then((res) => {
          if (res) {
            this.controlSuccess(res);
          }
        });
      }
    },
    /* 控制成功 */
    controlSuccess(msg) {
      let bd = BackgroundData.getInstance();
      for (let id in msg.data) {
        let val = msg.data[id];
        if (val.errorCode !== "0") {
          bd.removeCheckouts(val);
        }
      }
      let mss = ""; // 信息
      let iserror = false; // 是否有控制错误的风机
      for (let v in msg.data) {
        let val = msg.data[v];
        if (val.errorCode > 0) {
          iserror = true;
          mss += `${val.windturbineId}  ${
            this.controlErorCodes[val.errorCode]
          }\n`;
        }
      }
      let tp = iserror ? "success" : "warning";
      let dt = iserror ? 0 : 4500;
      // if (!iserror) {
      //   mss = "控制成功";
      // }

      this.$notify({
        title: "控制",
        message: mss,
        type: tp,
        position: "bottom-right",
        offset: 60,
        duration: 3000,
      });
    },

    /* 控制失败 */
    controlError(err) {
      this.$notify({
        title: "控制出现错误",
        message: err.message,
        type: "warning",
        position: "bottom-right",
        offset: 60,
        duration: 3000,
      });
    },
    changeTitle(id) {
      this.current = id;
      this.$refs.malfunction.dateClick(id);
    },
    handleDetails(itm) {
      this.dialogVisible = true;
      this.currentWindturbine = itm;
    },
    handleClose() {
      this.dialogVisible = false;
      this.showSvg = false;
      this.getLocks();
    },
  },
  unmounted() {
    clearInterval(this.intervals);
    this.intervals = null;
  },
  watch: {
    // windturbineChangeCount(val) {
    //   if (val > 0) {
    //     this.maintainList = [];
    //     this.offlineList = [];
    //     this.listedList = [];
    //     this.faultList = [];
    //     this.unpaidList = [];
    //     let faultRecord = [];
    //     let flashingList = this.$store.state.faultList || [];
    //     let arr = Object.keys(this.windturbinelistComp).sort();
    //     for (let id of arr) {
    //       let val = this.windturbinelistComp[id];
    //       this.chooseList.forEach((item) => {
    //         if (item.windturbineId === val.windturbineId) {
    //           val.active = true;
    //         }
    //       });
    //       if (val.status === 5) {
    //         let obj = flashingList.find(
    //           (fs) => fs.windturbineId === val.windturbineId
    //         );
    //         if (obj) {
    //           val.flashing = obj.flashing ? true : obj.flashing;
    //         } else {
    //           val.flashing = true;
    //         }
    //       }
    //       if (val.lockValue === 9) {
    //         val.lockValues = this.lockValues.filter(
    //           (item) => val.windturbineId === item.windturbineID
    //         )[0]?.value;
    //       }
    //       switch (val.status) {
    //         case 4:
    //           if (val.undeliveredStatus >= 3) {
    //             this.unpaidList.push(val);
    //           }
    //           break;
    //         case 5:
    //           faultRecord.push(val);
    //           this.faultList.push(val);
    //           break;
    //         case 6:
    //           this.maintainList.push(val);
    //           break;
    //         case 7:
    //           this.offlineList.push(val);
    //           break;
    //       }
    //       if (val.lockValue > 0) {
    //         this.listedList.push(val);
    //       }
    //     }
    //     this.$store.commit("faultList", faultRecord);
    //   }
    // },
  },
};
</script>

<style scoped="scoped">
.tit1 {
  width: 92%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.body {
  border: 1px solid #373737;
  width: 100%;
  margin-left: 15px;
  margin-top: 20px;
}

.body .scoll {
  height: 91%;
}

.Title {
  color: #ffffff;
  font-size: 14px;
  margin-left: 32px;
  font-weight: bold;
  /* margin-top: 12px; */
  margin-bottom: 10px;
  /* width: 570px; */
  width: 29vw;
  height: 50px;
  display: flex;
  align-items: center;
  position: absolute;
  background-color: #000000;
}

.Title::before {
  z-index: 1;
  content: "";
  position: absolute;
  left: -18px !important;
  /* top: 30px !important; */
  width: 5px;
  height: 5px;
  background-color: #54b75a;
  border-radius: 50%;
}
.content {
  overflow-y: auto;
  margin-top: 50px;
  height: 94%;
}
.content::-webkit-scrollbar {
  /*隐藏滚轮*/
  display: none;
}

.logo {
  position: absolute;
  top: 12px;
  left: 12px;
}

.matrix {
  margin-left: 20px;
  margin-right: 10px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(31, 31, 31, 1);
}

.problemTitle {
  /* box-sizing: border-box; */
  /* padding-left: 20px; */
}
</style>

<style lang="less">
.tit1 {
  .title {
    font-size: 14px;
    font-weight: bold;
    color: #bfbfbf;
  }
  .num {
    color: #fff;
    display: inline-block;
    width: 30px;
    height: 30px;
    background-color: rgba(37, 116, 219, 1);
    border-radius: 50%;
    line-height: 30px;
    text-align: center;
    box-sizing: border-box;
  }
}
</style>
