<template>
  <div class="air">
    <div class="air-top">
      <div class="air-desc">
        <p class="air-title">空调</p>
        <p class="air-temperature">
          {{ airData.tempSet ? airData.tempSet : "" }}
          <sup v-if="airData.tempSet">℃</sup>
        </p>
        <!-- <p class="air-model">
          <span v-if="modeName">
            {{ modeName }}
          </span>
          <span v-if="airData.tempSet"> {{ airData.tempSet }}℃ </span>
        </p> -->
        <p class="air-status" v-if="hasAir">
          {{ airData.isOpen ? "空调已开启" : "空调已关闭" }}
        </p>
        <p class="air-loading" v-if="airData.isOpen">
          <img
            v-if="airData.icon == 1 || airData.icon == 2 || airData.icon == 3"
            :src="airRunImg"
            alt=""
          />
          <span>{{ airData.spaceStatus }}</span>
        </p>
      </div>
      <div class="air-right">
        <img v-if="airData.airImg" :src="airData.airImg" alt="" />
        <van-loading style="padding-top: 20px" v-else />

        <Switch
          class="switch-btn"
          size="18px"
          :loading="loadingAir || firstLoadingAir"
          :disabled="!userIsControl || loadingAir || firstLoadingAir"
          inactive-color="rgba(196, 196, 196, 0.4)"
          @click="airChange"
          :model-value="airData.isOpen"
          v-if="hasAir"
        />
      </div>
    </div>
    <!--温度调节-->
    <div class="air-control" v-if="userIsControl && airData.isOpen">
      <div class="control-title">温度调节</div>
      <div class="btn-box">
        <div
          class="control-btn mr20"
          @click.stop="changeAir(4, 'temp', 'toCold')"
        >
          <img :src="parseImgUrl('envmonitor', 'arrow-top.png')" alt="" />
        </div>
        <div class="control-btn" @click.stop="changeAir(2, 'temp', 'toWarm')">
          <img :src="parseImgUrl('envmonitor', 'arrow-down.png')" alt="" />
        </div>
      </div>
    </div>
    <div
      class="air-control"
      v-if="userIsControl && airData.isOpen && showAirVolumeBtn"
    >
      <div class="control-title">风量调节</div>
      <div class="btn-box">
        <div
          class="control-btn mr20"
          @click.stop="changeAir(5, 'wind', 'toWindLow')"
        >
          <img
            class="temp-img"
            :src="parseImgUrl('envmonitor', 'fengshan.png')"
            alt=""
          />
        </div>
        <div class="control-btn" @click.stop="changeAir(6, 'wind', 'toWindUp')">
          <img
            class="temp-img"
            :src="parseImgUrl('envmonitor', 'wendu.png')"
            alt=""
          />
        </div>
      </div>
    </div>

    <!-- 空调反馈 文案 -->
    <van-dialog
      v-model:show="showDialog"
      class="dialog-width"
      :show-confirm-button="false"
      :show-cancel-button="false"
    >
      <div class="air-dialog-content">
        <div class="dialog-top">
          <img
            class="img-greey"
            :class="
              airSetText.toWhere == 'toCold'
                ? 'img-blue'
                : airSetText.toWhere == 'toWarm'
                ? 'img-red'
                : ''
            "
            :src="parseImgUrl('page-officehome', airSetText.nowImg)"
            alt=""
          />
        </div>
        <div class="dialog-text">
          <div class="air-body-item-num">
            <!-- <div class="air-temp-num">{{ temperature }}</div> -->
            <!-- <div
              class="air-temp-num"
              :class="{
                'arrow-cooling': airSetText.toWhere == 'toCold',
                'arrow-warn': airSetText.toWhere == 'toWarm',
              }"
            >
              →
            </div> -->
            <div v-if="airSetText.notice" class="air-temp-num">
              {{ airSetText.notice }}
            </div>
            <div v-else class="air-temp-load">
              <van-loading type="spinner" />
            </div>
            <!-- <div v-else class="air-temp-num-load">
              <img
                style="padding-top: 4px; height: 20px; width: 20px"
                :src="parseImgUrl('page-officehome', 'loading.svg')"
              />
            </div> -->
          </div>
          <p
            v-if="airSetText.remark && airSetText.remark.length"
            class="air-notice"
          >
            <span
              v-for="(remarkItem, index) in airSetText.remark"
              :key="'remark' + index"
              >{{ remarkItem }}</span
            >
          </p>
        </div>
        <div class="dialog-btns" @click.stop="closeDialog">
          <span>确定</span>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  computed,
  watch,
  onUnmounted,
  onBeforeMount,
  onBeforeUnmount,
} from "vue";
import { Switch, Dialog, Loading, Toast } from "vant";
import {
  changeTempHttp,
  getEquipmentListHttp,
  getFeedbackDocumentsHttp,
} from "@/apis/envmonitor";
import { parseImgUrl } from "@/utils";
import any = jasmine.any;

export default defineComponent({
  props: {
    temperature: {
      // 空调基本信息
      type: Number,
      default: () => 0,
    },
    hasAir: {
      // 有无空调
      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,
    },
  },
  components: {
    Switch,
    [Dialog.Component.name]: Dialog.Component,
    Loading,
  },
  setup(props, contx) {
    const propsVal = props;
    let airData: any = {
      avg: "", // 算法调节温度（目标值）
      icon: 1, // 固定框文案ID 7 为关机，其它都是开机
      spaceStatus: "", // 固定框文案展示
      notice: "", // 弹框文案展示
      mode: 0, //  模式
      tempSet: 0, // 温度
      isOpen: false, // 空调开关 true 是开
    };
    const feedbackTimer: any = null;
    const airTimer: any = null;
    const domAirOpeen: any = false;
    const proxyData = reactive({
      loadingAir: false,
      temperature: props.temperature,
      userIsControl: props.userIsControl,
      forceOverTimeFlag: props.forceOverTimeFlag,
      firstLoadingAir: true,
      spaceId: props.spaceId,
      domAirOpeen: domAirOpeen,
      feedbackTimer: feedbackTimer,
      parseImgUrl: parseImgUrl,
      airData: airData,
      modeName: "",
      showAirVolumeBtn: false, // 是否展示风量调节按钮
      showDialog: false,
      airTimer: airTimer,
      airSetText: {
        // 空调反馈文案
        notice: "",
        remark: [],
        nowImg: "",
        toWhere: "",
        designTemperature: 0,
      },
      // 格式化模式
      formateModel(model: any) {
        if (model) {
          if (model === 1) {
            proxyData.modeName = "制冷";
          } else if (model === 2) {
            proxyData.modeName = "制热";
          } else if (model === 3) {
            proxyData.modeName = "通风";
          } else if (model === 4) {
            proxyData.modeName = "除湿";
          } else {
            proxyData.modeName = "";
          }
        } else {
          proxyData.modeName = "";
        }
      },
      // 获取设备类型(ACATVI)
      getEquipmentListHttp() {
        let params = {
          spaceId: proxyData.spaceId,
        };
        proxyData.showAirVolumeBtn = false;
        let flag: any = true;
        getEquipmentListHttp(params).then((res) => {
          let resData: any = res;
          let data: any = resData ? resData.data : [];
          if (data && data.length) {
            for (let i = 0; i < data.length; i++) {
              let item: any = data[i];
              if (item.equipmentCategory === "ACATVI") {
                // 多联机不展示风量调整
                proxyData.showAirVolumeBtn = false;
                flag = false;
                break;
              }
            }
            if (flag) {
              proxyData.showAirVolumeBtn = true;
            }
          }
        });
      },
      // 定时获取空调状态
      getAirInfoToTimer(timerLong: any = 3000) {
        if (proxyData.airTimer) {
          clearTimeout(proxyData.airTimer);
        }
        proxyData.airTimer = setTimeout(function () {
          proxyData.getAirInfo();
        }, timerLong);
      },
      // 定时调文案的接口
      getFeedbackTimer(btnType: any, id: any) {
        clearTimeout(proxyData.airTimer);
        proxyData.airTimer = null;
        proxyData.feedbackTimer = setTimeout(() => {
          proxyData.getAirInfo("feedback", btnType, id, false); // 调节反馈文案
        }, 3000);
      },
      // 关闭空调的按钮点击的loading状态
      closeLoading() {
        let num: any = 0;
        let interval: any = setInterval(() => {
          if (num > 15 || proxyData.domAirOpeen === proxyData.airData.isOpen) {
            proxyData.loadingAir = false;
            clearInterval(interval);
          }
          num++;
        }, 1000);
      },
      getAirInfo(
        type: string = "",
        btnType: string = "",
        feedbackId: any = "",
        isTimer: boolean = true
      ) {
        let paramObj: any = {
          projectId: propsVal.projectId, // 项目id
          objectId: proxyData.spaceId, // 空间id
        };

        if (type === "feedback") {
          paramObj.id = feedbackId;
        }
        console.log("paramObj===");
        getFeedbackDocumentsHttp(paramObj)
          .then((res) => {
            const resData: any = res;
            if (type !== "feedback") {
              if (resData) {
                proxyData.airData = resData;
                proxyData.formateModel(proxyData.airData.mode);
                contx.emit("updateAirTemp", proxyData.airData.tempSet);
                if (proxyData.airData.icon && proxyData.airData.icon === 7) {
                  proxyData.airData.isOpen = false;
                  proxyData.airData.airImg = parseImgUrl(
                    "page-officehome",
                    "air_close.png"
                  );
                } else {
                  if (proxyData.airData.icon && proxyData.airData.icon !== 6) {
                    proxyData.airData.isOpen = true;
                    proxyData.airData.airImg = parseImgUrl(
                      "page-officehome",
                      "openair.png"
                    );
                  }
                }
              }
            }
            //   弹窗
            if (type === "feedback") {
              if (resData.notice) {
                proxyData.airSetText.notice = resData.notice;
                if (resData.remark && resData.remark.length) {
                  proxyData.airSetText.remark = resData.remark.split("*");
                }
                if (proxyData.feedbackTimer) {
                  clearTimeout(proxyData.feedbackTimer); // 拿到反馈文案清除定时器
                  proxyData.getAirInfoToTimer();
                }
              } else {
                proxyData.getFeedbackTimer(btnType, feedbackId);
              }
            } else {
              proxyData.getAirInfoToTimer();
            }
            proxyData.firstLoadingAir = false;
          })
          .catch(() => {
            proxyData.getAirInfoToTimer();
            proxyData.firstLoadingAir = false;
            proxyData.airData.airImg = parseImgUrl(
              "page-officehome",
              "air_close.png"
            );
          });
      },
      airChange() {
        // 先不更新状态等确认框弹出后再更新状
        if (proxyData.userIsControl) {
          if (!proxyData.loadingAir) {
            proxyData.airComfir();
          } else {
            Toast("指令正在下发中，勿重复操作！");
          }
        } else {
          Toast("您没有当前空间的控制权限！");
        }
      },
      // 确认
      airComfir() {
        const message = proxyData.airData.isOpen
          ? "要关闭空调吗？"
          : "要开启空调吗？";
        const confirmBtnText = proxyData.airData.isOpen ? "关闭" : "开启";
        Dialog.confirm({
          cancelButtonText: "取消",
          confirmButtonText: confirmBtnText,
          confirmButtonColor: "$elActiveColor",
          message: message,
        })
          .then(() => {
            // 操作空调
            const domAirOpen = !proxyData.airData.isOpen;
            if (proxyData.forceOverTimeFlag && domAirOpen) {
              //需要强制加班
              contx.emit("triggerWork");
              return;
            }
            const itemId = domAirOpen ? 12 : 10; // 12 开启 10关闭
            proxyData.domAirOpeen = domAirOpen;
            let btnTypeDetail = "";
            if (itemId == 12) {
              btnTypeDetail = "openAir";
            } else {
              btnTypeDetail = "closeAir";
            }
            proxyData.loadingAir = true;
            proxyData.closeLoading();
            proxyData.changeAir(itemId, "sw", btnTypeDetail);
          })
          .catch(() => {
            // on cancel
          });
      },
      // 切换散会的时候手动关闭空调()
      closeScenarioAir() {
        proxyData.changeAir(10, "sw", "closeAir");
      },
      // 更新空调开关状态
      updatAirStatus(btnType: string) {
        // 开启空调后手动调一下状态更新接口
        if (btnType === "sw") {
          proxyData.getAirInfo("", "", "", false);
        }
      },
      // 更新
      updateAirText(btnType: string, val: any) {
        if (btnType !== "sw") {
          proxyData.airSetText.designTemperature = val.designTemperature; // 目标温度
          proxyData.airSetText.toWhere = val.toWhere;
          if (proxyData.airSetText.toWhere == "toCold") {
            proxyData.airSetText.nowImg = "dialog_cooling.svg";
          } else if (proxyData.airSetText.toWhere == "toWarm") {
            proxyData.airSetText.nowImg = "dialog_warmUp.svg";
          } else {
            proxyData.airSetText.nowImg = "icon_wind.svg";
          }
        }
      },
      // 展示空调反馈弹窗¬
      showAirConditioning(btnType: string, btnTypeDetail: string) {
        // 空调温度和风量调整的时候展示弹窗
        if (btnType !== "sw") {
          proxyData.showDialog = true;
          // 调整空调温度接口
          const defaultAirText: any = {
            toWhere: btnTypeDetail,
            designTemperature: 0,
          };
          proxyData.updateAirText(btnType, defaultAirText);
        }
      },
      // 关闭弹窗
      closeDialog() {
        if (proxyData.feedbackTimer) {
          clearInterval(proxyData.feedbackTimer); // 拿到反馈文案清除定时器
          proxyData.feedbackTimer = null;
        }
        proxyData.getAirInfoToTimer();
        proxyData.showDialog = false;
      },
      changeAir(itemId: number, btnType: string, btnTypeDetail: string) {
        /**
         * 缺少的逻辑：
         * 1.设备位置判断
         * 2.空调温度调整的反馈文案
         */
        // 温度切换的时候调整文案
        proxyData.airSetText.notice = "";
        proxyData.airSetText.remark = [];
        const paramObj = {
          projectId: propsVal.projectId, // 项目id
          objectId: proxyData.spaceId, // 空间id
          valueType: 1, // 固定为1
          itemId: itemId, //    12 开启 10关闭  4 调低温  2 调高温 5 调小风量 6 调大风量
        };
        // 空调温度和风量调整的时候展示弹窗
        proxyData.showAirConditioning(btnType, btnTypeDetail);
        changeTempHttp(paramObj)
          .then((res) => {
            let resData: any = res;
            // 开启和关闭空调之后手动
            // proxyData.updatAirStatus(btnType)
            // 调整温度和风量的时候修改文案
            let airText = {
              toWhere: btnTypeDetail,
              designTemperature: resData.designTemperature,
            };
            proxyData.updateAirText(btnType, airText);
            // 改变温度和风量的时候给弹窗设置文案
            if (btnType !== "sw") {
              // debugger
              if (resData.notice) {
                proxyData.airSetText.notice = resData.notice;
                if (resData.remark && resData.remark.length) {
                  proxyData.airSetText.remark = resData.remark.split("*");
                }
              } else {
                proxyData.getFeedbackTimer(btnType, resData.id);
              }
            }
          })
          .catch(() => {
            proxyData.loadingAir = false;
          });
      },
    });
    watch(
      [() => props, () => props.spaceId],
      (newProps: any, oldProps: any) => {
        if (newProps[1] && newProps[1] != oldProps[1]) {
          // 空间id改变的重新获取值调用接口
          // 定时调空间信息
          proxyData.spaceId = newProps[1];
          // proxyData.getAirInfoToTimer(0);
          proxyData.getAirInfo()
          // proxyData.getEquipmentListHttp();
        }
        if (newProps[0]) {
          proxyData.temperature = newProps[0].temperature;
          proxyData.userIsControl = newProps[0].userIsControl;
          proxyData.forceOverTimeFlag = newProps[0].forceOverTimeFlag;
        }
      },
      {
        deep: false,
        immediate: true,
      }
    );
    onBeforeUnmount(() => {
      if (proxyData.airTimer) {
        clearTimeout(proxyData.airTimer);
        proxyData.airTimer = null;
      }
      if (proxyData.feedbackTimer) {
        clearTimeout(proxyData.feedbackTimer);
        proxyData.feedbackTimer = null;
      }
    });
    onMounted(() => {
      // 获取空调信息
      proxyData.firstLoadingAir = true;
      proxyData.getAirInfo();
      proxyData.getEquipmentListHttp();
    });
    const airRunImg = computed(() => {
      let imgStr: string = "";
      switch (proxyData.airData.icon) {
        case 1:
          imgStr = parseImgUrl("page-officehome", "temp-keep.png");
          break;
        case 2:
          imgStr = parseImgUrl("page-officehome", "temp_cold.svg");
          break;
        case 3:
          imgStr = parseImgUrl("page-officehome", "temp_sun.png");
          break;
        default:
          imgStr = "";
          break;
      }
      return imgStr;
    });
    return {
      airRunImg,
      ...toRefs(proxyData),
    };
  },
});
</script>
<style lang="scss" scoped>
.air {
  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;
}

.air-top {
  padding-left: 20px;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.air-desc {
  flex: 1 157px;
  padding-top: 10px;
  font-family: PingFang SC;
  font-size: 16px;
  line-height: 19px;
  color: #4d5262;
  flex: none;
  order: 0;
  //color: rgba(196, 196, 196, 0.2)
  flex-grow: 0;
  margin: 5px 0px;
}

.air-right {
  position: relative;
  width: 157px;
  text-align: center;

  img {
    width: 147px;
    height: 110px;
  }

  .switch-btn {
    position: absolute;
    z-index: 111;
    bottom: 10px;
    right: 25px;
  }
}

.air-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;
}

.air-temperature {
  display: inline-block;
  font-family: "Montserrat";
  font-style: normal;
  font-weight: normal;
  font-size: 32px;
  line-height: 32px;
  flex: none;
  order: 0;
  flex-grow: 0;
  margin: 0px 4px;

  sup {
    font-family: Mulish;
    font-style: normal;
    font-weight: 800;
    font-size: 12px;
    line-height: 15px;
  }
}

.air-model {
  padding-left: 5px;
  display: inline-block;
  font-family: "Montserrat";
  font-style: normal;
  font-weight: 400;
  font-size: 15px;
  line-height: 18px;
  color: #c4c4c4;

  span {
    padding-right: 2px;
  }
}

.air-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;
}

.air-loading {
  font-family: Roboto;
  padding-left: 5px;
  font-style: normal;
  font-weight: normal;
  font-size: 11px;
  //line-height: 13px;
  color: #c4c4c4;

  img {
    width: 12px;
    height: 12px;
    vertical-align: middle;
  }

  span {
    vertical-align: middle;
  }
}

.air-control {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  padding-left: 28px;
  padding-right: 15px;
  border-top: 1px solid rgba(196, 196, 196, 0.4);

  .control-title {
    flex: 1;
    line-height: 42px;
    font-weight: 500;
    font-size: 12px;
    color: #c4c4c4;
  }

  .btn-box {
    flex: 1;
    text-align: right;
  }

  .control-btn {
    display: inline-block;
    vertical-align: middle;
    width: 42px;
    height: 42px;
    text-align: center;
    border-radius: 50%;
    background: rgba(196, 196, 196, 0.2);

    img {
      width: 13px;
      height: 17px;
      margin: 0 auto;
      margin-top: 12.5px;
    }

    .temp-img {
      width: 20px;
      height: 20px;
    }
  }
}

.dialog-width {
  width: 280px !important;
}

.air-dialog-content {
  position: relative;
  width: 100%;
  height: 340px;

  .dialog-top {
    position: relative;
    height: 70px;
    background: #f3f3f3;

    .img-greey {
      background: #c4c4c4;
    }

    .img-blue {
      background: $elActiveColor;
    }

    .img-red {
      background: #e5574f;
    }

    img {
      box-sizing: border-box;
      border-radius: 50%;
      position: absolute;
      left: 50%;
      width: 70px;
      height: 70px;
      padding: 17px;
      transform: translateX(-50%);
      top: 15px;
    }
  }
}

.dialog-text {
  padding-top: 52px;
  text-align: center;

  .air-temp-num {
    font-family: Montserrat;
    display: inline-block;
    font-size: 24px;
    font-weight: 400;
    line-height: 29px;
    color: rgba(20, 0, 80, 1);

    &.arrow-cooling {
      color: $elActiveColor;
      margin: 0 30px;
      margin-bottom: 70px;
    }

    &.arrow-warn {
      color: rgba(229, 87, 79, 1);
      margin: 0 30px;
      margin-bottom: 70px;
    }
  }

  .air-temp-num-load {
    display: inline-block;
  }

  .air-notice {
    padding-top: 10px;
    padding-left: 48px;
    padding-right: 48px;
    text-align: center;
    // display: flex;
    justify-content: center;
    font-family: PingFang SC;
    font-size: 15px;
    font-weight: 400;
    line-height: 21px;
    color: rgba(77, 82, 98, 1);
    span {
      display: block;
      padding-bottom: 5px;
    }
  }

  .air-temp-load {
    padding-top: 25px;
  }

  .air-body-item-num {
    height: 50px;
  }
}

.dialog-btns {
  position: absolute;
  left: 50%;
  bottom: 30px;
  transform: translateX(-50%);
  text-align: center;
  margin: 0 auto;
  width: 88px;
  height: 46px;
  line-height: 1;
  color: #4d5262;
  background: #ffffff;
  border: 1px solid #c4c4c4;
  border-radius: 30px;
  cursor: pointer;

  span {
    height: 46px;
    line-height: 46px;
    display: inline-block;
  }
}
</style>
<style lang="scss">
.air-dialog-content {
  .van-button_text {
    color: $elActiveColor;
  }
}

.air {
  .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>
