<template>
  <div class="light" v-if="showLight && lampList && lampList.length">
    <!--如果有子设备-->
    <div class="light-top">
      <div class="light-desc">
        <p class="light-title">
          {{ isShowChildLight ? "光照" : lampList[0].localName }}
        </p>
        <p :class="isShowChildLight ? 'light-status' : 'light-status'">
          {{ lampSw ? "照明已开启" : "照明已关闭" }}
        </p>
      </div>
      <div class="light-right">
        <div class="switch-box" v-if="isShowChildLight">
          <span class="switch-item" @click="eqChange('allLamp', true, 0)"
            >全开</span
          >
          <span class="switch-item" @click="eqChange('allLamp', false, 0)"
            >全关</span
          >
        </div>
        <img :src="lightImg" alt="" v-if="!isShowChildLight" />
      </div>
    </div>

    <div class="light-main-control" v-if="!isShowChildLight">
      <div
        class="main-color"
        v-if="lampList[0].bright || lampList[0].colorTemperature"
      >
        <img
          :src="lightColorImg"
          @click="showLightColorCtrol(lampList[0])"
          alt=""
        />
      </div>
      <div v-else></div>
      <Switch
        v-if="!showFlag"
        :size="23"
        :disabled="!userIsControl"
        v-model="lampSw"
        @click="eqChange('allLamp', '', 0)"
        inactive-color="rgba(196, 196, 196, 0.4)"
        class="switch-btn"
      />
    </div>
    <!--灯控制按钮-->
    <div class="light-box" v-if="isShowChildLight">
      <template v-for="(item, index) in lampList" :key="item.id">
        <div
          class="light-control"
          @click="showLightColorCtrol(item)"
          v-if="showFlag ? index < lampList.length : index < 2"
        >
          <div class="control-top">
            <img :src="item.switch ? item.imgOpen : item.imgClose" alt="" />
            <Switch
              active-color="$elActiveColor"
              :disabled="!userIsControl"
              v-model="item.switch"
              :loading="item.loading"
              size="14px"
              @click.stop="eqChange('main', item, index)"
              inactive-color="rgba(196, 196, 196, 0.2)"
              class="child-switch"
            />
          </div>
          <div class="control-bottom">
            <div class="control-title">
              {{ item.localName }}
            </div>
            <img
              v-if="item.bright || item.colorTemperature"
              :style="{ opacity: item.switch ? '1' : '0.3' }"
              :src="lightColorImg"
              alt=""
            />
          </div>
        </div>
      </template>
    </div>

    <div
      class="show-all"
      v-if="lampList && lampList.length > 2"
      @click.stop="showAll"
    >
      <van-icon :name="lightIcon" class="light-icon" />
      <span v-if="lightIcon == 'arrow-down'">展开更多</span>
      <span v-else>收起全部</span>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  reactive,
  toRefs,
  getCurrentInstance,
  watch,
  onBeforeMount,
  onUnmounted,
  onBeforeUnmount,
} from "vue";
import { Switch, Toast } from "vant";
import { getLampHttp, getStatusHttp, setallLampHttp } from "@/apis/envmonitor";
import { getRelNowTime, parseImgUrl } from "@/utils";
import { type } from "os";
import { onDeactivated } from "vue";
import { AnyMxRecord } from "dns";

export default defineComponent({
  props: {
    projectId: {
      type: String,
      default: () => "",
    },
    controlMode: {
      type: Number,
      default: () => 0,
    },
    spaceId: {
      type: String,
      default: () => "",
    },
    userIsControl: {
      type: Boolean,
      default: () => false,
    },
    forceOverTimeFlag: {
      type: Boolean,
      default: () => false,
    },
    showLight: {
      type: Boolean,
      default: () => false,
    },
    seviceEquipmentList: {
      // 是否走服务定制的设备
      type: Array,
      default: () => [],
    },
  },
  components: { Switch },
  setup(props, contx) {
    const lampList: any = [];
    let lightsStatusTimer: any = null;
    const timeOut: any = null;
    const initData: any = [];
    let lightParams: any = [];
    let statusInterval: any = null;
    const proxyData = reactive({
      seviceEquipmentList: props.seviceEquipmentList,
      showLight: props.showLight,
      spaceId: props.spaceId,
      controlMode: props.controlMode,
      userIsControl: props.userIsControl,
      forceOverTimeFlag: props.forceOverTimeFlag,
      setStatus: 0,
      lightParams: lightParams,
      allowSvg: "down_Arrow.svg",
      timeOut: timeOut,
      lightIcon: "arrow-down",
      showFlag: false,
      loadingLight: false,
      loading: false,
      initData: initData,
      lampList: lampList,
      lightsStatusTimer: lightsStatusTimer,
      startCheckLightsTime: 0,
      lightColorImg: parseImgUrl("page-officehome", "lightColorControl.svg"),
      lightImg: parseImgUrl("page-officehome", "lamp_close.png"),
      lampSw: false, // 主灯开关
      // 点击展示所有的登录
      showAll() {
        proxyData.showFlag = !proxyData.showFlag;
        console.log("proxyData.showFlag==", proxyData.showFlag);
        if (proxyData.showFlag) {
          proxyData.lightIcon = "arrow-up";
        } else {
          proxyData.lightIcon = "arrow-down";
        }
      },
      // 点击展示调色和调温弹窗
      showLightColorCtrol(item: any, e: any = null) {
        console.log(item);

        if (item.switch && (item.bright || item.colorTemperature)) {
          contx.emit("showLightColorCtrol", item);
        }
      },
      // 检查设备是否执行空间服务时间
      checkDeviceIsExeSpaceTime(deviceAll: any = []) {
        // debugger
        if (proxyData.controlMode !== 1) {
          return true;
        }
        let seviceEquipmentList: any = proxyData.seviceEquipmentList;
        let flag: any = false;
        for (let i = 0; i < seviceEquipmentList.length; i++) {
          for (let j = 0; j < deviceAll.length; j++) {
            if (
              seviceEquipmentList[i].id == deviceAll[j].id &&
              seviceEquipmentList[i].isExeSpaceTime
            ) {
              flag = true;
              break;
            }
          }
          if (flag) {
            break;
          }
        }
        return flag;
      },
      // 获取灯的状态
      getLampList() {
        getLampHttp({ spaceId: proxyData.spaceId })
          .then((res) => {
            const resData: any = res;
            if (!proxyData.setStatus) {
              // console.log("灯的状态修改--");
              if (resData && resData.result == "success") {
                let content = resData?.content ?? [];
                let lampOpen = false; // 如果有一个开 则总灯开
                for (let i = 0; i < content.length; i++) {
                  content[i].type = "lamp";
                  if (content[i].lightType == 1) {
                    content[i].imgOpen = parseImgUrl(
                      "page-officehome",
                      "lamp_open.png"
                    );
                    content[i].imgClose = parseImgUrl(
                      "page-officehome",
                      "lamp_close.png"
                    );
                  } else {
                    content[i].imgOpen = parseImgUrl(
                      "page-officehome",
                      "atmLamp_small_open.png"
                    );
                    content[i].imgClose = parseImgUrl(
                      "page-officehome",
                      "atmLamp_small_close.png"
                    );
                  }

                  content[i].switch = content[i].runStatus ? true : false;
                  if (content[i].runStatus) {
                    lampOpen = true;
                  }
                  content[i].loading = false;
                }
                proxyData.initData = JSON.parse(JSON.stringify(content)); //  灯的数据
                proxyData.lampSw = lampOpen; // 主灯开关
                proxyData.lampList = content;

                proxyData.lightImg = proxyData.lampSw
                  ? parseImgUrl("page-officehome", "lamp_open.png")
                  : parseImgUrl("page-officehome", "lamp_close.png");
                if (content[0]) {
                  if (content[0].lightType !== 1) {
                    proxyData.lightImg = proxyData.lampSw
                      ? parseImgUrl("page-officehome", "atmLamp_small_open.png")
                      : parseImgUrl(
                          "page-officehome",
                          "atmLamp_small_close.png"
                        );
                  }
                }
              }
            }
            // console.log("执行了----====");
            proxyData.startLightsStatusTimer();
          })
          .catch(() => {
            proxyData.startLightsStatusTimer();
          });
      },
      // 调整灯
      eqChange(type: any, item: any, index: any) {
        if (proxyData.userIsControl) {
          // debugger
          if (type === "allLamp") {
            let isExeSpaceTime: Boolean = proxyData.checkDeviceIsExeSpaceTime(
              proxyData.lampList
            );
            if (item !== "") {
              proxyData.lampSw = item; // 点击全开和全关的时候item动态传值true或者false
            }
            // debugger
            if (
              proxyData.forceOverTimeFlag &&
              proxyData.lampSw &&
              isExeSpaceTime
            ) {
              // 强制加班开灯
              contx.emit("triggerWork", 3);
              return;
            }
            //  总开关按钮所有灯
            //  当前要执行的灯的操作
            proxyData.loading = true;
            proxyData.loadingLight = true;
            proxyData.lightImg = proxyData.lampSw
              ? parseImgUrl("page-officehome", "lamp_open.png")
              : parseImgUrl("page-officehome", "lamp_close.png");
            const statusFlag = proxyData.lampSw;
            // 瞬间修改状态
            proxyData.setStatus = 15; // 点击后状态重新计算
            proxyData.updateAllLampStatus(statusFlag);
            proxyData.setLamp(type, "", statusFlag, 0); // 调接口
          } else {
            let isExeSpaceTime: Boolean = proxyData.checkDeviceIsExeSpaceTime([
              item,
            ]);
            debugger;
            if (proxyData.forceOverTimeFlag && item.switch && isExeSpaceTime) {
              // 强制加班开灯
              contx.emit("triggerWork", 3, item);
              return;
            }
            //当前要执行的灯的操作
            // 按钮loading
            item.loading = true;
            const statusFlag: any = item.switch;
            let id = item.id;
            proxyData.setStatus = 15;
            proxyData.updateLampStatus(item, statusFlag);
            proxyData.setLamp(type, id, statusFlag, index, item); // 调接口
          }
        } else {
          Toast("您没有当前空间的控制权限！");
        }
      },
      // 定时查看灯的状态是否需要更新
      statusInterval: statusInterval,
      setStatusNum() {
        clearInterval(proxyData.statusInterval);
        proxyData.statusInterval = setInterval(() => {
          proxyData.setStatus--;
          if (proxyData.setStatus == 1) {
            proxyData.setStatus = 0;
            clearInterval(proxyData.statusInterval);
          }
        }, 1000);
      },
      //  控制灯的接口
      setLamp(
        type: string,
        id: any,
        statusFlag: any,
        index: any,
        item: any = null
      ) {
        let params: any = [];
        if (type === "allLamp") {
          for (let i = 0; i < proxyData.initData.length; i++) {
            proxyData.initData[i].switch = statusFlag;
          }
          params = proxyData.initData;
        } else {
          params = [
            {
              id: id,
              switch: statusFlag,
            },
          ];
        }
        proxyData.lightParams = params;
        // 调服务端的接口像后台发送灯的操作的指令
        setallLampHttp(params)
          .then((res) => {
            const resData: any = res;
            // set成功后15s更新灯的状态
            proxyData.setStatusNum();
            if (item) {
              item.loading = false;
            }
            if (resData.result === "success") {
              // const checkData: any = proxyData.judgeChangeResponeseSuccess(resData)
              // proxyData.getTimeLampStatus(checkData, type, id, statusFlag, index)
            } else {
              proxyData.initLampLoading();
            }
          })
          .catch((error: any) => {
            // set成功后15s更新灯的状态
            proxyData.setStatusNum();
            if (item) {
              item.loading = false;
            }
            // console.log(error)
            Toast("连接异常,请检查网络！");
          });
      },
      // 报错后关闭灯的loading
      initLampLoading() {
        proxyData.loadingLight = false;
        proxyData.lampList.map((item: any) => {
          item.loading = false;
        });
      },
      //手动修改灯的状态
      updateAllLampStatus(statusFlag: any) {
        proxyData.lampSw = statusFlag;
        for (let i = 0; i < proxyData.lampList.length; i++) {
          proxyData.lampList[i].switch = statusFlag;
          // if (proxyData.lampList[i].type == 'lamp') {
          // }
        }
      },
      // 单个灯的状态修改
      updateLampStatus(item: any, statusFlag: any) {
        item.switch = statusFlag;
      },
      // 轮询查看状态
      getTimeLampStatus(
        checkData: any,
        type: any,
        id: any,
        statusFlag: any,
        index: any
      ) {
        if (checkData["success"] && checkData["success"].length) {
          if (type === "allLamp") {
            // 点击主灯按钮
            proxyData.updateAllLampLoading(checkData["success"]); // 所有灯
          } else {
            // 当个的时候修改loading的状态
            proxyData.updateLampLoading(index);
          }
          proxyData.getLampList();
        }
        if (checkData["processing"] && checkData["processing"].length) {
          let checkParams: any = proxyData.lightParams;
          let processArr: any = checkData["processing"];
          let params: any = [];
          processArr.map((item: any) => {
            let obj: any = {
              id: item.id,
              orderSeqNum: item.orderSeqNum,
            };
            for (let i = 0; i < checkParams.length; i++) {
              if (item.id === checkParams[i].id) {
                obj.switch = checkParams[i].switch;
                break;
              }
            }
            params.push(obj);
          });
          proxyData.checkChangeLightStatusSuccess(
            params,
            type,
            id,
            statusFlag,
            index
          );
        }
        if (checkData["error"] && checkData["error"].length) {
          if (type === "allLamp") {
            // 点击主灯按钮
            proxyData.updateAllLampLoading(checkData["error"]); // 所有灯
          } else {
            // 当个的时候修改loading的状态
            proxyData.updateLampLoading(index);
          }
        }
      },
      // 查看指令是否成功完成
      judgeChangeResponeseSuccess(resData: any) {
        let data: any = resData?.content ?? [];
        let processingArr: any = [];
        let successArr: any = [];
        let errorArr: any = [];
        for (let i = 0; i < data.length; i++) {
          let item: any = data[i];
          if ((item.result = "success")) {
            if (item.state === 200 && item.exeResult === "success") {
              successArr.push(item);
            } else if (
              (item.state === 200 && item.exeResult === "processing:rcvd") ||
              (item.state === 202 && !item.exeResult)
            ) {
              processingArr.push(item);
            } else {
              errorArr.push(item);
            }
          } else {
            errorArr.push(item);
          }
        }
        let obj: any = {
          success: successArr,
          processing: processingArr,
          error: errorArr,
        };
        return obj;
      },
      // 操作成功后更新所有灯的真实状态
      updateAllLampLoading(arr: any) {
        for (let i = 0; i < proxyData.lampList.length; i++) {
          if (proxyData.lampList[i].type == "lamp") {
            arr.map((item: any) => {
              if (proxyData.lampList[i].id === item.id) {
                proxyData.lampList[i].loading = false;
              }
            });
          }
        }
        let loadingLen = proxyData.lampList.filter((item: any) => {
          return item.loading;
        });
        if (loadingLen.length === 0) {
          proxyData.loadingLight = false;
        }
      },
      // 动态切换主灯的状态
      updateLampLoading(index: any) {
        proxyData.lampList[index].loading = false;
      },
      // 灯的指令完成后更新状态
      checkChangeLightStatusSuccess(
        checkParams: any,
        type: any,
        id: any,
        value: any,
        index: any
      ) {
        // 轮询查询灯的状态
        getStatusHttp(checkParams).then((res) => {
          const resData: any = res;
          const checkData: any = proxyData.judgeChangeResponeseSuccess(resData);
          proxyData.getTimeLampStatus(checkData, type, id, value, index);
        });
      },
      // 灯灯接口清除定时器
      clearLightStatusTimer() {
        clearTimeout(proxyData.lightsStatusTimer);
        proxyData.lightsStatusTimer = null;
      },
      // 定时刷新接口
      startLightsStatusTimer(timerLen: any = 15000) {
        let nowTime: any = getRelNowTime();
        if (timerLen == 15000 && nowTime < "070000" && nowTime > "200000") {
          timerLen = 300000;
        }
        proxyData.clearLightStatusTimer();
        proxyData.lightsStatusTimer = setTimeout(() => {
          proxyData.clearLightStatusTimer();
          proxyData.getLampList();
        }, timerLen);
      },
    });
    const isShowChildLight: any = computed(() => {
      return proxyData.lampList.length && proxyData.lampList.length > 1;
    });
    // onDeactivated(()=>{
    //   destroyWatch()
    // })
    watch(
      [() => props, () => props.spaceId],
      (newProps: any, oldProps: any) => {
        // debugger
        if (newProps[0]) {
          proxyData.showLight = newProps[0].showLight;
          proxyData.userIsControl = newProps[0].userIsControl;
          proxyData.controlMode = newProps[0].controlMode;
          proxyData.forceOverTimeFlag = newProps[0].forceOverTimeFlag;
          proxyData.seviceEquipmentList = newProps[0].seviceEquipmentList;
        }

        if (newProps[1] && oldProps[1] && newProps[1] != oldProps[1]) {
          // 空间id改变的重新获取值调用接口
          proxyData.clearLightStatusTimer();
          proxyData.showFlag = false;
          proxyData.lampList = [];
          proxyData.spaceId = newProps[1];
          proxyData.getLampList();
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );
    onBeforeUnmount(() => {
      console.log("灯的组件销毁了--");
      proxyData.clearLightStatusTimer();
    });
    onMounted(() => {
      // proxyData.clearLightStatusTimer();
      proxyData.getLampList();
    });
    return {
      isShowChildLight,
      ...toRefs(proxyData),
    };
  },
});
</script>
<style lang="scss" scoped>
.light {
  width: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.07), 0px 4px 10px rgba(0, 0, 0, 0.05);
  border-radius: 25px;
  margin: 15px 0px;
}

.light-main {
  padding-left: 20px;
  padding-bottom: 10px;
  padding-top: 10px;
}

.light-top {
  padding-left: 20px;
  // padding-bottom: 14px;
  // padding-top: 10px;
  display: flex;
  justify-content: space-between;
}
.light-main-control {
  padding-bottom: 16px;
  padding-left: 20px;
  padding-right: 20px;
  // line-height: 36px;
  display: flex;
  justify-content: space-between;
  text-align: right;
  div {
    width: 36px;
  }
  .main-color {
    width: 36px;
    height: 36px;
    // line-height: 36px;
    text-align: center;
    border-radius: 50%;
    background: #f7f9fa;
    img {
      width: 20px;
      height: 20px;
      margin-top: 8px;
    }
  }
  .switch-btn {
    margin-top: 6px;
    // margin-right: 12px;
  }
}

.light-desc {
  padding-top: 24px;
  font-family: "PingFang SC";
  font-size: 16px;
  font-weight: 600;
  line-height: 22px;
  letter-spacing: 0;
  text-align: left;
}

.light-right {
  position: relative;
  text-align: center;
  .switch-box {
    padding-top: 33px;
    padding-right: 15px;
    span {
      display: inline-block;
      font-family: "PingFang SC";
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      color: #2e3742;
      margin-left: 20px;
      // width: 60px;
      height: 32px;
      line-height: 32px;
      padding: 0 15px;
      background: #f1f4f6;
      border-radius: 21px;
    }
    .switch-item {
      &:hover {
        background: #e8ecf0;
      }
      &:active {
        background: #e8ecf0;
      }
    }
  }

  img {
    //width: 98px;
    height: 100px;
  }

  .switch-btn {
    position: absolute;
    right: -20px;
    bottom: 20px;
  }
}

.light-title {
  font-family: "PingFang SC";
  font-size: 16px;
  line-height: 19px;
  color: #4d5262;
  flex: none;
  order: 0;
  flex-grow: 0;
}

.light-status {
  font-family: "PingFang SC";
  font-size: 14px;
  font-weight: 400;
  line-height: 20px;
  padding-top: 8px;
  color: rgba(196, 196, 196, 1);
}

.show-all {
  font-family: "PingFang SC";
  font-style: normal;
  font-weight: 400;
  font-size: 12px;
  line-height: 17px;
  padding-bottom: 15px;
  // padding-top: 5px;
  color: #cccccc;
  text-align: center;
  .light-icon {
    font-size: 12px;
    padding-right: 10px;
  }
}

.light-box {
  padding: 0 12px;
  font-size: 0;
  padding-top: 14px;
  padding-bottom: 8px;
}
.light-control {
  display: inline-block;
  width: 49%;
  vertical-align: middle;
  background: #f7f9fa;
  border-radius: 16px;
  margin-bottom: 12px;
  // margin-left: 2%;

  &:nth-child(2n - 1) {
    margin-right: 2%;
  }
  .control-top {
    display: flex;
    padding-right: 16px;
    padding-bottom: 12px;
    justify-content: space-between;
    img {
      width: 80px;
      height: 70px;
      vertical-align: middle;
    }
    .child-switch {
      margin-top: 16px;
      display: inline-block;
      vertical-align: middle;
    }
  }

  .control-bottom {
    display: flex;
    justify-content: space-between;
    padding-right: 16px;
    padding-left: 18px;
    padding-bottom: 15px;
    .control-title {
      font-weight: 500;
      font-family: "PingFang SC";
      color: #4d5262;
      font-size: 16px;
      line-height: 20px;
    }
    img {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }
}
</style>
<style class="style" lang="scss">
.light {
  .van-loading__spinner {
    color: $elActiveColor !important;
  }

  .van-switch__loading {
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    line-height: 1;
  }

  .van-switch--disabled {
    opacity: 0.5;
  }
}
</style>
