<template>
  <div
    class="big-v3-wrap"
    id="big-v3-wrap-id"
    ref="big-v3-wrap-id"
    :style="{
      transformOrigin: 'center top',
      transform: `scale(${scalseNumX}, ${scalseNumY})`,
      opacity: 1,
      transition: `all 0.5s ease 0s`,
    }"
  >
    <div class="main-block">
      <e-head
        ref="mainHead"
        :handelTile="title"
        :projectList="projectList"
        @eventFullscreen="eventFullscreen"
        @eventProjectId="eventProjectId"
        @eventRegionalismId="eventRegionalismId"
      />
      <div class="count-wrap">
        <div class="count-left">
          <div class="left-block-1">
            <e-project-census-temp
              :props="{
                label: 'spaceName',
                key: 'spaceId',
                value: 'coal',
              }"
              title="年度能耗"
              icon="/images/icon01.png"
              unit="（吨标准煤）"
              :tableList="projectSpaceCensusList"
              :countNum="(projectStatInfo['coal'] / 1000).toFixed(2) || 0"
            ></e-project-census-temp>

            <e-project-census-temp
              :props="{
                label: 'spaceName',
                key: 'spaceId',
                value: 'ELECTRICITY_METER',
              }"
              title="年度用电"
              icon="/images/icon02.png"
              unit="（万kwh）"
              :tableList="projectSpaceCensusList"
              :countNum="
                (projectStatInfo['ELECTRICITY_METER'] / 10000).toFixed(2) || 0
              "
            ></e-project-census-temp>

            <e-trend-census :result="actualEnergyCensus" />
          </div>
          <div
            class="map-block-1"
            :style="userLoginType !== 'PERSONAL' ? '' : ''"
          >
            <map-wrap
              v-if="userLoginType !== 'PERSONAL'"
              tempUserType="userLoginType"
              :fullscreen="fullscreen"
              :countResult="alarmInfoResult"
              :result="alarmInfoResult"
              @eventFullscreen="eventFullscreenMap"
              :projectList="projectList"
            ></map-wrap>

            <map-wrap-personal
              v-else
              :fullscreen="fullscreen"
              tempUserType="userLoginType"
              :countResult="alarmInfoResult"
              @eventFullscreen="eventFullscreenMap"
              :projectList="projectList"
            ></map-wrap-personal>

            <div
              style="width: 100%; display: flex; justify-content: space-between"
            >
              <wraring-info-wrap :result="alarmInfoResult"></wraring-info-wrap>

              <device-proportion-wrap
                :projectId="projectId"
              ></device-proportion-wrap>
            </div>
          </div>
        </div>
        <div class="right-block-1">
          <e-project-census-temp
            :props="{
              label: 'spaceName',
              key: 'spaceId',
              value: 'WATER_METER',
            }"
            title="年度用水"
            icon="/images/icon03.png"
            unit="（万吨）"
            :tableList="projectSpaceCensusList"
            :countNum="(projectStatInfo['WATER_METER'] / 10000).toFixed(2) || 0"
          ></e-project-census-temp>

          <e-project-census-temp
            :props="{
              label: 'spaceName',
              key: 'spaceId',
              value: 'GAS_METER',
            }"
            title="年度用气"
            icon="/images/icon04.png"
            unit="（万m³）"
            :tableList="projectSpaceCensusList"
            :countNum="(projectStatInfo['GAS_METER'] / 10000).toFixed(2) || 0"
          ></e-project-census-temp>

          <type-distribution-wrap
            style="margin-top: -5px"
            :result="resultInfo.alarmCategoriesList || []"
          ></type-distribution-wrap>
        </div>
      </div>
    </div>
    <div style="width: 0; height: 0;">
      <notification-alarm></notification-alarm>
    </div>
  </div>
</template>

<script>
import EHead from "./profile/EHead";
import DeviceProportionWrap from "./profile/deviceProportion";
import WraringInfoWrap from "./profile/wraringInfo";
import AlarmTableListWrap from "./profile/alarmTableList";
import TypeDistributionWrap from "./profile/typeDistribution";
import ETrendCensus from "./profile/ETrendCensus";
import MapWrap from "./profile/mapWrap";
import MapWrapPersonal from "./profile/personalCenter";
import { bigWebSocketUrl } from "@/config/env";
import Cookies from "js-cookie";
import EProjectCensusTemp from "./profile/EProjectCensusTemp";
import NotificationAlarm from './profile/NotificationAlarm';

import { getWarningAnalysis, homeCount, appProjectList } from "@/api/app";
import {
  getEnergySpaceCensusList,
  getEnergyCensusList,
} from "@/api/bigScreen/index";
export default {
  name: "Device_oneself",
  components: {
    EHead,
    DeviceProportionWrap,
    WraringInfoWrap,
    AlarmTableListWrap,
    // ETodayRatio,
    TypeDistributionWrap,
    ETrendCensus,
    MapWrap,
    MapWrapPersonal,
    EProjectCensusTemp,
    NotificationAlarm,
  },
  data() {
    return {
      title: "智慧能源综合管理系统",
      scalseNumX: 1,
      scalseNumY: 1,
      resultInfo: {},
      alarmInfoResult: {},
      projectList: [],
      projectId: null,
      regionalismId: null,
      fullscreen: false,
      thisScrollTopY: 0,
      userLoginType: "",
      stompClient: null,
      socket_flag: true,
      setIntervalGetCountOpt: null,
      projectStatInfo: {},
      projectSpaceCensusList: [],
      actualEnergyCensus: [],
      setTimeOut_flag: null,
    };
  },
  mounted() {
    // 计算缩放比例
    this.resize_window();
    this.userLoginType = this.$store.getters.userType;
    this.thisScrollTopY = document.getElementById("con_lf_top_div").scrollTop;
    document.getElementById("con_lf_top_div").style.background = "#010e45";
    document.getElementById("con_lf_top_div").style.height =
      "calc(100vh - 0px)";
    document.getElementById("con_lf_top_div").style.minHeight =
      "calc(100vh - 0px)";
    document.getElementById("con_lf_top_div").style.overflow = "hidden";
    document.getElementById("con_lf_top_div").scrollTop = 0;
    window.addEventListener("resize", () => {
      this.resize_window();
    });
  },
  watch: {
    // $route(to, from) {
    //   if (from.fullPath === "/index") {
    //     document.getElementById("con_lf_top_div").style.background = "#fff";
    //     document.getElementById("con_lf_top_div").style.height =
    //       "calc(100vh - 84px)";
    //     document.getElementById("con_lf_top_div").style.minHeight =
    //       "calc(100vh - 84px)";
    //   } else if (to.fullPath === "/index") {
    //     document.getElementById("con_lf_top_div").style.background = "#010e45";
    //     document.getElementById("con_lf_top_div").style.height =
    //       "calc(100vh - 84px)";
    //     document.getElementById("con_lf_top_div").style.minHeight =
    //       "calc(100vh - 84px)";
    //   }
    // },
  },
  created() {
    document.getElementById("app").style.background = "#010e45";
    this.getProjectList();
    this.warningAnalysisList();
    this.homeCount();
    this.getEnergyCensus();
    this.getEnergySpaceCensus();
    this.connection();
  },

  methods: {
    // 查询 能源数据状态情况
    getEnergyCensus() {
      getEnergyCensusList({
        projectId: this.projectId,
      }).then((res) => {
        this.projectStatInfo = res.data || {};
      });
    },
    // 查询 能源数据 空间统计
    getEnergySpaceCensus() {
      this.projectSpaceCensusList = [];
      getEnergySpaceCensusList({
        projectId: this.projectId,
      }).then((res) => {
        console.log(res);
        this.projectSpaceCensusList = res.data || [];
      });
    },
    getGuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    // 创建一个ws 监听获取报警实时数据
    connection() {
      if (this.stompClient) {
        return;
      }
      if (!bigWebSocketUrl) {
        return;
      }
      this.stompClient = new WebSocket(
        `${bigWebSocketUrl}/${this.getGuid()}/${this.projectId || -1}`
      );
      this.stompClient.onmessage = this.socket_onmsg;
      this.stompClient.onclose = this.socket_onclose;
    },
    socket_onmsg(evt) {
      console.log("wsljcg:=", evt);
      const data = JSON.parse(evt.data);
      this.actualEnergyCensus = data.params || {};
      this.$forceUpdate();
    },
    socket_onclose(e) {
      this.stompClient = null;
      if (this.socket_flag) {
        this.socket_flag = false;
        let _this = this;
        this.setTimeOut_flag = setTimeout(function () {
          _this.socket_flag = true;
          _this.connection();
        }, 10000);
      }
    },
    closeWebscoket() {
      if (this.stompClient) {
        this.stompClient.close();
      }
      this.socket_flag = false;
      this.stompClient = null;
      clearTimeout(this.setTimeOut_flag);
    },
    // 跳转路由是关闭全屏状态
    eventFullscreenMap(data) {
      this.fullscreen = data.value;
      this.$refs.mainHead["fullscreen"] = data.value;
    },
    // 全屏或者关闭 返回状态
    eventFullscreen(data) {
      this.fullscreen = data.value;
    },
    eventProjectId(data) {
      this.projectId = data;
      this.homeCount();
      this.warningAnalysisList();
      this.getEnergyCensus();
      this.getEnergySpaceCensus();
      this.closeWebscoket();
      this.connection();
    },
    eventRegionalismId(data) {
      this.regionalismId = data;
      this.getProjectList();
    },
    resize_window() {
      if (this.fullscreen) {
        this.scalseNumX = Number(document.documentElement.clientWidth / 1920);
        this.scalseNumY = Number(document.documentElement.clientHeight / 1080);
      } else {
        if (document.documentElement.clientWidth < 993) {
          this.scalseNumX =
            Number(document.documentElement.clientWidth / 1920) -
            (Cookies.get("sidebarStatus") !== "0" ? Number(200 / 1920) : 0);
        } else {
          this.scalseNumX =
            Number(document.documentElement.clientWidth / 1920) -
            (Cookies.get("sidebarStatus") !== "0"
              ? Number(200 / 1920)
              : Number(54 / 1920));
        }
        this.scalseNumY = Number(document.documentElement.clientHeight / 1080);
      }
    },
    // 查询项目列表
    getProjectList() {
      if (this.$store.getters.userType !== "PERSONAL") {
        appProjectList({
          regionalismId: this.regionalismId,
        }).then((response) => {
          this.projectList = response.data;
        });
      }
    },
    // 查询警情信息
    homeCount() {
      if (this.setIntervalGetCountOpt) {
        clearInterval(this.setIntervalGetCountOpt);
      }
      this.setIntervalGetCount();
      this.setIntervalGetCountOpt = setInterval(
        this.setIntervalGetCount,
        1000 * 60 * 30
      );
    },
    // 定时执行 请求
    setIntervalGetCount() {
      homeCount({
        alarmDivide: "ALARM",
        projectId: this.projectId,
      }).then((res) => {
        this.alarmInfoResult = res.data;
      });
    },
    // 查询获取告警分析等数据
    warningAnalysisList() {
      getWarningAnalysis({
        projectId: this.projectId,
      }).then((res) => {
        this.resultInfo = res.data;
      });
    },
  },
  destroyed() {
    this.closeWebscoket()
    document.getElementById("app").style.background = "#fff";
    document.getElementById("con_lf_top_div").style.background = "#fff";
    document.getElementById("con_lf_top_div").style.overflow = "auto";
    document.getElementById("con_lf_top_div").style.height =
      "calc(100vh - 84px)";
    document.getElementById("con_lf_top_div").style.minHeight =
      "calc(100vh - 84px)";
    document.getElementById("con_lf_top_div").scrollTop = this.thisScrollTopY;
    if (this.setIntervalGetCountOpt) {
      clearInterval(this.setIntervalGetCountOpt);
    }
  },
};
</script>
<style lang="scss">
.big-v3-wrap {
  width: 100%;
  height: calc(100vh - 0px);
  display: flex;
  justify-content: center;
  // background-image: url("../../../assets/images/big/v3/bg.jpg");
  background-color: #051832;
  cursor: default;
  .main-block {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    .count-wrap {
      width: 100%;
      height: calc(100% - 65px);
      display: flex;
      flex-wrap: wrap;
      color: #fff;
      background: #1531f508;
      padding: 0px 10px;
      .count-left {
        display: flex;
        flex-wrap: wrap;
        width: calc(100% - 400px);
        height: calc(100%);
        // padding-left: 20px;
        padding: 0 10px;
        .left-block-1 {
          width: 400px;
          height: calc(100% - 300px);
          padding: 0 10px;
        }
        .map-block-1 {
          width: calc(100% - 405px);
          height: calc(100% - 320px);
          padding-left: 10px;
        }

        .bottom-block-1 {
          width: calc(100% - 5px);
          height: 300px;
        }
      }
      .right-block-1 {
        width: 400px;
        height: calc(100%);
        position: relative;
        padding: 0 10px;
      }
    }
  }
}
.app-main {
  width: 100%;
  height: calc(100vh - 0);
  // background: #021c80;
}
.big-v3-wrap {
  width: 1920px;
  height: 1080px;
  transform-origin: center top 0px;
  position: relative;
  left: 50%;
  margin-left: -960px;
}
</style>

