<template>
  <div
    class="socket-box"
    v-if="socketData && socketData.equipList && socketData.equipList.length"
  >
    <div class="socket-top">
      <div class="socket-desc">
        <p class="socket-title">智能插座</p>
        <p class="socket-status" v-if="socketData.isOpen">插座已开启</p>
        <p class="socket-status" v-else>插座已关闭</p>
      </div>
      <div class="socket-right">
        <img
          v-if="socketData.isOpen"
          :src="parseImgUrl('ipdImages', 'socket-active.svg')"
          alt=""
        />
        <img v-else :src="parseImgUrl('ipdImages', 'socket.svg')" alt="" />
      </div>
    </div>
    <div class="top-switch">
      <div
        class="top-nav"
        v-if="
          socketData && socketData.equipList && socketData.equipList.length > 1
        "
      >
        <span
          :class="navType == 'all' ? 'nav-active' : ''"
          @click="checkNav('all')"
        >
          总控制
        </span>
        <span
          :class="navType == 'child' ? 'nav-active' : ''"
          @click="checkNav('child')"
        >
          子设备
        </span>
      </div>
      <div v-else></div>
      <Switch
        class="switch-btn"
        v-if="navType == 'all'"
        :size="23"
        @click="socketControl('all')"
        inactive-color="rgba(196, 196, 196, 0.4)"
        :model-value="socketData.isOpen"
      />
    </div>
    <template v-if="navType == 'child'">
      <div
        class="socket-child"
        :key="item.id"
        v-for="item in socketData.equipList"
      >
        <div class="child-item">
          <span>{{ item.localName }}</span>
          <Switch
            class="switch-btn"
            @click="socketControl('child', item)"
            :model-value="item.isOpen"
            inactive-color="rgba(196, 196, 196, 0.4)"
            :size="23"
          />
        </div>
      </div>
    </template>
  </div>
</template>
<script lang="ts">
import { Switch, Dialog, Toast } from "vant";
import {
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
  watch,
} from "vue";
import { getRelNowTime, parseImgUrl, setQueryConfig } from "@/utils";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import axios from "axios";
import {
  queryEquipmentStatusInfo,
  setSpaceCondtioners,
} from "@/apis/envmonitor";

export default defineComponent({
  props: {
    temperature: {
      // 空调基本信息
      type: Number,
      default: () => 0,
    },
    showSocket: {
      // 有无空调
      type: Boolean,
      default: () => false,
    },
    airVolumes: {
      // 风量信息
      type: Array,
      default: () => [],
    },
    projectId: {
      type: String,
      default: () => "",
    },
    spaceId: {
      type: String,
      default: () => "",
    },
    userIsControl: {
      type: Boolean,
      default: () => false,
    },
    forceOverTimeFlag: {
      type: Boolean,
      default: () => false,
    },
    seviceEquipmentList: {
      // 是否走服务定制的设备
      type: Array,
      default: () => [],
    },
  },
  components: {
    Switch,
    [Dialog.Component.name]: Dialog.Component,
  },
  setup(props, contx) {
    const route: any = useRoute();
    let socketData: any = {
      isOpen: false,
    };
    let socketTimer: any = null;
    let loadingTimer: any = null;
    const proxyData = reactive({
      parseImgUrl: parseImgUrl,
      distroyFlag: false,
      showSocket: props.showSocket,
      navType: "all",
      projectId: props.projectId,
      spaceId: props.spaceId,
      socketData: socketData,
      checkNav(type: any = "all") {
        proxyData.navType = type;
      },
      // 不通型号设备的时长不一样,拓展
      getTimerLen() {
        return 15;
      },
      loadingTimer: loadingTimer,
      loadingNum: 0,
      setLoadingNumber() {
        let timerLen: any = proxyData.getTimerLen();
        proxyData.loadingTimer = setInterval(() => {
          proxyData.loadingNum++;
          if (proxyData.loadingNum >= timerLen) {
            clearInterval(proxyData.loadingTimer);
            proxyData.loadingTimer = null;
            proxyData.loadingNum = 0;
            proxyData.getSocketTimer(0);
          }
        }, 1000);
      },
      // 刷新空调状态的接口
      updateLoadingNum() {
        clearTimeout(proxyData.socketTimer);
        proxyData.socketTimer = null;
        proxyData.loadingNum = 1;
        if (!proxyData.loadingTimer) {
          proxyData.setLoadingNumber();
        }
      },
      socketTimer: socketTimer,
      // 定时获取插座列表
      getSocketTimer(timerLong: any = 15000) {
        let nowTime: any = getRelNowTime();
        if (timerLong == 15000 && nowTime < "070000" && nowTime > "200000") {
          timerLong = 300000;
        }
        console.log("nowTime===", nowTime);

        if (proxyData.socketTimer) {
          clearTimeout(proxyData.socketTimer);
          proxyData.socketTimer = null;
        }
        proxyData.socketTimer = setTimeout(function () {
          if (!proxyData.distroyFlag) {
            if (!proxyData.loadingNum) {
              proxyData.querySocketInfo();
            }
          }
        }, timerLong);
      },
      querySocketInfo(isAddTimer: any = 0) {
        let params: any = {
          spaceId: proxyData.spaceId,
          equipType: "socket",
        };
        let paramsStr: any = setQueryConfig(params);
        queryEquipmentStatusInfo(paramsStr)
          .then((res: any) => {
            let data: any = res.data || {};
            proxyData.socketData = data;
            if (proxyData.socketData && proxyData.socketData.runStatus) {
              proxyData.socketData.isOpen = true;
            }
            if (
              proxyData.socketData &&
              proxyData.socketData.equipList &&
              proxyData.socketData.equipList.length
            ) {
              proxyData.socketData.equipList.map((item: any) => {
                item.isOpen = item.runStatus ? true : false;
              });
            }

            if (isAddTimer == 0) {
              proxyData.getSocketTimer();
            }
          })
          .catch(() => {
            if (isAddTimer == 0) {
              proxyData.getSocketTimer();
            }
          });
      },
      // 更新父亲设备的状态
      updateParentSwitch() {
        let flag: any = false;
        proxyData.socketData.equipList.map((item: any) => {
          if (item.isOpen) {
            flag = true;
          }
        });
        proxyData.socketData.isOpen = flag;
      },
      // 更新子设备的状态
      updateChildSwitch() {
        proxyData.socketData.equipList.map((item: any) => {
          item.isOpen = proxyData.socketData.isOpen;
        });
      },
      // 插座控制
      socketControl(type: any, item: any = null) {
        // 下发指令的时候先关闭定时器
        proxyData.updateLoadingNum();
        let arr: any = [];
        if (type == "all") {
          proxyData.socketData.isOpen = !proxyData.socketData.isOpen;
          if (
            proxyData.socketData &&
            proxyData.socketData.equipList &&
            proxyData.socketData.equipList.length
          ) {
            proxyData.updateChildSwitch();
            proxyData.socketData.equipList.map((item: any) => {
              let obj: any = {
                id: item.id, //类型：String  必有字段  备注：设备id
                code: item.switchCode, //类型：String  必有字段  备注：编码 EquipSwtichSet
                value: proxyData.socketData.isOpen ? 1 : 0, //类型：String  必有字段  备注：值 0
              };
              arr.push(obj);
            });
          }
        } else if (type == "child") {
          console.log(item);
          item.isOpen = !item.isOpen;
          let obj: any = {
            id: item.id, //类型：String  必有字段  备注：设备id
            code: item.switchCode, //类型：String  必有字段  备注：编码 EquipSwtichSet
            value: item.isOpen ? 1 : 0, //类型：String  必有字段  备注：值 0
          };
          arr.push(obj);
          proxyData.updateParentSwitch();
        }
        // 下发开/关的指令
        proxyData.setSpaceCondtioners(arr);
      },
      // 改变设备状态
      setSpaceCondtioners(data: any) {
        setSpaceCondtioners(data)
          .then((res) => {})
          .catch(() => {
            Toast("连接异常,请检查网络！");
          });
      },
    });
    watch(
      [() => props, () => props.spaceId],
      (newProps: any, oldProps: any) => {
        if (newProps[0]) {
          proxyData.showSocket = newProps[0].showSocket;
        }
        if (newProps[1] && newProps[1] != oldProps[1]) {
          proxyData.distroyFlag = false;
          proxyData.spaceId = newProps[1];
          proxyData.querySocketInfo();
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );
    onBeforeUnmount(() => {
      proxyData.distroyFlag = true;
      clearTimeout(proxyData.socketTimer);
      proxyData.socketTimer = null;
    });
    onMounted(() => {
      proxyData.distroyFlag = false;
      proxyData.querySocketInfo(1);
    });
    return {
      ...toRefs(proxyData),
    };
  },
});
</script>

<style lang="scss" scoped>
.socket-box {
  border-radius: 25px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.07);
  .socket-top {
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 12px;
    padding-top: 24px;
    display: flex;
    justify-content: space-between;
    .socket-desc {
      position: relative;
      font-family: PingFang SC;
      font-size: 16px;
      line-height: 19px;
      color: #4d5262;
      flex: none;
      flex-grow: 0;
      margin: 5px 0px;
      // min-height: 100px;
      .socket-title {
        font-family: "PingFang SC";
        // padding-left: 5px;
        font-size: 16px;
        line-height: 20px;
        color: #4d5262;
        padding-bottom: 10px;
        i {
          display: inline-block;
          font-size: 12px;
          transform: scale(0.9);
          font-style: normal;
          padding-left: 5px;
          color: #c4c4c4;
        }
      }
      .socket-status {
        font-family: "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        // padding-left: 5px;
        line-height: 20px;
        letter-spacing: 0em;
        text-align: left;
        color: rgba(196, 196, 196, 1);
      }
      .show-all {
        position: absolute;
        width: 110px;
        bottom: -8px;
        font-family: PingFang SC;
        font-size: 14px;
        line-height: 16px;
        color: #c4c4c4;
        margin: 0px 5px;
        span {
          font-size: 12px;
        }
        .light-icon {
          font-size: 12px;
          padding-right: 10px;
        }
      }
    }
    .socket-right {
      position: relative;
      width: 157px;
      text-align: center;

      img {
        width: 70px;
        height: 70px;
      }

      .switch-btn {
        position: absolute;
        z-index: 111;
        bottom: -5px;
        right: 25px;
      }
    }
  }
  .top-switch {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    padding-bottom: 24px;
    .top-nav {
      height: 28px;
      // line-height: 28px;
      border-radius: 21px;
      background: #f1f4f6;
      span {
        box-sizing: border-box;
        display: inline-block;
        font-family: "PingFang SC";
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        padding: 7px 8px;
        height: 28px;
        line-height: 14px;
        color: #424c59;
      }
      .nav-active {
        background: #fff;
        border: 1px solid #e1e5eb;
        border-radius: 21px;
      }
    }
    .switch-btn {
      margin-top: 0;
    }
  }
  .line {
    width: 100%;
    height: 0px;
    border-top: 1px solid rgba(232, 236, 240, 1);
  }
  .socket-child {
    border-top: 1px solid rgba(232, 236, 240, 1);
    padding: 16px 20px;
    .child-item {
      display: flex;
      justify-content: space-between;
      span {
        font-size: 16px;
        font-weight: 500;
        font-family: "PingFang SC";
        color: #4d5262;
        line-height: 22px;
        letter-spacing: 0em;
        text-align: left;
      }
    }
  }
}
</style>
    
  
    