<template>
  <div class="problem" @contextmenu="contextmenu">
    <div class="body">
      <img class="logo" src="../../assets/img/logo.png" alt="" />
      <div class="titleBar">
        <div class="title" @click="parametersContrast()">设备区</div>
        <el-select
          @change="listedChange()"
          class="inputs"
          v-model="selectValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div
        class="content"
        style="
          margin-top: 20px;
          margin-left: 35px;
          height: 85%;
          overflow-y: auto;
        "
      >
        <!-- <el-scrollbar>
          <div class="scoll"> -->
        <div class="matrix" v-if="showList.length > 0">
          <!-- 简单矩阵 -->
          <box-select
            node=".box"
            @selectList="selectList"
            v-if="selectValue === '0'"
            v-for="(item, index) in allList" :key="index"
          >
            <div class="box1">
              {{ key }}
            </div>
            <EaxyMatrxBlock
              @choose-click="handleClick"
              @on-click="handleDetails"
              :dataList="item"
            >
            </EaxyMatrxBlock>
          </box-select>
          <!-- 全部矩阵 -->
          <box-select
            node=".box"
            @selectList="selectList"
            v-else-if="selectValue === '1'"
            v-for="(item, key) of allList"
          >
            <div class="box1">
              {{ key }}
            </div>
            <MatrixBlock
              @choose-click="handleClick"
              @on-click="handleDetails"
              :dataList="item"
            >
            </MatrixBlock>
          </box-select>
          <!-- 其他 -->
          <box-select node=".box" @selectList="selectList" v-else>
            <MatrixBlock
              @choose-click="handleClick"
              @on-click="handleDetails"
              :dataList="showList"
            >
            </MatrixBlock>
          </box-select>
        </div>
        <!-- </div>
        </el-scrollbar> -->
      </div>
    </div>

    <WindturbineDetailPages
      v-model="dialogVisible"
      :showSvg="showSvg"
      @close="handleClose"
      :windturbine="currentWindturbine"
    ></WindturbineDetailPages>
    <ParametersContrast
      :chooseList="chooseList"
      v-model="parametersDisplay"
    ></ParametersContrast>
  </div>
</template>

<script>
import WindturbineDetailPages from "../WindturbineDetailPages.vue";
import MatrixBlock from "../matrixBlock.vue";
import EaxyMatrxBlock from "../eaxyMatrixBlock.vue";
import BackgroundData from "utils/BackgroundData";
import api from "api/index";
import boxSelect from "components/boxSelect.vue";
import ParametersContrast from "./parametersContrast.vue";
export default {
  name: "ProblemArea",
  components: {
    WindturbineDetailPages,
    MatrixBlock,
    boxSelect,
    ParametersContrast,
    EaxyMatrxBlock,
  },
  props: {
    current: {
      type: Number,
    },
    datas: {
      type: String,
    },
  },
  data() {
    return {
      allNames: [],
      allList: {},
      dataList: [],
      showList: [],
      chooseList: [],
      lockValues: [],
      currentWindturbine: {},
      dialogVisible: false,
      showSvg: false,
      parametersDisplay: false,
      windturbinelist: {},
      options: [
        {
          value: "0",
          label: "简单矩阵",
        },
        {
          value: "1",
          label: "全部设备",
        },
        {
          value: "2",
          label: "故障",
        },
        {
          value: "3",
          label: "维护",
        },
        {
          value: "4",
          label: "离线",
        },
        {
          value: "5",
          label: "挂牌",
        },
      ],
      selectValue: "0",
      controlErorCodes: [
        "控制成功",
        "控制命令发送失败",
        "无效的控制地址",
        "被控设备异常",
        "无效的控制功能",
        "网络连接错误,检查场站通信",
        "控制结果读取超时",
        "未知错误",
        "控制命令错误",
        "收到无法识别数据",
        "未读取到数据包",
        "未知错误",
        "风机操作过频繁",
        "风机被挂牌",
        "风机操作与风机状态不符",
        "需要登录",
      ],
    };
  },
  computed: {},
  created: function () {
    this.controls();
    this.getLocks();
  },
  methods: {
    selectList(val) {
      val.forEach((item) => {
        this.handleClick(this.windturbinelist[item.id]);
      });
    },
    controls() {
      this.options = [
        {
          value: "0",
          label: "简单矩阵",
        },
        {
          value: "1",
          label: "全部设备",
        },
        {
          value: "2",
          label: "故障",
        },
        {
          value: "3",
          label: "维护",
        },
        {
          value: "4",
          label: "离线",
        },
        {
          value: "5",
          label: "挂牌",
        },
      ];
      let stationList = this.$store.state.stationList;
      stationList.forEach((item, index) => {
        let obj = {};
        obj.value = String(index + 6);
        obj.label = item.address;
        obj.stationId = item.code;
        this.options.push(obj);
      });
      let json = this.$store.state.windturbinelist;
      this.dataList = [];
      this.showList = [];
      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;
          }
        });
        this.dataList.push(val);
        switch (Number(this.selectValue)) {
          case 0:
            this.showList.push(val);
            break;
          case 1:
            this.showList.push(val);

            break;
          case 2:
            val.status === 5 ? this.showList.push(val) : "";
            break;
          case 3:
            val.status === 6 ? this.showList.push(val) : "";
            break;
          case 4:
            val.status === 7 ? this.showList.push(val) : "";
            break;
          case 5:
            val.lockValue > 0 ? this.showList.push(val) : "";
            break;
          default:
            if (
              val.stationId ===
              this.options.filter((ops) => ops?.value === this.selectValue)[0]
                .stationId
            ) {
              this.showList.push(val);
            }
            break;
        }
      }
      let checkoutList = BackgroundData.getInstance().checkouts;
      checkoutList.forEach((item) => {
        let showIndex = null;
        this.showList.forEach((param, index) => {
          if (item.windturbineId === param.windturbineId) {
            showIndex = index;
          }
        });
        this.showList.splice(showIndex, 1);
      });
    },
    getLocks() {
      api.getCustomerLock().then((res) => {
        if (res) {
          this.lockValues = res.data;
        }
      });
    },
    /* 右键菜单 */
    contextmenu() {
      const remote = require("electron").remote;
      let that = this;
      let menuTemplate = [];
      if (
        this.selectValue === "0" ||
        this.selectValue === "1" ||
        this.selectValue === "2" ||
        this.selectValue === "3" ||
        this.selectValue === "4"
      ) {
        menuTemplate = [
          // {
          //     label: "标注",
          //     click() {
          //         that.sendLock({ type: "marking" });
          //     },
          // },
          {
            label: "挂牌",
            submenu: [
              {
                label: "检修",
                click() {
                  that.sendLock({ value: "CheckLock" });
                },
              },
              {
                label: "故障维修",
                click() {
                  that.sendLock({ value: "FaultLock" });
                },
              },
              {
                label: "场内受累检修",
                click() {
                  that.sendLock({ value: "StationCheckLock" });
                },
              },
              {
                label: "场内受累故障",
                click() {
                  that.sendLock({ value: "StationFaulLock" });
                },
              },
              {
                label: "场外受累电网",
                click() {
                  that.sendLock({ value: "StationPowerLineLock" });
                },
              },
              {
                label: "场外受累天气",
                click() {
                  that.sendLock({ value: "StationWeatherLock" });
                },
              },
            ],
          },
          {
            label: "取消挂牌",
            click() {
              that.sendLock({ value: "UnLock" });
            },
          },
          {
            label: "参数对比",
            click() {
              that.parametersContrast();
            },
          },
        ];
      } else {
        menuTemplate = [
          // {
          //   label: "启动",
          //   click() {
          //     that.sendCommand({ controlType: "1", deviceType: "Manual" });
          //   },
          // },
          // {
          //   label: "停机",
          //   click() {
          //     that.sendCommand({ controlType: "2", deviceType: "Manual" });
          //   },
          // },
          // {
          //   label: "复位",
          //   click() {
          //     that.sendCommand({ controlType: "5", deviceType: "Manual" });
          //   },
          // },
          // {
          //   label: "维护",
          //   click() {
          //     that.sendCommand({ controlType: "6", deviceType: "Manual" });
          //   },
          // },
          // {
          //   label: "取消维护",
          //   click() {
          //     that.sendCommand({ controlType: "8", deviceType: "Manual" });
          //   },
          // },
          {
            label: "挂牌",
            submenu: [
              {
                label: "检修",
                click() {
                  that.sendLock({ value: "CheckLock" });
                },
              },
              {
                label: "故障维修",
                click() {
                  that.sendLock({ value: "FaultLock" });
                },
              },
              {
                label: "场内受累检修",
                click() {
                  that.sendLock({ value: "StationCheckLock" });
                },
              },
              {
                label: "场内受累故障",
                click() {
                  that.sendLock({ value: "StationFaulLock" });
                },
              },
              {
                label: "场外受累电网",
                click() {
                  that.sendLock({ value: "StationPowerLineLock" });
                },
              },
              {
                label: "场外受累天气",
                click() {
                  that.sendLock({ value: "StationWeatherLock" });
                },
              },
            ],
          },
          {
            label: "取消挂牌",
            click() {
              that.sendLock({ value: "UnLock" });
            },
          },
          {
            label: "参数对比",
            click() {
              that.parametersContrast();
            },
          },
          // {
          //     label: "标注",
          //     click() {
          //         that.sendLock({ type: "marking" });
          //     },
          // },
        ];
      }

      const menu = remote.Menu.buildFromTemplate(menuTemplate);

      menu.popup(remote.getCurrentWindow());
    },

    sendCommand(msg, windturbine) {
      let bd = BackgroundData.getInstance();
      if (!bd.LoginUser) {
        this.$notify({
          title: "请登录",
          message: "控制风机需要先登录！",
          type: "warning",
          position: "bottom-right",
          offset: 60,
          duration: 3000,
        });
        return;
      }
      let sendList = [];
      if (windturbine) {
        sendList = windturbine;
      } else {
        this.chooseList.forEach((item) => {
          item.controlType = Number(msg.controlType);
        });
        sendList = this.chooseList;
      }

      if (sendList.length > 0) {
        bd.checkout(sendList);
        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,
            auto: false,
            deviceType: msg.deviceType,
          };
          pairs[ct.windturbineId] = ct;
        });
        api.windturbControl(pairs).then((res) => {
          if (res) {
            this.controlSuccess(res);
          }
        });
      }
    },
    sendLock(msg, windturbine) {
      let bd = BackgroundData.getInstance();
      if (!bd.LoginUser) {
        this.$notify({
          title: "请登录",
          message: "控制风机需要先登录！",
          type: "warning",
          position: "bottom-right",
          offset: 60,
          duration: 3000,
        });
        return;
      }
      let sendList = [];
      if (windturbine) {
        windturbine.lockType = msg.value;
        sendList.push(windturbine);
      } else {
        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 ? "warning" : "success";
      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,
      });
    },
    handleClick(values) {
      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);
      }
      this.showList.forEach((item) => {
        if (item.windturbineId === values.windturbineId) {
          item.active = !item.active;
        }
      });
    },
    listedChange() {
      this.chooseList = [];
      this.showList = [];
      if (Number(this.selectValue) >= 6) {
        console.log(
          this.options.filter((ops) => ops?.value === this.selectValue)[0]
            .stationId
        );
        this.$store.commit(
          "currentStation",
          this.options.filter((ops) => ops?.value === this.selectValue)[0]
            .stationId
        );
      } else {
        this.$store.commit("currentStation", "");
      }
      console.log(this.$store.state.currentStation);
      this.dataList.forEach((val) => {
        val.active = false;
        switch (Number(this.selectValue)) {
          case 0:
            this.showList.push(val);
            break;
          case 1:
            // if (
            //   val.status === 5 ||
            //   val.status === 6 ||
            //   val.status === 7 ||
            //   val.lockValue > 0
            // ) {
            this.showList.push(val);
            // }
            break;
          case 2:
            val.status === 5 ? this.showList.push(val) : "";
            break;
          case 3:
            val.status === 6 ? this.showList.push(val) : "";
            break;
          case 4:
            val.status === 7 ? this.showList.push(val) : "";
            break;
          case 5:
            val.lockValue > 0 ? this.showList.push(val) : "";
            break;
          default:
            if (
              val.stationId ===
              this.options.filter((ops) => ops?.value === this.selectValue)[0]
                .stationId
            ) {
              this.showList.push(val);
            }
            break;
        }
      });
    },
    handleDetails(itm) {
      this.dialogVisible = true;
      this.currentWindturbine = itm;
    },
    handleClose() {
      this.dialogVisible = false;
      this.showSvg = false;
      this.getLocks();
    },
    parametersContrast() {
      if (this.chooseList.length > 0) {
        this.parametersDisplay = true;
      }
    },
  },
  watch: {
    "$store.getters.windturbinelist": {
      deep: true,
      handler: function (json) {
        this.windturbinelist = json;
        this.dataList = [];
        this.showList = [];
        let arr = Object.keys(json).sort();
        let newArr = [];
        for (let id of arr) {
          let val = json[id];
          newArr.push(val);
          this.chooseList.forEach((item) => {
            if (item.windturbineId === val.windturbineId) {
              val.active = true;
            }
          });
          if (val.lockValue === 9) {
            val.lockValues = this.lockValues.filter(
              (item) => val.windturbineId === item.windturbineID
            )[0]?.value;
          }
          this.dataList.push(val);
          switch (this.selectValue) {
            case "0":
              this.showList.push(val);
              break;

            case "1":
              this.showList.push(val);
              break;
            case "2":
              if (val.status === 5) {
                this.showList.push(val);
              }
              break;
            case "3":
              if (val.status === 6) {
                this.showList.push(val);
              }
              break;
            case "4":
              if (val.status === 7) {
                this.showList.push(val);
              }
              break;
            case "5":
              if (val.lockValue > 0) {
                this.showList.push(val);
              }
              break;

            default:
              if (
                val.stationId ===
                this.options.filter((ops) => ops?.value === this.selectValue)[0]
                  .stationId
              ) {
                this.showList.push(val);
              }
              break;
          }
        }
        // -----------------------------------------
        // if(this.selectValue === 0){
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        this.allList = {};
        newArr.forEach((item) => {
          let Fid = item.projectId;
          if (Fid.indexOf("CL") != -1) {
            arr1.push(item);
          } else if (Fid.indexOf("KB") != -1) {
            arr2.push(item);
          } else if (Fid.indexOf("DX") != -1) {
            arr3.push(item);
          } else if (Fid.indexOf("SY") != -1) {
            arr4.push(item);
          }
        });

        // 获取场站
        // this.allNames = [];
        let stationList = this.$store.state.stationList;
        stationList.forEach((item, index) => {
          if (item.stationName.indexOf("崇礼") != -1) {
            this.allList[item.stationName] = arr1;
          } else if (item.stationName.indexOf("康保") != -1) {
            this.allList[item.stationName] = arr2;
          } else if (item.stationName.indexOf("代县") != -1) {
            this.allList[item.stationName] = arr3;
          } else if (item.stationName.indexOf("寿阳") != -1) {
            this.allList[item.stationName] = arr4;
          }
        });
        // console.log(this.allNames);
        console.log(this.allList);

        let checkoutList = BackgroundData.getInstance().checkouts;
        checkoutList.forEach((item) => {
          let showIndex = null;
          this.showList.forEach((param, index) => {
            if (item.windturbineId === param.windturbineId) {
              showIndex = index;
            }
          });
          this.showList.splice(showIndex, 1);
        });
      },
    },
  },
};
</script>
<style scoped>
.problem {
  height: 100%;
}

.body {
  border: 1px solid #373737;
  width: 100%;
  margin-left: 15px;
  margin-top: 10px;
  height: 61vh;
}

.body .scoll {
  height: 91%;
}

.titleBar {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.title {
  color: #ffffff;
  font-size: 14px;
  margin-left: 32px;
  /* 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%;
}

.inputs {
  border: none;
  width: 174px !important;
  margin-left: 110px;
}

.el-input__inner {
  background-color: rgb(100, 100, 100) !important;
  color: rgb(220, 220, 220) !important;
  border: 1px solid red !important;
}

.logo {
  position: absolute;
  top: 2px;
  left: 12px;
}
.content::-webkit-scrollbar {
  /*隐藏滚轮*/
  display: none;
}
.box1 {
  width: 99%;
  height: 40px;
  background-color: rgb(30, 30, 30);
  margin-top: 2px;
  text-align: left;
  line-height: 40px;
  color: #fff;
  box-sizing: border-box;
    padding-left: 20px;
}
</style>