<template>
  <div class="OverView scada-display-plugin">
    <div class="OverView-title">
      <div class="OverView-title-ul">
        <ul class="navigation">
          <li
            v-for="(item, key) in company"
            :key="key + 'A'"
            :class="defaultNavigation == item.LABEL ? 'selectedLi' : ''"
            @click="chnageNavigation(item.LABEL)"
          >{{ item.LABEL }}</li>
        </ul>
      </div>
      <div class="OverView-title-close">
        <i @click="close()" class="el-icon-close close-chart"></i>
      </div>
    </div>
    <div class="radio">
      <el-radio-group v-model="radio" @change="changeShow">
        <el-radio :label="val" v-for="(val, key) in dataType" :key="key + 'E'">{{ val }}</el-radio>
      </el-radio-group>
    </div>

    <div class="contain">
      <ul class="inlineBox">
        <li v-for="(val, key) in showArr" :key="key + 'B'">
          <div class="title" @click.stop>
            <i
              class="icon-more  iconfont-lcw"
              title="定位"
              @click="position(val)"
              style="float:left;"
            >&#xe601;</i>
            {{ val.ZBNAME }}
            <span></span>
            <i
              title="收藏"
              @click="collect(val, key)"
              :class="
                val.ISCOLLECT == '1'
                  ? 'icon-more icon-wujiaoxing1 collected iconfont-lcw'
                  : 'icon-more icon-kongxinwujiaoxing uncollected iconfont-lcw'
              "
            >&#xe607;</i>
          </div>
          <div class="measureBox">
            <div class="containBox" v-for="item in val.children" :key="item.ZBID">
              <div class="smallTitle" v-if="item.showTitle">
                <span></span>
                {{ item.ZBTYPE }}
              </div>

              <div class="measure">
                <div>{{ getZbName(item) }}: </div>
                <div style="color:rgb(255, 255, 255)">{{ item.VALUE }}</div>
              </div>
            </div>
          </div>
        </li>
        <!-- 解决最后一行居中 -->
        <li class="content_items" style="height:0; border:none;"></li>
        <li class="content_items" style="height:0; border:none;"></li>
        <li class="content_items" style="height:0; border:none;"></li>
        <li class="content_items" style="height:0; border:none;"></li>
        <li class="content_items" style="height:0; border:none;"></li>
      </ul>
    </div>
  </div>
</template>

<script>
import WebSocketUtils from "../assets/js/WebSocketUtils";
import store from "../store/index";
import Axios from "axios";
export default {
  name: "ScadaGlance",
  props: {
    httpProp: {
      default: ""
    },
    wsSocket:{
      default: "ws://192.168.7.188:25097/"
    }
  },
  data() {
    return {
      defaultNavigation: "全部", //默认打开的导航栏
      radio: "", // 单选框
      checkedFun: [], //显示多选框
      dataArr: [], //数据数组
      alarmArr: [], //报警数据
      showArr: [], //最终展示数组
      tagName: {}, //详细站点名
      company: [
        {
          LABEL: "全部"
        },
        {
          LABEL: "收藏"
        }
      ],
      index_radio: 0,
      dataType: [], //类型分组
      showArr_two: [],
      sendArr: [],
      stations: [],
      valueArr: [] //具体内容
    };
  },
  computed: {},
  components: {},
  methods: {
    getZbName(item) {
      return item.ZBNAME + (!item.ZBUNIT ? '' : `(${item.ZBUNIT}')`)
    },
    close() {
      this.$emit("closeOverView");
    },
    // 切换导航栏
    chnageNavigation(label) {
      this.defaultNavigation = label;
      this.changeShow();
    },
    // 首次获取数据
    getDate() {
      let baseurl = (this.httpProp?this.httpProp:store.state.appConfig.services.ApiUrl);
      Axios.get( baseurl  + "/api/scada/tree")
        .then(res => {
          this.dataArr = res.data;
          if (this.dataArr == "" || this.dataArr == "-2") {
            return;
          }
          //获取数据类型的种类
          this.dataType = []
          this.getDataType(this.dataArr);
          this.dataType.push('全部')
          // 获取所有的站点数据（包括子级）
          this.stations = []
          this.getStations(this.dataArr);
          // this.swapPlaces(this.dataType);
          //展示数据分类
          // this.dataType.forEach(val => {
          //   this.showArr_two.push([val]);
          //   this.checkedFun.push(val);
          // });
          //根据种类分类
          // this.categoricalArray(this.dataArr);
          // for (let key in this.checkedFun) {
          //   if (this.checkedFun[key] == null) {
          //     this.checkedFun[key] = "其他";
          //   }
          // }
          this.radio = this.dataType.length > 0  ? this.dataType[0] : '';
          this.changeShow();
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    // 递归，获取站点数据
    getStations(dataArr) {
      for(let item of dataArr) {
        if(item.ZBMARK === '站点'){
          // 获取指标类型的set，用于类型过滤
          if(!item.children) continue;
          item.TagTypes = new Set((item.children || []).map(citem => citem.ZBTYPE || '其他'))
          item.children.sort((a, b) => a.ZBTYPE > b.ZBTYPE ? -1 : 1)
          this.stations.push(item)
        } else if(Array.isArray(item.children) && item.children.length > 0) {
          this.getStations(item.children)
        }
      }
    },

    // 切换数据
    changeShow() {
      this.showArr = []; //最终展示数组
      this.sendArr = [];

      for(let station of this.stations) {
        if(station.TagTypes.has(this.radio) || this.radio === '全部'){
          let sCopy = JSON.parse(JSON.stringify(station));
          sCopy.children = (sCopy.children || []).filter(citem => citem.ZBTYPE === this.radio || this.radio === '全部')
          if(sCopy.children.length > 0) {
            this.showArr.push(sCopy);
            let tagAr = []
            let tmpType = ''
            for(let titem of sCopy.children) {
              tagAr.push(titem.TAG)
              if(tmpType !== titem.ZBTYPE) {
                titem.showTitle = true
                tmpType = titem.ZBTYPE
              }
            }
            this.sendArr = this.sendArr.concat(tagAr)
          }
        }
      } 

      // for (let i = 0; i < this.checkedFun.length; i++) {
      //   if (this.radio == this.checkedFun[i]) {
      //     this.index_radio = i;
      //     let data = this.showArr_two[i];
      //     console.log(data);
      //     for (let key in data) {
      //       if (key != 0) {
      //         //去重
      //         let falg = true;
      //         this.showArr.forEach(val => {
      //           if (val.ZBNAME === data[key].ZBNAME) {
      //             falg = false;
      //           }
      //         });
      //         if (falg) {
      //           this.showArr.push(data[key]);
      //           // sendArr
      //           this.sendArr.push(data[key].TAG);
      //         }
      //       }
      //     }
      //   }
      // }

      //调用获取value值
      if (this.sendArr.length) {
        // console.log(this.sendArr);
        this.initSocket(this.sendArr.join("|"));
      }
    },

    //递归数据类型
    getDataType(data) {
      data.forEach(val => {
        let _type = val.ZBTYPE || '其他';
        let flag = this.dataType.includes(_type);
        if (!flag && val.ZBMARK === '指标') {
          this.dataType.push(_type);
        }
        if (val.children) {
          this.getDataType(val.children);
        }
      });
    },

    swapPlaces(dataType) {
      for (let key in dataType) {
        if (dataType[key] == null) {
          let temp = dataType[key];
          dataType[key] = dataType[dataType.length - 1];
          dataType[dataType.length - 1] = temp;
        }
      }
    },
    //根据类型分类
    categoricalArray(data) {
      data.forEach(val => {
        for (let key in this.dataType) {
          if (this.dataType[key] == val.ZBTYPE && val.ZBMARK == "指标") {
            this.showArr_two[key].push(val);
          }
        }
        if (val.children) {
          this.categoricalArray(val.children);
        }
      });
    },

    //建立长连接
    initSocket(send) {
      console.log("初始化");
      this.loading = true;
      this.webSocket = new WebSocketUtils({
        myUrl: (this.wsSocket+"pushreal"),
        sendMessage: send,
        webSocketBack: this.messageBack
      });
    },

    messageBack(res) {
      // console.log(res);
      //处理接受回来的数据,存放至valueArr
      let data = [];
      data = JSON.parse(res.data);
      // 获取所有指标，放到一个数组中
      let tempAr = []
      for(let station of this.showArr) {
        tempAr = tempAr.concat(station.children || [])
      }
      // 获取指标id和指标的键值对
      let tempDict = {}
      for(let tagItem of tempAr) {
        tempDict[tagItem.ZBID] = tagItem
      }
      // 数据赋值
      for(let item of data) {
        if(tempDict[item.id]) {
          tempDict[item.id] = item.value;
        }
      }

      // for (let key = 0; key < data.length; key++) {
      //   if (this.valueArr.length && data[key] != undefined) {
      //     let falg = true;
      //     this.valueArr.forEach(val => {
      //       try {
      //         if (val.id == data[key].id) {
      //           val.value = data[key].value;
      //           falg = false;
      //         }
      //       } catch (error) {
      //         console.log(error);
      //       }
      //     });
      //     if (falg) {
      //       if (data[key] != null) {
      //         this.valueArr.push(data[key]);
      //       }
      //     }
      //   } else {
      //     this.valueArr.push(data[key]);
      //   }
      // }
      // this.interpolation();
    },

    closeWebsocket() {
      if (this.webSocket) {
        this.webSocket.close();
        this.webSocket = null;
      }
    },

    interpolation() {
      //插入value值
      for (let key in this.showArr) {
        for (let i in this.valueArr) {
          if (this.showArr[key].TAG == this.valueArr[i].id) {
            this.showArr[key].VALUE = this.valueArr[i].value;
            let tempObj = this.showArr[key];
            this.$set(this.showArr, key, tempObj);
          }
        }
      }
      // console.log("this.showArr-----1");
      // console.log(this.showArr);
    }
  },

  watch: {
    // 切换radio关闭弹框
    radio(oldData, newData) {
      if (oldData != newData) {
        this.infoWindowShow = false;
      }
    },

    visible(val) {
      this.dialog_visible = val;
    }
  },
  created() {
    this.getDate();
  },
  mounted() {},
  beforeDestroy() {
    this.closeWebsocket();
  }
};
</script>


<style scoped>
.OverView {
  background-color: #404040;
  height: 100%;
  width: 100%;
  font-family: "Microsoft YaHei", serif;
}

ul,
li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.OverView-title {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  background-color: #282828;
}

.OverView-title-ul {
  display: flex;
  justify-content: center;
  width: 80%;
}

.OverView-title-close {
  margin: 10px;
}

.OverView-title-close:hover {
  color: rgb(33, 163, 241);
  cursor: pointer;
}

.navigation {
  /* color: var(--main-color); */
  /* background: var(--main-one); */
  color: #404040;
  background-color: #282828;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.navigation li {
  width: 100px;
  margin: 6px 4px;
  padding: 2px 0;
  cursor: pointer;
  color: rgb(33, 163, 241);
  border: 1px solid rgb(33, 163, 241);
  border-radius: 3px;
  transition: all 0.5s;
}

.navigation .selectedLi {
  background: rgb(0, 181, 247);
  transition: all 0.2s;
  color: #fdeded;
  transition: all 0.5s;
}
.el-radio {
  color: white !important;
  padding: 10px;
}
.radio .el-radio__label {
  color: red !important;
}

.radio .el-radio-group {
  text-align: center;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

.contain {
  height: calc(100% - 61px);
  overflow: auto;
}

.inlineBox {
  height: 100%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  align-content: flex-start;
  overflow: auto;
}

.inlineBox::-webkit-scrollbar,
.contain::-webkit-scrollbar {
  display: none;
}

.inlineBox::after {
  content: "";
  visibility: hidden;
  clear: both;
  /* flex: auto;    最后一列靠左 */
}

.contain li {
  width: 300px;
  height: 150px;
  margin: 5px 10px 10px;
  float: left;
  overflow: hidden;
  border-radius: 3px;
  box-shadow: 0px 0px 12px #11111111;
  cursor: pointer;
  transition: all 0.2s;
}

.contain li:hover {
  box-shadow: 0px 0px 45px #888888;
}

.measureBox {
  height: calc(100% - 24px);
  overflow: auto;
  font-size: 14px;
}

.measureBox::-webkit-scrollbar {
  display: none;
}

.title {
  font-size: 14px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background: #404040;
  color: #fdeded;
  padding: 0 10px;
}

.title span {
  float: left;
  font-size: 12px;
  cursor: pointer;
}

.title i {
  font-size: 12px;
  line-height: 24px;
  cursor: pointer;
}

.collected {
  float: right;
  /* color: var(--start-collect); */
}

.uncollected {
  float: right;
  color: var(--main-titlecolor);
}

/* .containBox {
        border-bottom: 1px solid var(--main-three);
    } */

.containBox:last-child {
  border: 0;
}

.smallTitle {
  /* color: var(--main-theme); */
  color: rgb(33, 163, 241);
  padding: 4px 10px;
  border-bottom: 1px solid rgb(100, 100, 100);
}

.smallTitle > span {
  display: inline-block;
  width: 3px;
  height: 12px;
  margin-left: 4px;
  background: rgb(33, 163, 241);
  margin-right: 6px;
}

.measure {
  padding: 4px;
  width: calc(100% - 8px);
}

.measure > div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.measure > div:nth-child(2n + 1) {
  float: left;
  text-indent: 0.5em;
  color: rgb(180, 180, 180);
}

.measure > div:nth-child(2n) {
  float: right;
  text-align: right;
  font-weight: bold;
  /* color: var(--main-titlecolor); */
  position: relative;
}

.measure .unusualA {
  padding-right: 20px;
  color: red !important;
  animation: abnormalA 1s infinite;
}

.measure .unusualC {
  color: red !important;
  animation: abnormalA 1s infinite;
}

.measure .unusualB {
  color: rgb(90, 90, 90) !important;
}

.unusualB i {
  padding-left: 5px;
  font-size: 13px;
}

.unusualA i {
  font-size: 15px;
  position: absolute;
}

.measure::after {
  content: "";
  display: block;
  visibility: hidden;
  height: 0;
  clear: both;
}

.OverView .pagemask {
  width: 100vw;
  height: 100vh;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;
  background: rgba(0, 0, 0, 0.5);
}

.OverView .pageBox {
  width: 90%;
  height: calc(100vh - 100px);
  background: #fdeded;
  position: absolute;
  left: 0;
  right: 0;
  top: -18px;
  bottom: 0;
  margin: 40px auto;
  z-index: 3;
  border-radius: 4px;
  box-shadow: 4px 6px 15px 0px #11111111;
  background-color: #404040;
}

.OverView .pageTitle {
  width: 100%;
  height: 30px;
  /* background: var(--popup-titlebg); */
  background: red;
  color: #fdeded;
  line-height: 30px;
  padding-left: 10px;
  border-radius: 4px 4px 0 0;
}

.OverView .pageTitle i {
  float: right;
  line-height: 30px;
  color: #fdeded;
  font-size: 16px;
  margin-right: 10px;
  cursor: pointer;
}

.HjInfoWindowBox .title {
  background: var(--popup-titlebg);
  /* background :red; */
}

.HjInfoWindowBox .title span {
  color: #fdeded;
}
.close-over-view {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 16px;
  cursor: pointer;
  color: #fdeded;
}
</style>