<style lang="less" scoped>
.office-card {
    box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.07),
        0px 4px 10px rgba(156, 125, 125, 0.05);
    border-radius: 50rpx;
    background: #ffffff;
    margin-bottom: 30rpx;
}
.lamp-basic-name {
    font-weight: 600;
    font-size: 32rpx;
    line-height: 44rpx;
    color: rgba(77, 82, 98, 1);
}
.lamp-status {
    font-size: 14px;
    font-weight: 400;
    line-height: 40rpx;
    color: rgba(196, 196, 196, 1);
    &.lamp-status-padding {
        padding-top: 20rpx;
    }
}
.lamp-basic-one {
    padding: 48rpx 40rpx 12rpx 40rpx;
    font-family: PingFang SC;
    .lamp-basic-num {
        font-family: Montserrat;
        font-size: 64rpx;
        line-height: 78rpx;
        color: #1b144e;
        label {
            font-weight: 800;
            font-size: 24rpx;
            margin-left: 8rpx;
            line-height: 54rpx;
            vertical-align: top;
            color: #c4c4c4;
        }
    }
}
.lamp-adjust {
    box-sizing: border-box;
    position: relative;
    .lamp-pic {
        height: 140px;
        width: 165px;
        position: absolute;
        top: 0;
        left: 166px;
        image {
            width: 100%;
            height: 100%;
        }
    }
    .lamp-basic {
        font-family: PingFang SC;
        padding-top: 48rpx;
        padding-bottom: 40rpx;
        .lamp-basic-num {
            font-family: Montserrat;
            font-size: 64rpx;
            line-height: 78rpx;
            color: #1b144e;
            label {
                font-weight: 800;
                font-size: 24rpx;
                margin-left: 8rpx;
                line-height: 54rpx;
                vertical-align: top;
                color: #c4c4c4;
            }
        }
    }
}
.lamp-item {
    display: flex;
    flex-wrap: wrap;
    padding-top: 40rpx;
    padding-left: 24rpx;
    padding-right: 24rpx;
    .item-box {
        position: relative;
        height: 232rpx;
        width: 296rpx;
        border-radius: 32rpx;
        margin-top: 24rpx;
        background: #f7f9fa;
    }
    .item-box:nth-child(2n-1) {
        margin-right: 22rpx;
    }
}
.adjust-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 72rpx;
    width: 72rpx;
    border-radius: 50%;
}
.bg {
    background: #f1f4f6;
}
.icon_adjust {
    width: 40rpx;
    height: 40rpx;
}
.dplCenter {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.all-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 24rpx;
    height: 64rpx;
    width: 120rpx;
    border-radius: 42rpx;
    background: #f1f4f6;
    .btn-text {
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 40rpx;
        color: #2e3742;
    }
}

.small-img-card {
    .small-lamp-img {
        width: 80px;
        height: 70px;
    }
}
.small-sw-card {
    position: absolute;
    top: 0rpx;
    right: 0rpx;
}

.lamp-spread {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 25rpx;
    .lamp-basic-allow {
        width: 50rpx;
        height: 36rpx;
    }
}
.cellhoverstyle {
    background: #e8ecf0;
}
</style>
<template>
    <div class="lamp-adjust office-card">
        <!-- 一个灯 -->
        <div
            class="lamp-pic"
            v-if="lampList.length===1"
        >
            <image
                :src="[lampSw ?  (h5StaticPath+'lamp_open_v2.png') : (h5StaticPath+'lamp_close_v2.png')]"
                alt=""
            />
        </div>
        <div
            class="lamp-basic-one"
            v-if="lampList.length===1"
            @click="openColourPop(lampList[0])"
        >
            <span class="lamp-basic-name">光照</span>
            <div class="lamp-status lamp-status-padding">{{lampSw? '照明已开启':'照明已关闭'}}</div>
            <div
                class="dplCenter"
                style="margin-top: 20rpx;"
            >
                <div :class="{'adjust-box':true,'bg':(lampList[0].bright || lampList[0].colorTemperature)}">
                    <div
                        v-if="lampList[0].bright || lampList[0].colorTemperature"
                        :style="{'opacity':(!lampList[0].switch?'0.3':'1')+';width:40rpx;height:40rpx'}"
                    >
                        <image
                            class="icon_adjust"
                            src="/static/icon_adjust.svg"
                        />
                    </div>
                </div>
                <div>
                    <switch
                        class="lamp-switch"
                        :checked="lampList[0].switch"
                        :showWorkTime="showWorkTime"
                        :eqTitle="lampList[0].localName"
                        @component-switch-change="eqChange($event,lampList[0].id)"
                    ></switch>
                </div>
            </div>
        </div>
        <!-- 多个灯 -->
        <div
            class="lamp-basic"
            style="{{ lampList.length>2 ? 'padding-bottom: 20rpx;' :'' }}"
            v-if="lampList.length>1"
        >
            <div
                class="dplCenter"
                style="margin-left:40rpx;margin-right: 40rpx;"
            >
                <div>
                    <span class="lamp-basic-name">光照</span>
                    <div class="lamp-status lamp-status-padding">{{lampSw? '照明已开启':'照明已关闭'}}</div>
                </div>
                <div class="dplCenter">
                    <div
                        class="all-btn"
                        hover-class="cellhoverstyle"
                        @click="eqChange(true,'allLamp')"
                    >
                        <span class="btn-text">全开</span>
                    </div>
                    <div
                        class="all-btn"
                        hover-class="cellhoverstyle"
                        @click="eqChange(false,'allLamp')"
                    >
                        <span class="btn-text">全关</span>
                    </div>
                </div>
            </div>
            <div class="lamp-item">
                <div
                    class="item-box"
                    v-for="(item,index) in lampList"
                    :data-index="item.id"
                    :key="item.id"
                    @click="openColourPop(item)"
                >
                    <div class="small-img-card">
                        <image
                            class="small-lamp-img"
                            src="{{h5StaticPath}}{{item.lampImg}}"
                            :key="item.id"
                        />
                    </div>
                    <div class="small-sw-card">
                        <switch-small
                            class="lamp-switch"
                            :checked="item.switch"
                            :eqTitle="item.name"
                            :showWorkTime="showWorkTime"
                            @component-switch-change="eqChange($event,item.id,index)"
                        ></switch-small>
                    </div>

                    <div
                        class="dplCenter"
                        style="padding-right:28rpx;padding-left:32rpx"
                    >
                        <div class="lamp-basic-name">
                            <span>{{item.localName}}</span>
                        </div>
                        <div
                            :style="{'opacity':(!item.switch?'0.3;':'1')}"
                            v-if="item.bright || item.colorTemperature"
                        >
                            <image
                                class="icon_adjust"
                                src="{{h5StaticPath}}icon_adjust.svg"
                                :key="item.id"
                            />
                        </div>
                    </div>
                </div>
            </div>
            <div
                class="lamp-spread"
                v-if="total>2"
                @click="handleShow"
            >
                <image
                    class="lamp-basic-allow"
                    src="{{h5StaticPath}}{{allowSvg}}"
                />
                <span class="lamp-status">{{showLamps?'收起':'展开'}}更多</span>
            </div>

        </div>
    </div>
</template>

<script>
import wepy from '@wepy/core'
import { setallLampHttp, getLampHttp, getStatusHttp } from '@/packagesEnv/api/officehome.js'
import { isWithinLocation } from '@/service/location'
import config from '@/config'
import store from '@/store'
import { mapState } from '@wepy/x'
let fifteenTimer = null
wepy.component({
  props: {
    equipConfig: Array, // 设备配置情况
    controlMode: Number, // 手动模式
    roomType: String, // 房间类型
    roomHasScene: Boolean, // 加班场景
    spaceId: String, // 空间id
    lampHide: Boolean
  },
  store,
  data: {
    showWorkTime: false,  // 展示预约时间弹框
    lightsStatusTimer: null,
    h5StaticPath: config.h5StaticPath + '/page-officehome/',
    lampSw: null, // 主灯开关
    showLamps: false,
    allowSvg: 'down_Arrow.svg',
    startX: 0,
    sliderWidth: 0,
    total: 0,
    lampList: [],
    initData: [] // 灯原始数据

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

  },
  watch: {
    spaceId(val) {
      this.showLamps = false // 恢复初始化值
      this.allowSvg = 'down_Arrow.svg'
      if (val) {
        this.getLampList()
        this.getTwoTimerLoop()
      }
    },
    lampHide(nval) {
      if (this.showLamps) {
        this.handleShow()
      }
    }

  },
  detached() {
    clearInterval(this.lightsStatusTimer)
    this.lightsStatusTimer = null
    clearTimeout(fifteenTimer)
    fifteenTimer = null
  },
  methods: {
    openColourPop(obj) {
            //  灯开时 才能调节色温
      if (obj.runStatus && (obj.bright || obj.colorTemperature)) {
        this.$emit('component-open-colourPop', obj)
      }
    },
    // 设置灯对应的图片
    setLampItem(item) {
      if (item.lightType === 1) {
        if (item.switch) {
          item.lampImg = 'lamp_small_open.png'
        } else {
          item.lampImg = 'lamp_small_close.png'
        }
      } else {
        if (item.switch) {
          item.lampImg = 'atmLamp_small_open.png'
        } else {
          item.lampImg = 'atmLamp_small_close.png'
        }
      }
    },
    // 大于三个灯时，展示的数量
    showLampCount() {
      let arr = []
      this.initData.map((item, idx) => {
        this.setLampItem(item)
        if (this.initData.length < 3 || !this.showLamps) {
          if (idx < 2) {
            arr.push(item)
          }
        } else {
          arr = [...this.initData]
        }
      })
      this.lampList = JSON.parse(JSON.stringify(arr))
    },
    getLampList() {
      getLampHttp({ spaceId: this.spaceId }).then(res => {
        const content = res.content || []
        if (!content.length) return
        let flag = false
        for (let index = 0; index < content.length; index++) {
          let item = content[index]
          item.switch = !!item.runStatus
          if (item.runStatus) {
            flag = true
          }
        }
        this.lampSw = flag
        this.initData = JSON.parse(JSON.stringify(res.content))//  灯的数据
        this.total = this.initData.length
        this.showLampCount()
      })
    },
    vibrateShort() {
      if (wx.canIUse('vibrateShort')) {
        wx.vibrateShort()
      } else {
        wx.vibrateLong()
      }
    },
        // 手动模式下设备是否可控
    checkControlMode(id) {
      let flag = false
      if (!this.controlMode) {
        return flag
      }

            //  总开关
      if (id === 'allLamp') {
        let canOpen = true
        for (let i = 0; i < this.equipConfig.length; i++) {
          const ele = this.equipConfig[i]
          for (let j = 0; j < this.lampList.length; j++) {
            const jele = this.lampList[j]
                        // 有可控设备
            if (ele.equipmentId === jele.id && ele.isExeSpaceTime) {
              canOpen = false
              return
            }
          }
        }
        flag = canOpen
      } else {
        this.equipConfig.map(item => {
                    //  设备不受控制 可直接开灯
          if (item.equipmentId === id && !item.isExeSpaceTime) {
            flag = true
          }
                    // 设备受控 且有当前工作时间 可直接开灯
          if (item.equipmentId === id && this.isNowTime && item.isExeSpaceTime) {
            flag = true
          }
        })
      }

      return flag
    },
    checkLampCanOpen(value, id) { // 判断灯是否能开启
      if (value) {
                // 手动模式下设备是否可控
        let canControl = this.checkControlMode(id)
                // 有场景无时间 得预约
        if (this.roomHasScene && !this.isNowTime && !canControl) {
                    // 手动模式下
          this.controlMode && this.$emit('component-EquipType-workTimePop', id)
          this.$emit('component-open-workTimePop', true)
          return false
        }
      }
      return true
    },
    eqChange(value, id, index) {
      isWithinLocation().then(() => {
        if (this.roomType === '开放') {
          this.showWorkTime = this.checkLampCanOpen(value, id)
          if (!this.showWorkTime) return
        }
        this.fifteenTimeout()
        let params = []
        if (id === 'allLamp') {
          params = this.initData
          params.forEach(item => {
            item.switch = value
          })
         // 前端现更改灯的状态，15s后获取设备状态
          this.lampList.map(item => {
            item.switch = value
            this.setLampItem(item)
          })
          this.initData.map(item => {
            item.switch = value
            this.setLampItem(item)
          })
          this.lampSw = value
        } else {
          params = [{ id: id, switch: value }]
          //  前端现更改灯的状态，15s后获取设备状态
          if (this.lampList.length === 1) {
            this.lampSw = value
          }
          this.lampList.map(item => {
            if (item.id === id) {
              item.switch = value
              this.setLampItem(item)
            }
          })
          this.initData.map(item => {
            if (item.id === id) {
              item.switch = value
              this.setLampItem(item)
            }
          })
        }
        this.fifteenTimeout()
        setallLampHttp(params).then(res => {})
        this.vibrateShort()
      })
    },
    // 15s 之后再请求状态
    fifteenTimeout() {
      clearInterval(this.lightsStatusTimer)
      this.lightsStatusTimer = null
      clearTimeout(fifteenTimer)
      fifteenTimer = null
      fifteenTimer = setTimeout(() => {
        this.getTwoTimerLoop()
      }, 1000 * 15)
    },
    getTwoTimerLoop() {
      clearInterval(this.lightsStatusTimer)
      this.lightsStatusTimer = null
      this.lightsStatusTimer = setInterval(() => {
        this.getLampList()
      }, 2 * 1000) // 2秒描刷接口
    },

        // 灯列表
    handleShow() {
      if (!this.lampList.length) return
      this.showLamps = !this.showLamps
      if (!this.showLamps) {
        this.allowSvg = 'down_Arrow.svg'
      } else {
        this.allowSvg = 'up_Arrow.svg'
      }
      this.setLampList()
    },
    setLampList() {
      this.showLampCount()
    }
  }
})
</script>



<config>
{
    usingComponents: {
        "switch": "./switch",
        "switch-small": "./switch-small",
        "van-popup": "module:@vant/weapp/dist/popup"
    }
}
</config>
