<template>
    <div class="light" v-if="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 class="show-all" @click.stop="showAll" v-if="isShowChildLight">
            <van-icon :name="lightIcon" class="light-icon" />
            <span>显示全部</span>
          </div>
        </div>
        <div class="light-right">
          <img :src="lightImg" alt="" />
          <Switch
            v-if="!showFlag"
            :disabled="!userIsControl"
            v-model="lampSw"
            @click="eqChange('allLamp', '', 0)"
            inactive-color="rgba(196, 196, 196, 0.4)"
            class="switch-btn"
          />
        </div>
      </div>
      <!--灯控制按钮-->
      <template v-if="showFlag && isShowChildLight">
        <div
          class="light-control"
          v-for="(item, index) in lampList"
          :key="item.id"
        >
          <div class="control-title">
            {{ item.localName }}
          </div>
          <Switch
            active-color="$elActiveColor"
            :disabled="!userIsControl"
            v-model="item.switch"
            @click="eqChange('main', item, index)"
            inactive-color="rgba(196, 196, 196, 0.2)"
            class="switch-btn"
          />
        </div>
      </template>
    </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 { parseImgUrl } from "@/utils";
  
  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,
      },
      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 = [];
      const proxyData = reactive({
        seviceEquipmentList: props.seviceEquipmentList,
        controlMode: props.controlMode,
        userIsControl: props.userIsControl,
        forceOverTimeFlag: props.forceOverTimeFlag,
        setStatus: false,
        lightParams: lightParams,
        allowSvg: "down_Arrow.svg",
        timeOut: timeOut,
        lightIcon: "arrow-down",
        showFlag: false,
        loadingLight: false,
        initData: initData,
        lampList: lampList,
        lightsStatusTimer: lightsStatusTimer,
        startCheckLightsTime: 0,
        lightImg: parseImgUrl("page-officehome", "lamp_close_v2.png"),
        lampSw: false, // 主灯开关
        // 点击展示所有的登录
        showAll() {
          proxyData.showFlag = !proxyData.showFlag;
          proxyData.lightIcon = "arrow-down";
        },
        // 检查设备是否执行空间服务时间
        checkDeviceIsExeSpaceTime(deviceAll: any = []) {
          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: props.spaceId })
            .then((res) => {
              const resData: any = res;
              if (!proxyData.setStatus) {
                if (resData && resData.result == "success") {
                  let content = resData?.content ?? [];
                  let lampOpen = false; // 如果有一个开 则总灯开
                  for (let i = 0; i < content.length; i++) {
                    content[i].type = "lamp";
                    content[i].imgOpen = parseImgUrl(
                      "page-officehome",
                      "lampch_open.png"
                    );
                    content[i].imgClose = parseImgUrl(
                      "page-officehome",
                      "lampch_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_v2.png")
                    : parseImgUrl("page-officehome", "lamp_close_v2.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 (
                proxyData.forceOverTimeFlag &&
                proxyData.lampSw &&
                isExeSpaceTime
              ) {
                // 强制加班开灯
                contx.emit("triggerWork", 3);
                return;
              }
              //  总开关按钮所有灯
              //  当前要执行的灯的操作
              proxyData.loadingLight = true;
              // const statusFlag = !proxyData.lampSw
              // console.log('proxyData.lampSw==')
              const statusFlag = proxyData.lampSw;
              // 瞬间修改状态
              proxyData.setStatus = true;
              proxyData.updateAllLampStatus(statusFlag);
              proxyData.setLamp(type, "", statusFlag, 0); // 调接口
            } else {
              let isExeSpaceTime: Boolean = proxyData.checkDeviceIsExeSpaceTime([
                item,
              ]);
              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 = true;
              proxyData.updateLampStatus(item, statusFlag);
              proxyData.setLamp(type, id, statusFlag, index); // 调接口
            }
          } else {
            Toast("您没有当前空间的控制权限！");
          }
        },
        //  控制灯的接口
        setLamp(type: string, id: any, statusFlag: any, index: any) {
          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成功后1s关闭定时器
              setTimeout(() => {
                proxyData.setStatus = false;
              }, 1000);
              if (resData.result === "success") {
                // const checkData: any = proxyData.judgeChangeResponeseSuccess(resData)
                // proxyData.getTimeLampStatus(checkData, type, id, statusFlag, index)
              } else {
                proxyData.initLampLoading();
              }
            })
            .catch(() => {
              setTimeout(() => {
                proxyData.setStatus = false;
              }, 1000);
            });
        },
        // 报错后关闭灯的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;
          // let flag: any = true
          // for (let i = 0; i < proxyData.lampList.length; i++) {
          //   if (proxyData.lampList[i].type == 'lamp') {
          //     if (proxyData.lampList[i].switch !== statusFlag) {
          //       flag = false
          //       break
          //     }
          //   }
          // }
        },
        // 轮询查看状态
        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 = 2000) {
          proxyData.lightsStatusTimer = setTimeout(() => {
            proxyData.getLampList();
            proxyData.clearLightStatusTimer();
          }, timerLen);
        },
      });
      const isShowChildLight = computed(() => {
        return proxyData.lampList.length && proxyData.lampList.length > 1;
      });
      watch(
        props,
        (newProps: any) => {
          // 定时调空间信息
          proxyData.userIsControl = newProps.userIsControl;
          proxyData.controlMode = newProps.controlMode;
          proxyData.forceOverTimeFlag = newProps.forceOverTimeFlag;
          proxyData.seviceEquipmentList = newProps.seviceEquipmentList;
          if (newProps.spaceId) {
            // 空间id改变的重新获取值调用接口
            proxyData.clearLightStatusTimer();
            proxyData.getLampList();
            console.log("调用了====");
          }
        },
        {
          deep: false,
          immediate: true,
        }
      );
      onBeforeUnmount(() => {
        proxyData.clearLightStatusTimer();
      });
      onMounted(() => {});
      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-top {
    padding-left: 20px;
    padding-bottom: 0px;
    display: flex;
    justify-content: space-between;
  }
  
  .light-desc {
    flex: 1 98px;
    padding-top: 10px;
    font-family: PingFang SC;
    font-size: 16px;
    line-height: 19px;
    color: #4d5262;
    flex: none;
    order: 0;
    flex-grow: 0;
    margin: 5px 0px;
  }
  
  .light-right {
    position: relative;
    width: 98px;
    margin-right: 45px;
    text-align: center;
  
    img {
      //width: 98px;
      height: 120px;
    }
  
    .switch-btn {
      position: absolute;
      right: -20px;
      bottom: 20px;
    }
  }
  
  .light-title {
    font-family: PingFang SC;
    padding-left: 5px;
    font-size: 16px;
    line-height: 19px;
    color: #4d5262;
    flex: none;
    order: 0;
    flex-grow: 0;
    margin: 5px 0px;
  }
  
  .light-status {
    font-family: PingFang SC;
    padding-left: 5px;
    font-size: 14px;
    line-height: 16px;
    color: #c4c4c4;
    flex: none;
    order: 1;
    flex-grow: 0;
    margin: 10px 0px;
  }
  
  .show-all {
    font-family: PingFang SC;
    //display: none;
    .light-icon {
      font-size: 12px;
      padding-right: 10px;
    }
  
    padding-top: 28px;
    padding-bottom: 22px;
    font-size: 14px;
    line-height: 16px;
    color: #c4c4c4;
    margin: 0px 5px;
  }
  
  .light-control {
    display: flex;
    justify-content: space-between;
    padding: 10px 15px 10px 28px;
    border-top: 1px solid rgba(196, 196, 196, 0.4);
  
    .control-title {
      flex: 1 110px;
      font-weight: 500;
      font-family: PingFang SC;
      font-size: 16px;
      line-height: 30px;
      color: #4d5262;
    }
  
    .switch-btn {
      margin-top: 5px;
    }
  }
  </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>
  