<template>
    <div class="air-adjust office-card g-fl">
        <div class="air-content">
            <div class="air-adjust-env">
                <div>
                    <span class="envname">空调</span>
                    <div
                        class="envnum"
                        @tap.stop="showDetail('Tdb,RH')"
                    >{{temperature ? temperature :'--'}}<span>℃</span></div>
                </div>
                <div
                    class="air-status"
                    v-if="hasAir"
                >
                    <span>{{airData.isOpen ? '空调已开启' : '空调已关闭'}}</span>
                </div>
                <div
                    class="room-air-status"
                    v-if="airData.isOpen"
                >
                    <image
                        v-if="airData.icon==1 || airData.icon==2 || airData.icon==3"
                        class="room-air-img"
                        src="{{h5StaticPath + airRunImg}}"
                    />
                    <span class="air-common-text air-status-text">{{airData.spaceStatus}}</span>
                </div>
                <div
                    v-else
                    style="height:52rpx"
                >

                </div>
            </div>
            <div class="air-adjust-btn">
                <image
                    :src="h5StaticPath+airImg"
                    alt=""
                    lazyload
                />
            </div>
            <div class="air-switch">
                <switch
                    v-if="hasAir && !isACATVA"
                    :isACATFC="isACATFC"
                    :seasonType="seasonType"
                    :isHand="'auto'"
                    :showWorkTime="showWorkTime"
                    :checked="airData.isOpen"
                    :eqTitle="eqTitle"
                    @component-switch-change="airChange($event)"
                ></switch>
            </div>
        </div>
        <!-- 空调 调节 -->
        <div v-if="airData.isOpen">
            <div class="air-control-item">
                <div class="air-control-item-box">
                    <!-- <div
                        class="envnum-common"
                        :class="[airTemSt]"
                        v-show="glistenFlag"
                    >{{airData.designTemperature}}<span>℃</span></div> -->
                    <span class="air-common-text change-text">温度调节</span>
                </div>
                <div class="air-common-switch">
                    <div
                        class="switch"
                        :class="{'yell': suspendUpFlag} "
                        @click="changeAir(4, 'temp','toCold')"
                    >
                        <image src="{{h5StaticPath}}arrow_down_grey.png" />
                    </div>
                    <div
                        class="switch"
                        :class="{'yell': suspendUpFlag} "
                        @click=" changeAir(2, 'temp','toWarm')"
                    >
                        <image src="{{h5StaticPath}}arrow_up_grey.png" />
                    </div>
                </div>
            </div>
            <!--Pj1101050038  ACATVA没有风量调节 和开关按钮 -->
            <div
                class="air-control-item"
                v-if="!isACATVA"
            >
                <div class="air-control-item-box">
                    <!-- <div class="envnum-common air-envnum-comon">
                        <span
                            class="envnum-common-wind"
                            v-for="(item,index) in windGearArr"
                            :key="index"
                            :class="{'windBlack': item == windGear}"
                        >{{item}}</span>
                    </div> -->
                    <span class="air-common-text change-text">风量调节</span>
                </div>
                <div class="air-common-switch">
                    <div
                        class="switch"
                        :class="{'yell': suspendUpFlag} "
                        @click="changeAir(5,'wind','toWindLow')"
                    >
                        <image src="{{h5StaticPath}}wind_small.png" />
                    </div>
                    <div
                        class="switch"
                        :class="{'yell': suspendUpFlag} "
                        @click="changeAir(6,'wind','toWindUp')"
                    >
                        <image src="{{h5StaticPath}}wind_big.png" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import wepy from '@wepy/core'
import { changeTempHttp, getFeedbackDocumentsHttp, getTempRangeHttp, getSeasonType } from '@/packagesEnv/api/officehome.js'
import config from '@/config'
import { isWithinLocation } from '@/service/location'
import moment from 'moment'
import store from '@/store'
import { mapState } from '@wepy/x'
import { checkSpaceControl } from '@/packagesEnv/pages/common.js'

let infoTimer
let feedbackTimer

wepy.component({
  props: {
    isControl: Boolean, // 是否可控
    roomType: String, // 房间类型
        // hasBlowing: Boolean, // 有无变风量
    roomHasScene: Boolean, // 加班场景
    temperature: Number,
    objectId: String,
    hasAir: {
      type: Boolean,
      default: true
    }, // 有无空调
    projectId: String,
    isACATVA: Boolean,
    isACATFC: Boolean,
    airVolumes: Array, // 风量信息
    airVisible: Boolean
  },
  store,
  data: {
    showWorkTime: false, // 展示是否需要预约时间
    h5StaticPath: config.h5StaticPath + '/page-officehome/',
    visible: false,
    eqTitle: '空调',
    airImg: 'air_close.png',
    airTemSt: 'colorBlack',
    glistenFlag: true,
    windGear: 0, // 风量档位
    windGearArr: [1, 2, 3], // 风量3/5个档位
    airData: {
      avg: '--',                // 算法调节温度（目标值）
      icon: 1,                // 固定框文案ID 7 为关机，其它都是开机
      spaceStatus: '',    // 固定框文案展示
      notice: '',                // 弹框文案展示
      isOpen: false // 空调开关 true 是开
    },
    watchObjectIdEnd: false, // 监听空间ID
    tempMax: '--',
    tempMin: '--',
    seasonType: ''
  },
  watch: {
    airVisible(val) {
      if (!val) {
        console.log('---关闭定时器')
        clearInterval(feedbackTimer)
      }
    },
    hasAir(val) {
      if (!val) {
        clearInterval(infoTimer)
        this.airData.isOpen = false
        this.airImg = 'air_close.png'
      }
    },
    objectId(val) {
            //   this.glistenAirTemHttp();

      if (val) {
        clearInterval(infoTimer) // 定时器先清理 再设定
        infoTimer = setInterval(() => {
          this.getInfo()
        }, 1000)
      } else {
        this.airData.isOpen = false
        this.airImg = 'air_close.png'
      }
    }

  },
  computed: {
    ...mapState({isNowTime: state => state.officehome.isNowTime}),

    airRunImg() {
      let imgStr = ''
      switch (this.airData.icon) {
        case 1:
          imgStr = 'temp-keep.png'
          break
        case 2:
          imgStr = 'temp_cold.svg'
          break
        case 3:
          imgStr = 'temp_sun.png'
          break
        default:
          imgStr = ''
          break
      }
      return imgStr
    }
  },
  ready() {
    this.querySeasonType()
  },
  detached() {
    this.airData.isOpen = false
    this.airData.icon = 1

    clearInterval(feedbackTimer)
    clearInterval(infoTimer)
  },
  methods: {
    querySeasonType() {
      const params = {
        projectId: this.projectId,
        date: moment().format('YYYYMMDD') // 当天日期
      }
      if (!this.seasonType) {
        getSeasonType(params).then(res => {
          this.seasonType = res.data || ''
        }).catch(() => {
        })
      }
    },
    showDetail(funcid) {
      this.$emit('showDetail', { funcid: funcid })
      wx.uma.trackEvent('officeHome_changeAir_temperature', { key: 'roomTemperature' })
    },
    async getInfo() {
      await this.getAirInfo('info')
            //   this.judgeAirLevel();
            //   this.glistenAirTem();
    },

        // 空调信息airTemp
    getAirInfo(type, btnType, feedbackId) {
      const paramObj = {
        projectId: 'Pj1101080259', // 项目id
        objectId: this.objectId // 空间id
      }
      if (type === 'feedback') {
        paramObj.id = feedbackId
      }
      getFeedbackDocumentsHttp(paramObj).then(res => {
        if (type !== 'feedback') {
          res.isOpen = false
          this.airData = res
          this.airData.designTemperature = res.designTemperature ? res.designTemperature.toFixed(1) : '--'

          if (this.airData.icon === 7) {
            this.airData.isOpen = false
            this.airImg = 'air_close.png'
                        // 如果是过渡季 并且 是ATVA 空调 开启时则显示 过渡季节运行中...
          } else if (this.airData.icon != 6) {
            this.airData.isOpen = true
            this.airImg = 'openair.png'

            if (this.isACATVA && this.seasonType == 'Transition') {
              this.airData.spaceStatus = '过渡季节运行中...'
              this.airData.icon = 1
            }
          }
        }
                //   弹窗
        if (type === 'feedback' && res.notice && btnType != 'sw') {
          clearInterval(feedbackTimer) // 拿到反馈文案清除定时器
          this.$emit('airTemp', {notice: res.notice, remark: res.remark})
        }
      })
    },

        // 空调温度 闪烁
    glistenAirTemHttp() {
      getTempRangeHttp().then(res => {
        this.tempMax = res.tempMax
        this.tempMin = res.tempMin
      })
    },
        // glistenAirTem() {
        //   clearInterval(timer);
        //   if (this.airData.avg >= this.tempMax || this.airData.avg <= this.tempMin) {
        //     this.airData.avg >= this.tempMax ? (this.airTemSt = 'colorRed') : (this.airTemSt = 'colorBlue');
        //     const _this = this;
        //     timer = setInterval(() => {
        //       _this.glistenFlag = !_this.glistenFlag;
        //     }, 500);
        //   } else {
        //     this.glistenFlag = true;
        //     this.airTemSt = 'colorBlack';
        //   }
        // },

        // judgeAirLevel() {
        //         // - 空调风量判断 -
        //   let blowObj = this.airVolumes ? this.airVolumes[0] : {};
        //   let airLevel = 0;
        //   if (blowObj.data === undefined || blowObj.data === 0 || !this.airData.isOpen) {
        //     this.airLevel = 0;
        //     return;
        //   }
        //   this.windGearArr = [1, 2, 3];
        //   switch (blowObj.code) {
        //     case 'AirSpeedGear':
        //       this.windGearArr = [1, 2, 3, 4, 5]; // AirSpeedGear是五个挡位
        //       airLevel = blowObj.data;
        //       break;
        //     case 'FanGear':
        //       airLevel = blowObj.data;
        //       break;
        //     case 'SupplyAirFlow':
        //       let avg = (blowObj.maxAirFlow - blowObj.minAirFlow) / 3;
        //       if (blowObj.data > blowObj.minAirFlow && blowObj.data <= blowObj.minAirFlow + avg) {
        //         airLevel = 1;
        //       } else if (blowObj.data > blowObj.minAirFlow + avg && blowObj.data <= blowObj.minAirFlow + avg * 2) {
        //         airLevel = 2;
        //       } else {
        //         airLevel = 3;
        //       }
        //       break;

        //     default:
        //       break;
        //   }
        //   this.windGear = airLevel;
        // },

    vibrateLong() {
      if (wx.canIUse('vibrateLong')) {
        wx.vibrateLong()
      } else {
        wx.vibrateShort()
      }
    },
    vibrateShort() {
      if (wx.canIUse('vibrateShort')) {
        wx.vibrateShort()
      } else {
        wx.vibrateLong()
      }
    },

    airChange(value) {
      if (!checkSpaceControl(this.isControl)) return
      const itemId = value ? 12 : 10 // 10关闭 12开启
      console.log('itemId', itemId, value)
      let btnTypeDetail = ''
      if (itemId == 12) {
        btnTypeDetail = 'openAir'
      } else {
        btnTypeDetail = 'closeAir'
      }
      this.changeAir(itemId, 'sw', btnTypeDetail)
    },
    onClose() {
      this.visible = false
    },
    popShow() {
      this.visible = true
    },

    checkAirCanOpen(itemId) { // 判断空调是否能开启
      if (!this.roomHasScene && !this.isNowTime) {
        wx.showToast({
          title: '大厦该时段无空调提供',
          icon: 'info',
          duration: 1000
        })
        return false
      }
      if (itemId === 12) { // 12表示开空调
        console.log(this.isNowTime, 'this.isNowTime')
        if (this.roomHasScene && !this.isNowTime) {
          this.$emit('component-open-workTimePop', true)
          return false
        }
      }
      return true
    },
    changeAir(itemId, btnType, btnTypeDetail) {
      if (!checkSpaceControl(this.isControl)) return
            // 如果是过渡季 并且ACATVA 空调  则不能调节温度 不能开
    //   console.log('btnType,this.isACATVA,this.seasonType', btnType, this.isACATVA, this.isACATFC, this.seasonType);
      if (btnType == 'temp' && this.isACATVA && this.seasonType == 'Transition') {
        setTimeout(() => {
          wx.showToast({
            title: '目前为过渡季节，大厦无冷热水供应，空调无法调节',
            duration: 2600,
            icon: 'none'
          })
        }, 0)
        return
      }
      isWithinLocation().then(() => {
        if (this.roomType === '开放') {
          this.showWorkTime = this.checkAirCanOpen(itemId)
          if (!this.showWorkTime) return
        }
        wx.uma.trackEvent(`officeHome_changeAir_${btnTypeDetail}`, { key: btnTypeDetail })
        this.vibrateShort()
        const paramObj = {
          objectId: this.objectId, // 空间id
          valueType: 1, // 固定为1
          itemId: itemId  //   1,有点冷  2,冷死了 3,有点热 4,热死了
        }
                // 如果不是开关空调
        if (btnType != 'sw') {
          this.$emit('airShowVisible', {
            'toWhere': btnTypeDetail,
            'designTemperature': 0 }
                    )
        }
        console.log('空调下发指令')
                //  下达指令
        changeTempHttp(paramObj).then(res => {
          if (btnType != 'sw') {
            this.$emit('airShowVisible', {
              'toWhere': btnTypeDetail,
              'designTemperature': res.designTemperature }
                        )
            if (res.notice) {
              this.$emit('airTemp', {notice: res.notice, remark: res.remark})
            } else {
              feedbackTimer = setInterval(() => {
                this.getAirInfo('feedback', btnType, res.id) // 调节反馈文案
              }, 1000)
            }
          }
        }).catch(() => {
        })
      }).catch(() => {
      })
    }
  }

})
</script>

<style lang="less" scoped>
.air-common-text {
    padding-top: 2rpx;
    font-family: PingFang SC;
    font-size: 22rpx;
    font-weight: 400;
    line-height: 30rpx;
    color: rgba(196, 196, 196, 1);
    &.air-status-text {
        width: 60%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #827f7f;
    }

    &.change-text {
        font-size: 28rpx;
        line-height: 40rpx;
    }
}
.office-card {
    box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.07),
        0px 4px 10px rgba(0, 0, 0, 0.05);
    border-radius: 50rpx;
    background: #ffffff;
    margin-bottom: 30rpx;
}

.air-adjust {
    position: relative;
    // height: 280rpx;
    .air-content {
        padding: 48rpx 30rpx 0rpx 60rpx;
        box-sizing: border-box;
    }

    .air-switch {
        position: absolute;
        top: 190rpx;
        right: 30rpx;
    }

    .air-adjust-env {
        .envname {
            font-family: PingFang SC;
            color: rgba(77, 82, 98, 1);
            font-size: 32rpx;
            font-weight: 600;
            line-height: 44rpx;
        }
        .envnum {
            font-family: Montserrat;
            font-size: 64rpx;
            font-weight: 400;
            line-height: 64rpx;
            padding-top: 10rpx;
            color: #1b144e;
            label {
                font-family: Mulish;
                font-weight: 800;
                font-size: 24rpx;
                margin-left: 6rpx;
                line-height: 30rpx;
                vertical-align: top;
                color: #c4c4c4;
            }
        }
    }
    .air-status {
        padding-top: 20rpx;
        font-family: PingFang SC;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 40rpx;
        color: rgba(196, 196, 196, 1);
    }

    .room-air-status {
        padding-top: 6rpx;
        padding-bottom: 20rpx;
        display: flex;
        align-items: center;
        .room-air-img {
            margin-right: 7rpx;
            width: 28rpx;
            height: 28rpx;
        }
    }

    .air-adjust-btn {
        flex: 1;
        image {
            position: absolute;
            top: 0;
            right: 0;
            width: 314rpx;
            height: 220rpx;
        }
    }
}
.air-control-item {
    padding: 20rpx 28rpx 16rpx 56rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    border-top: 1px solid rgba(196, 196, 196, 0.4);
    .air-control-item-box {
        display: flex;
        align-items: center;
    }
    .envnum-common {
        font-family: Montserrat;
        font-size: 40rpx;
        font-weight: 500;
        line-height: 48rpx;
        color: rgba(77, 82, 98, 1);
        &.air-envnum-comon {
            display: flex;
            align-items: center;
        }
        .envnum-common-wind {
            font-family: Montserrat;
            font-size: 24rpx;
            font-weight: 500;
            line-height: 30rpx;
            margin-right: 10rpx;
            color: rgba(196, 196, 196, 1);
            &.windBlack {
                font-size: 40rpx;
                line-height: 48rpx;
                color: rgba(77, 82, 98, 1);
            }
        }
        &.colorRed {
            color: red;
        }
        &.colorBlue {
            color: rgba(94, 139, 207, 1);
        }
        &.colorBlack {
            color: rgba(77, 82, 98, 1);
        }
        label {
            font-size: 11px;
            line-height: 13px;
            color: rgba(196, 196, 196, 1);
            vertical-align: top;
        }
    }
    .air-common-switch {
        display: flex;
    }
    .switch:first-child {
        margin-right: 40rpx;
    }
    .switch {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 80rpx;
        width: 80rpx;
        background: #c4c4c433;
        border-radius: 50%;
        image {
            width: 40rpx;
            height: 40rpx;
        }
        &.yell {
            background: rgba(61, 203, 204, 0.3);
        }
    }
}
</style>

<config>
{
    usingComponents: {
        "switch": "./switch"    
    }

}
</config>
