<style type="less">
.title-block {
  margin: 0 64rpx 0 64rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-top: 24rpx;
  padding-bottom: 20rpx;
  align-items: center;
}

.title-block .title-text {
  font-weight: 600;
  font-size: 40rpx;
  line-height: 48rpx;
  color: rgba(13, 13, 61, 0.86);
}

.briefly-info {
  text-align: right;
}

.briefly-info image {
  width: 32rpx;
  height: 32rpx;
  float: left;
  margin-right: 10rpx;
}

.briefly-info .value {
  line-height: 32rpx;
  font-weight: bold;
  font-size: 32rpx;
  color: rgba(13, 13, 61, 0.86);
  margin-bottom: 8rpx;
}

.briefly-info .temperature {
  font-weight: bold;
  font-size: 32rpx;
  line-height: 32rpx;
  color: rgba(13, 13, 61, 0.86);
  margin-bottom: 8rpx;
}

.briefly-info .text {
  font-size: 24rpx;
  line-height: 32rpx;
  text-align: right;
  color: rgba(9, 9, 61, 0.45);
}

.control-area {
  /* margin-top: 48rpx; */
}

.control-area .top {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 136rpx;
  margin: 0 32rpx 32rpx 32rpx;
  border-radius: 24rpx;
}

.control-area .top.downing {
  background: linear-gradient(
    90deg,
    rgba(50, 132, 255, 0.08) 0%,
    rgba(255, 255, 255, 0) 25.85%
  );
}

.control-area .top.uping {
  background: linear-gradient(
    90deg,
    rgba(255, 136, 76, 0.08) 0%,
    rgba(255, 255, 255, 0) 25.85%
  );
}

.control-area .control-switch {
  margin-top: 16rpx;
}

.title-right {
  position: absolute;
  top: 144rpx;
  right: 48rpx;
}

.control-area .main {
  padding: 0 46rpx;
}

.main.environment {
  margin-bottom: 6rpx;
}

.control-area .top .temperture-info {
  margin-left: 32rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: left;
}

.top .temperture-info .temperture .text {
  display: inline-block;
  font-weight: bold;
  font-size: 48rpx;
  line-height: 48rpx;
  color: rgba(13, 13, 61, 0.86);
}

.top .temperture-info .temperture .unit {
  display: inline-block;
  font-weight: bold;
  font-size: 28rpx;
  line-height: 28rpx;
  color: rgba(13, 13, 61, 0.86);
  margin-left: 4rpx;
  vertical-align: super;
}

.top .temperture-info .sub-text {
  font-size: 24rpx;
  line-height: 24rpx;
  text-align: left;
  color: rgba(11, 11, 61, 0.64);
  margin-top: 8rpx;
  vertical-align: super;
}

.control-temperture-area {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.control-temperture-area .item {
  width: 316rpx;
  height: 224rpx;
  border-radius: 12px;
  font-size: 24rpx;
  line-height: 40rpx;
}

.control-temperture-area .item:active {
  transform: scale(0.95);
  transition: transform 0.3s;
}

.control-temperture-area .item .icon {
  width: 42rpx;
  height: 48rpx;
  margin: 64rpx auto 32rpx auto;
  display: block;
}

.control-temperture-area .item.fall {
  background: rgba(77, 148, 255, 0.12);
  color: #4d94ff;
  border-bottom: 4rpx solid rgba(77, 148, 255, 0.49);
}

.control-temperture-area .item.up {
  background: rgba(255, 136, 77, 0.14);
  color: #ff884d;
  border-bottom: 4rpx solid rgba(255, 136, 77, 0.44);
}

.control-btns-area {
  margin: 44rpx 0 82rpx;
  text-align: left;
  height: 146rpx;
  width: 100%;
  white-space: nowrap;
  display: flex;
  flex-direction: row;
  align-content: center;
}

.control-btns-area .btn {
  width: 146rpx;
  height: 146rpx;
  background: #ffffff;
  border-radius: 24rpx;
  margin-right: 24rpx;
  padding-top: 24rpx;
  position: relative;
  box-sizing: border-box;
}

.control-btns-area .btn.uncontrol {
  border: 2px dashed rgba(2, 2, 82, 0.12);
  color: #bcbccf;
  box-sizing: border-box;
  background: transparent;
}

.control-btns-area .btn.uncontrol .text {
  color: #bcbccf;
}

.control-btns-area .btn:active {
  opacity: 0.6;
}
.btn .timestamp {
  font-weight: bold;
  font-size: 52rpx;
  line-height: 52rpx;
  text-align: center;
  color: rgba(13, 13, 61, 0.86);
  margin-top: 8rpx;
  margin-bottom: 16rpx;
}

.btn .tip {
  font-size: 24rpx;
  line-height: 34rpx;
  text-align: center;
  color: rgba(13, 13, 61, 0.86);
}

.control-btns-area .btn:last-child {
  margin-right: 0;
}

.control-btns-area .btn.closed {
  background: rgba(0, 0, 0, 0.03);
}

.control-btns-area .btn.closed .text {
  color: rgba(9, 9, 61, 0.45);
}

.control-btns-area .btn .icon {
  width: 100rpx;
  height: 100rpx;
  display: block;
  margin: 0 auto;
}

.control-btns-area .btn .text {
  font-size: 24rpx;
  line-height: 34rpx;
  text-align: center;
  color: rgba(13, 13, 61, 0.86);
  position: absolute;
  bottom: 16rpx;
  left: 0;
  right: 0;
}

.environment-item {
  float: left;
  width: 315rpx;
  height: 224rpx;
  padding: 16px 0 0 16px;
  position: relative;
  background: #ffffff;
  border-radius: 24rpx;
  margin-right: 24rpx;
  margin-bottom: 24rpx;
  text-align: left;
  box-sizing: border-box;
}

.environment-item:nth-child(even) {
  margin-right: 0;
}

.environment-item .title {
  font-weight: bold;
  font-size: 12px;
  line-height: 12px;
  color: rgba(9, 9, 61, 0.45);
  margin-bottom: 36rpx;
}

.environment-item .icon {
  width: 48rpx;
  height: 48rpx;
  position: absolute;
  top: 24rpx;
  right: 24rpx;
}

.environment-item .value {
  font-weight: bold;
  font-size: 48rpx;
  line-height: 64rpx;
  color: rgba(13, 13, 61, 0.86);
  margin-bottom: 12rpx;
}

.environment-item .des {
  font-size: 24rpx;
  line-height: 24rpx;
  color: rgba(9, 9, 61, 0.45);
  height: 24rpx;
}

@keyframes slideDown {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(100%);
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.test {
  width: 100%;
  height: 80px;
  position: absolute;
  bottom: 0;
  background: red;
}
</style>
<template>
  <slider-panel-v2
    foldStatus="{{foldStatus}}"
    expandPanelHeight="{{expandPanelHeight}}"
    foldPanelHeight="{{foldPanelHeight}}"
    @component-slider-panel-v2-fold="foldPanel"
    @component-slider-panel-v2-expand="expandPanel"
    :isInCustomTopbar="false"
    :canSlide="canSlide"
    hasTopBar="{{true}}"
  >
    <view class="title-block">
      <view class="title-text">{{title||''}}</view>
      <block v-if="foldStatus==='fold'">
        <view v-if="selectedControlOption==='equipment'" class="briefly-info">
          <view class="temperature">{{temperature}}℃</view>
          <view class="text">{{airConditionStatusText}}</view>
        </view>
        <view v-if="selectedControlOption==='environment'" class="briefly-info">
          <view class="value">
            <image mode="scaleToFill" src="/static/page-intelligent-control/icon_formaldehyde.png" />
            {{hcho.value}}
          </view>
          <view class="text">{{hcho.text}}</view>
        </view>
      </block>
      <block v-else>
        <select-switch
          class="control-switch"
          options="{{controlOptions}}"
          selected="{{selectedControlOption}}"
          @component-select-switch-change="changeControlOption"
        ></select-switch>
      </block>
    </view>
    <view class="title-right" v-if="foldStatus!=='fold'&&selectedControlOption==='equipment'">
      <work-overtime v-if="spaceId" spaceId="{{spaceId}}"></work-overtime>
    </view>

    <view class="control-area" wx:if="{{foldStatus==='expand'}}">
      <view
        class="{{(('top') + ' ' +((airConditionStatus == 2 || airConditionStatus==4) ? 'downing' : ((airConditionStatus==3|| airConditionStatus==5) ? 'uping': '')))}}"
      >
        <view class="temperture-info">
          <view class="temperture">
            <view class="text">{{temperature}}</view>
            <view class="unit">℃</view>
          </view>
          <view class="sub-text">{{airConditionStatusText}}</view>
        </view>
      </view>
      <view class="main equipment" wx:if="{{selectedControlOption==='equipment'}}">
        <temperture-control-panel
          type="{{temperturePanelType}}"
          show="{{showTemperturePanel}}"
          @component-temperture-control-end="hideTemperturePanelFun($event)"
        >
          <view class="control-temperture-area">
            <view class="item fall" v-on:longpress="showFallPanel" data-source="btn">
              <image
                class="icon"
                mode="aspectFit"
                src="{{h5StaticPath + 'icon_cold.png'}}"
                data-source="btn-image"
              />
              <view class="text" data-source="btn-text">按住下滑降温</view>
            </view>
            <view class="item up" v-on:longpress="showUpPanel" data-source="btn2">
              <image
                class="icon"
                mode="aspectFit"
                src="{{h5StaticPath+'icon_warm.png'}}"
                data-source="btn2-image"
              />
              <view class="text" data-source="btn2-text">按住上滑升温</view>
            </view>
          </view>
        </temperture-control-panel>
        <scroll-view
          class="control-btns-area"
          scroll-x="{{true}}"
          scroll-y="{{false}}"
          enable-flex="true"
        >
          <block wx:if="{{!lightControl}}">
            <view class="btn uncontrol" bindtap="clickUncontrolLight">
              <image mode="aspectFit" class="icon" src="{{h5StaticPath+ 'icon_uncontrol.svg'}}" />
              <view class="text">暂不支持</view>
            </view>
          </block>
          <block wx:else>
            <view
              v-for="(item, idx) in lights"
              class="btn {{ [ item.opened ? '' : 'closed' ] }}"
              bindtap="changeTopLightStatus"
              data-light="{{item}}"
            >
              <image
                mode="aspectFit"
                class="icon"
                src="{{item.opened === true ?(h5StaticPath+'icon_toplight.png'):(h5StaticPath +'icon_toplight_disabled.png')}}"
              />
              <view class="text">{{item.lampType}}</view>
            </view>
          </block>
          <view
            class="btn aircondition {{ airConditioningSwitchStatus }}"
            bindtap="changeAircondition"
          >
            <block
              wx:if="{{airConditioningSwitchStatus=='open' || airConditioningSwitchStatus=='closed'}}"
            >
              <image
                mode="aspectFit"
                class="icon"
                src="{{airConditioningSwitchStatus=='open'?h5StaticPath+'icon_airconditioning.png': h5StaticPath+'icon_airconditioning_disabled.png' }}"
              />
              <view class="text">空调</view>
            </block>
            <block
              wx:if="{{airConditioningSwitchStatus == 'closedOperating' || airConditioningSwitchStatus == 'openOperating' }}"
            >
              <view class="timestamp">{{countdownText}}</view>
              <view class="tip">
                <block wx:if="{{airConditioningSwitchStatus== 'closedOperating'}}">即将关闭..</block>
                <block wx:if="{{airConditioningSwitchStatus== 'openOperating'}}">即将开启..</block>
              </view>
            </block>
          </view>
          <view
            class="btn"
            wx:if="{{airConditioningSwitchStatus=='open' || airConditioningSwitchStatus=='closedOperating'}}"
            bindtap="changeWindspeed"
          >
            <block wx:if="{{windspeedStatus=='init'}}">
              <image class="icon" mode="aspectFit" src="{{h5StaticPath+'icon_windspeed.png'}}" />
              <view class="text">调小风速</view>
            </block>
            <block wx:if="{{windspeedStatus=='minimizing'}}">
              <view class="timestamp">{{windCountdownText}}</view>
              <view class="tip">即将调小..</view>
            </block>
            <block wx:if="{{windspeedStatus=='minied'}}">
              <image class="icon" mode="aspectFit" src="{{h5StaticPath+'icon_windspeed.png'}}" />
              <view class="text">继续调小</view>
            </block>
          </view>
        </scroll-view>
      </view>
      <view class="main environment" wx:if="{{selectedControlOption==='environment'}}">
        <block v-for="(item, index) in environmentItems">
          <view class="environment-item">
            <view class="title">{{item.title}}</view>
            <image mode="scaleToFill" class="icon" src="{{item.iconUrl}}" />
            <view class="value">{{item.value}}</view>
            <view class="des">{{item.des}}</view>
          </view>
        </block>
      </view>
    </view>
  </slider-panel-v2>
</template>
<script>
import wepy from '@wepy/core';
import { checkLogin } from '@/service/user';
import { isWithinLocation } from '@/service/location';

import {
  getSpaceLightsHttp,
  setSpaceLightHttp,
  getEnvironmentInfoHttp,
  getAirConditionStatusHttp,
  changeAirconditionHttp,
  checkChangeLightStatusSuccessHttp
} from '@/packagesEnv/api/intelligentControl';
import utils from '@/common/utils';

const panel = wx.createSelectorQuery().select('.panel-intelligent-control');
let lightsStatusTimer;
let oldAirconditinStatus;
let airconditionCoutdownTimer;
let changeAirconditionTimer;
let windspeedTimer;
let changewindspeedTimer;
let setWeedInitTimer;

let airConditionStatusTimer;
let startCheckLightsTime = 0;
let envInfoTimer;

// 注意单位都是rpx
// 伸展状态下的面板高度
const expandPanelHeight = 407 * 2;
// 收缩状态下的面板高度
const foldPanelHeight = 96 * 2;

import config from '@/config';

let h5StaticPath = config.h5StaticPath + '/page-intelligent-control/';
let defaultEnvIitems = [
  {
    title: 'PM 2.5',
    iconUrl: h5StaticPath + 'icon_pm.png',
    value: '',
    des: '',
    id: 'pm25'
  },
  {
    title: 'CO₂',
    iconUrl: h5StaticPath + 'icon_co.png',
    value: '',
    des: '',
    id: 'co2'
  },
  {
    title: '甲醛',
    iconUrl: h5StaticPath + 'icon_formaldehyde.png',
    value: '',
    des: '',
    id: 'hcho'
  },
  {
    title: '湿度',
    iconUrl: h5StaticPath + 'icon_humidity.png',
    value: '',
    des: '',
    id: 'humidity'
  }
];
wepy.component({
  data: {
    h5StaticPath: h5StaticPath,
    showTemperturePanel: false,
    temperturePanelType: 'down',
    temperature: 26.2,
    hcho: {
      value: 0,
      text: '符合国标'
    },
    lights: [],
    controlOptions: [
      {
        text: '设备',
        value: 'equipment'
      },
      {
        text: '环境',
        value: 'environment'
      }
    ],
    selectedControlOption: 'equipment',
    toplightOpened: true,
    spotlightOpened: true,
    airConditionStatus: 1, //空调默认状态，为开启
    airConditionStatusText: '',
    airConditioningSwitchStatus: 'closed', //open-开启 openOperating-打开中 closedOperating-关闭中 closed-关闭
    windspeedStatus: 'init', //init-初始状态 minimizing-调小中 minied-继续调小
    environmentItems: [...defaultEnvIitems],
    countdownText: 3,
    windCountdownText: 3,
    expandPanelHeight: expandPanelHeight,
    foldPanelHeight: foldPanelHeight
  },
  props: {
    pageHide: Boolean,
    title: '',
    spaceId: '',
    lightControl: Boolean,
    foldStatus: {
      type: String,
      default: 'fold'
    },
    tempertureStatus: {
      status: '',
      level: 0
    },
    canSlide: {
      type: Boolean,
      default: true
    },
    companyId: String
  },
  watch: {
    spaceId: function(newSpaceId, oldSpaceId) {
      if (oldSpaceId !== newSpaceId) {
        this.reset();
        this.getPanelInfo();
      }
    },
    pageHide: function(newValue, oldValue) {
      if (oldValue !== newValue) {
        if (newValue == true) {
          this.reset();
        } else if (oldValue == true && newValue == false) {
          this.getPanelInfo();
        }
      }
    }
  },
  detached: function() {
    // 在组件实例被从页面节点树移除时执行
    this.reset();
  },
  methods: {
    vibrateShort() {
      if (wx.canIUse('vibrateShort')) {
        wx.vibrateShort();
      }
    },
    changeControlOption(value) {
      this.selectedControlOption = value;
    },
    changeTopLightStatus(event) {
      isWithinLocation().then(() => {
        const light = event.currentTarget.dataset.light;
        let { lights } = this;

        lightsStatusTimer = clearInterval(lightsStatusTimer); //先关闭轮询，然后再重启
        this.vibrateShort();
        wx.showLoading({
          title: '加载中...',
          mask: true
        });
        //查询等状态
        getSpaceLightsHttp(this.spaceId, this.companyId)
          .then(
            res => {
              const result = JSON.parse(res.data);
              const data = (result && result.content) || [];
              let lights = this.convertLightStatus(data);

              let currentLights = lights.filter(item => item.id == light.id)[0];
              if (currentLights && currentLights.opened == light.opened) {
                return setSpaceLightHttp(light.id, !light.opened, this.companyId);
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '已' + (!light.opened ? '开' : '关') + '灯',
                  duration: 2000
                });
                this.setLightStatus(light.id);
                return Promise.reject();
              }
            },
            res => {
              wx.hideLoading();
              // 不是网络错误的情况下继续刷
              if (res && res.reason != 'wxRequestFail') {
                this.startLightsStatusTimer();
              }
              return Promise.reject(res);
            }
          )
          .then(
            res => {
              // 当网络异常的时候，没有数据返回，也不进行之后的操作
              if (res) {
                return this.judgeChangeResponeseSuccess(res);
              }
            },
            res => {
              wx.hideLoading();
              if (res && res.reason != 'wxRequestFail') {
                this.startLightsStatusTimer();
              }
              return Promise.reject(res);
            }
          )
          .then(
            res => {
              if (!(res && res.status)) {
                wx.hideLoading();
                return;
              }
              switch (res.status) {
                case 'success':
                  // 去更改灯的状态
                  wx.hideLoading();
                  this.setLightStatus(light.id);
                  this.startLightsStatusTimer();
                  break;
                case 'processing':
                  // 继续查询
                  startCheckLightsTime = new Date().getTime();
                  return this.checkChangeLightStatusSuccess(
                    light.id,
                    !light.opened,
                    res.data.orderSeqNum
                  );
                  break;
                default:
                  wx.hideLoading();
              }
            },
            (res) => {
              wx.hideLoading();
              wx.showToast({
                title: '操作失败，请重试',
                icon: 'none'
              });
              // 不是网络错误的情况下继续刷
              if (res && res.reason != 'wxRequestFail') {
                this.startLightsStatusTimer();
              }
            }
          );
      });
    },
    judgeChangeResponeseSuccess(res) {
      return new Promise((resolve, reject) => {
        let response = JSON.parse(res.data);
        let result = response.content[0];

        if (result.result == 'success') {
          if (result.state == 200 && result.exeResult == 'success') {
            resolve({ status: 'success', data: result });
          } else if (
            (result.state == 200 && result.exeResult == 'processing:rcvd') ||
            (result.state == 202 && !result.exeResult)
          ) {
            //查询数据
            resolve({ status: 'processing', data: result });
          } else {
            reject();
          }
        } else {
          reject();
        }
      });
    },
    checkChangeLightStatusSuccess(lightId, status, orderSeqNum) {
      // 判断是否已到五秒，到达5s则不去处理了
      let now = new Date().getTime();
      if (now - startCheckLightsTime >= 5 * 1000) {
        wx.hideLoading();
        setTimeout(() => {
          wx.showToast({
            title: '网络故障，请重试',
            icon: 'none',
            duration: 2000
          });
        }, 200);
      } else {
        checkChangeLightStatusSuccessHttp({
          lightId: lightId,
          lightSwitch: status,
          orderSeqNum
        })
          .then(res => {
            return this.judgeChangeResponeseSuccess(res);
          })
          .then(
            res => {
              switch (res.status) {
                case 'success':
                  // 去更改灯的状态
                  wx.hideLoading();
                  this.setLightStatus(lightId);
                  break;
                case 'processing':
                  // 继续查询
                  let result = res.data;
                  this.checkChangeLightStatusSuccess(
                    lightId,
                    status,
                    result.orderSeqNum
                  );
                  break;
              }
            },
            () => {
              wx.hideLoading();
              setTimeout(() => {
                wx.showToast({
                  title: '操作失败，请重试',
                  icon: 'fail',
                  duration: 2000
                });
              }, 0);
            }
          );
      }
    },
    setLightStatus(lightId) {
      let { lights } = this;
      lights.find(item => {
        if (item.id == lightId) {
          item.opened = !item.opened;
        }
      });
      this.lights = [...lights];
    },
    changeSpotLightStatus() {
      this.spotlightOpened = !this.spotlightOpened;
    },
    changeAircondition() {
      isWithinLocation().then(() => {
        this.vibrateShort();
        airConditionStatusTimer = clearInterval(airConditionStatusTimer);
        let airConditioningSwitchStatus = this.airConditioningSwitchStatus;
        if (airConditioningSwitchStatus == 'open') {
          this.setAirconditionOperting('open', 'closed');
        } else if (airConditioningSwitchStatus.indexOf('Operating') !== -1) {
          this.airConditioningSwitchStatus = oldAirconditinStatus;
          this.clearAirconditionCutdownTimer();
          this.startAirConditionStatusTimer();
        } else if (airConditioningSwitchStatus == 'closed') {
          this.setAirconditionOperting('closed', 'open');
        }
      });
    },
    clearAirconditionCutdownTimer() {
      this.countdownText = 3;
      airconditionCoutdownTimer = clearInterval(airconditionCoutdownTimer);
      changeAirconditionTimer = clearTimeout(changeAirconditionTimer);
    },
    setAirconditionOperting(oldStatus, newStatus) {
      this.clearAirconditionCutdownTimer();
      oldAirconditinStatus = oldStatus;
      this.airConditioningSwitchStatus = newStatus + 'Operating';
      // 开启倒计时
      airconditionCoutdownTimer = setInterval(() => {
        if (this.countdownText > 1) {
          this.countdownText = --this.countdownText;
        }
      }, 1000);

      //开启3s后自动调节成功
      changeAirconditionTimer = setTimeout(() => {
        this.doChangeAircondition(newStatus);
      }, 3000);
    },
    doChangeAircondition(newStatus) {
      let httStatus = newStatus == 'closed' ? 10 : 12; //  10 是关闭，12是开启
      wx.showLoading({
        title: '加载中...', //提示的内容,
        mask: true //显示透明蒙层，防止触摸穿透
      });

      this.clearAirconditionCutdownTimer();
      changeAirconditionHttp(this.spaceId, httStatus, this.companyId).then(
        () => {
          this.getAirConditionStatus().then(
            afterChangeStatus => {
              wx.hideLoading();
              this.setAirconditionDatavalue(afterChangeStatus);
              this.startAirConditionStatusTimer();
            },
            () => {
              wx.hideLoading();
            }
          );
        },
        () => {
          wx.hideLoading();
          //失败需要回退
          this.startAirConditionStatusTimer();
          this.setAirconditionDatavalue(oldAirconditinStatus);
        }
      );
      this.countdownText = 3;
      //如果关闭，同时关闭调小风速倒计是
      if (newStatus == 'closed') {
        this.cancelWindSpeedMinimzing();
      }
    },
    setAirconditionDatavalue(switcStatus) {
      let showStatus = switcStatus == 'closed' ? 0 : 1;
      this.airConditionStatus = showStatus;
      this.airConditionStatusText = this.getAirConditionStatusText(showStatus); //设置提示文案
      this.airConditioningSwitchStatus = switcStatus;
    },
    changeWindspeed() {
      isWithinLocation().then(() => {
        this.vibrateShort();
        let windspeedStatus = this.windspeedStatus;
        if (windspeedStatus === 'init') {
          this.setWindSpeedMinimzing();
        } else if (windspeedStatus === 'minimizing') {
          this.cancelWindSpeedMinimzing();
        } else if (windspeedStatus === 'minied') {
          clearTimeout(setWeedInitTimer);
          this.setWindSpeedMinimzing();
        }
      });
    },
    setWindSpeedMinimzing() {
      this.windspeedStatus = 'minimizing';
      this.openWindCountdown();
      this.setWindMinied();
    },
    cancelWindSpeedMinimzing() {
      setWeedInitTimer = clearTimeout(setWeedInitTimer);
      windspeedTimer = clearInterval(windspeedTimer);
      changewindspeedTimer = clearInterval(changewindspeedTimer);
      this.windspeedStatus = 'init';
      this.windCountdownText = 3;
    },
    openWindCountdown() {
      windspeedTimer = setInterval(() => {
        if (this.windCountdownText > 1) {
          this.windCountdownText = --this.windCountdownText;
        }
      }, 1000);
    },
    setWindMinied() {
      //开启3s后自动调节成功
      changewindspeedTimer = setTimeout(() => {
        windspeedTimer = clearInterval(windspeedTimer);
        this.changeWindspeedHttp().then(() => {
          //开启15s后回复初始状态
          setWeedInitTimer = setTimeout(() => {
            this.windspeedStatus = 'init';
          }, 15000);
        });
      }, 3000);
    },
    changeWindspeedHttp() {
      wx.showLoading({
        title: '加载中...', //提示的内容,
        mask: true //显示透明蒙层，防止触摸穿透
      });
     return changeAirconditionHttp(this.spaceId, 5, this.companyId).then(
        () => {
          this.windspeedStatus = 'minied';
          this.windCountdownText = 3;
          wx.hideLoading();

          //toast 提示调小成功
          wx.showToast({
            title: '已调小',
            duration: 1000,
            icon: 'none'
          });
        },
        () => {
          this.windspeedStatus = 'init';
          this.windCountdownText = 3;
          wx.hideLoading();
        }
      );
    },
    foldPanel() {
      this.$emit('component-control-panel-fold');
    },
    expandPanel() {
      this.$emit('component-control-panel-expand');
    },
    showFallPanel() {
      isWithinLocation().then(() => {
        this.temperturePanelType = 'down';
        this.showTemperturePanel = true;
      });
    },
    showUpPanel() {
      isWithinLocation().then(() => {
        this.temperturePanelType = 'up';
        this.showTemperturePanel = true;
      });
    },
    hideTemperturePanelFun(newTemperture) {
      this.showTemperturePanel = false;
      if (newTemperture.level == 0) {
        return;
      }
      this.changeAircondBySlide(newTemperture);
    },
    startAirConditionStatusTimer() {
      if (airConditionStatusTimer) {
        return;
      }
      airConditionStatusTimer = setInterval(() => {
        this.getAirConditionStatus();
      }, 1 * 1000); //10描刷接口
    },
    startLightsStatusTimer() {
      if (lightsStatusTimer) {
        return;
      }
      lightsStatusTimer = setInterval(() => {
        this.getLights();
      }, 1 * 1000); //10描刷接口
    },
    startEnvInfoTimer() {
      if (envInfoTimer) {
        return;
      }
      envInfoTimer = setInterval(() => {
        this.getEnvironmentInfo();
      }, 1 * 1000); //10描刷接口
    },
    cancelEnvInfoTimer() {
      envInfoTimer = clearInterval(envInfoTimer);
    },
    getPanelInfo() {
      this.getLights();
      this.getEnvironmentInfo();
      this.getAirConditionStatus();
      // this.startLightsStatusTimer();
      // this.startAirConditionStatusTimer();
      // this.startEnvInfoTimer();
    },
    getLights() {
      return getSpaceLightsHttp(this.spaceId, this.companyId).then(res => {
        const result = JSON.parse(res.data);
        const data = (result && result.content) || [];
        this.lights = this.convertLightStatus(data);
      });
    },
    convertLightStatus(data) {
      const lights = [];
      data.forEach(item => {
        lights.push({
          id: item.id,
          opened: item.runStatus >= 1 ? true : false,
          lampType: item.lampType
        });
      });
      return lights;
    },
    getEnvironmentInfo() {
      checkLogin()
        .then(() => {
          return getEnvironmentInfoHttp(this.spaceId, this.companyId);
        })
        .then(res => {
          const result = JSON.parse(res.data);
          const data = (result && result.content && result.content[0]) || {};

          let { environmentItems } = this;
          let hcho;
          environmentItems.forEach(item => {
            let id = item.id,
              des;
            item.value =
              utils.formateEnvIndicatorValue(id, data[id] || '') || '--';
            des = utils.getEnvIndectorDesc(id, item.value);
            item.des = des || '';
            if (id == 'hcho') {
              hcho = {
                value: item.value,
                text: des
              };
            }
          });
          this.environmentItems = environmentItems;
          this.hcho = hcho;
          this.temperature =
            data['temperature'] && data['temperature'].toString();
        });
    },
    getAirConditionStatus() {
      return checkLogin()
        .then(() => {
          return getAirConditionStatusHttp(this.spaceId, this.companyId);
        })
        .then(res => {
          const result = JSON.parse(res.data);
          const data = (result && result.content && result.content[0]) || {};
          let airConditionStatusText = this.getAirConditionStatusText(
            data.stateId
          );
          if (data) {
            this.airConditionStatus = data.stateId;
            this.airConditionStatusText = airConditionStatusText;
            this.airConditioningSwitchStatus =
              data.stateId == 0 ? 'closed' : 'open';
            this.temperature =
              data['temperature'] && data['temperature'].toString();
          }
          return this.airConditioningSwitchStatus || 'open';
        });
    },
    judgeNeedOpenAircond() {
      // 开启空调并发送
      if (this.airConditioningSwitchStatus === 'closed') {
        return changeAirconditionHttp(this.spaceId, 12, this.companyId).then(() => {
          this.airConditioningSwitchStatus = 'open';
        });
      } else {
        return Promise.resolve();
      }
    },
    changeAircondBySlide(temperature) {
      //先关闭空调轮询，再设置空调状态，当设置完成后再开启
      wx.showLoading({
        title: '加载中...', //提示的内容,
        mask: true //显示透明蒙层，防止触摸穿透
      });

      airConditionStatusTimer = clearInterval(airConditionStatusTimer);
      this.judgeNeedOpenAircond().then(
        () => {
          //根据手动操作的值，对应去先显示请求
          let airConditionStatus, airConditionStatusText;
          let httpSetStatus;

          if (temperature.type == 'down') {
            airConditionStatus = temperature.level == 1 ? 2 : 4;
            httpSetStatus = temperature.level == 1 ? 3 : 4;
          } else if (temperature.type == 'up') {
            airConditionStatus = temperature.level == 1 ? 3 : 5;
            httpSetStatus = temperature.level == 1 ? 1 : 2;
          }

          changeAirconditionHttp(this.spaceId, httpSetStatus, this.companyId)
            .then(
              () => {
                return this.getAirConditionStatus();
              },
              () => {
                wx.hideLoading();
              }
            )
            .then(
              res => {
                wx.hideLoading();
                this.startAirConditionStatusTimer();
              },
              () => {
                wx.hideLoading();
              }
            );
        },
        () => {
          wx.hideLoading();
        }
      );
    },
    reset() {
      // 重制正在开启空调，或者调下风速节面倒计时
      this.cancelWindSpeedMinimzing();
      this.clearAirconditionCutdownTimer();
      this.cancelEnvInfoTimer();
      // 定时刷新任务空调信息
      airConditionStatusTimer = clearInterval(airConditionStatusTimer);
      // 定时刷灯状态
      lightsStatusTimer = clearInterval(lightsStatusTimer);
      this.environmentItems = this.environmentItems.map(item => {
        return { ...item, value: '' };
      });
    },

    getAirConditionStatusText(status) {
      status = Number(status);

      let msg = '';
      switch (status) {
        case 0:
          msg = '空调未开启';
          break;
        case 1:
          msg = '恒温保持中';
          break;

        case 2:
          msg = '正在降温..';
          break;

        case 4:
          msg = '正在快速降温..';
          break;
        case 3:
          msg = '正在逐步升温..';
          break;
        case 5:
          msg = '正在快速升温..';
          break;
      }
      return msg;
    },
    clickUncontrolLight() {
      wx.showToast({
        title: '请使用墙上开关',
        duration: 2000,
        icon: 'none'
      });
    }
  }
});
</script>
<config>
{
    "usingComponents": {
        "select-switch": "~@/components/common/select-switch",
        "slider-panel-v2": "~@/components/common/slider-panel-v2",
         "temperture-control-panel": "../temperturecontrolpanel/temperturecontrolpanel",
         "work-overtime": "../workovertime/workovertime"
    },
    componentPlaceholder: {
    'select-switch': 'view',
    'slider-panel-v2': 'view'
  }
   
}
</config>
