<template>
  <div class="more-box">
    <div class="air-more-top">
      <div class="left">
        <div class="air-box">
          <img alt="" :src="airSwitchStatus.switchStatus ? AirIconOpen : AirIconClose" />
        </div>
        <div class="air-name">{{ $t(`air.${airSwitchStatus.statusText}`) }}</div>
      </div>
      <div class="right">
        <div class="control" :ref="setRef" @click="handleSwitch('isOpen', true)">{{ $t(`common.全开`) }}</div>
        <div class="control" :ref="setRef" @click="handleSwitch('isOpen', false)">{{ $t(`common.全关`) }}</div>
      </div>
    </div>
    <div class="air-middle" v-if="airSwitchStatus.switchStatus">
      <div class="bright-slider">
        <AirSlider
          v-model="airData.tempSet"
          :min="airData.minTempSet"
          :max="airData.maxTempSet"
          isFollow
          showValue
          suffix="℃"
          @onStart="sendEvent(true)"
          @onEnd="setAirStatus('tempSet')"></AirSlider>
      </div>
      <div class="temp-slider">
        <div class="handle-box">
          <div
            class="handle-item air-down"
            :ref="setRef"
            data-type="minus"
            @click.prevent.stop="handle('minus', airData, 'all')">
            <div
              class="icon"
              :style="{
                background: `url(${buttonStates.minus ? MinusIconActive : MinusIcon}) no-repeat center`,
                backgroundSize: 'contain'
              }"></div>
          </div>
          <div
            class="handle-item air-up"
            :ref="setRef"
            data-type="plus"
            @click.prevent.stop="handle('plus', airData, 'all')">
            <img class="icon" :src="buttonStates.plus ? AddIconActive : AddIcon" />
          </div>
          <div class="handle-item air-auto" @click.prevent.stop="handle('auto', airData, 'all')">
            <img class="icon" :src="airData.isAutoGear ? AutoIconActive : AutoIcon" />
          </div>
        </div>

        <div class="fan-speed">
          <div class="volume-top">
            <!-- <span :class="airData.gear == 0 ? 'span-active' : ''">0</span> -->
            <span :class="airData.gear == 1 ? 'span-active' : ''">1</span>
            <span :class="airData.gear == 2 ? 'span-active' : ''">2</span>
            <span :class="airData.gear == 3 ? 'span-active' : ''">3</span>
            <span :class="airData.gear == 4 ? 'span-active' : ''">4</span>
            <span :class="airData.gear == 5 ? 'span-active' : ''">5</span>
          </div>
          <div class="text">{{ $t(`air.风量调节`) }}</div>
        </div>
      </div>
    </div>

    <div class="divider" v-if="airSwitchStatus.switchStatus">
      <img src="@/assets/svg/line.svg" alt="" />
    </div>
    <!-- 子设备列表 -->
    <div class="air-bottom">
      <div class="item-box" :class="item.isOpen ? 'item-active' : ''" v-for="item in airEquipList" :key="item.id">
        <div class="handle-top">
          <div class="switch-box">
            <div class="name">{{ item.localName }}</div>
            <div class="switch">
              <SwitchButton
                :loading="allAirStatus[item.id]?.loading"
                v-model="item.isOpen"
                @change="sigleAirChange('isOpen', item, 'single')" />
            </div>
          </div>
          <div v-if="item.isOpen" class="fan-speed air-card">
            <div class="handle-box">
              <div
                class="handle-item air-down"
                :ref="setRef"
                data-type="minus"
                @click.prevent.stop="handle('minus', item, 'single')">
                <img class="icon" :src="buttonStates[item.id]?.minus ? MinusIconActive : MinusIcon" />
              </div>
              <div
                class="handle-item air-up"
                :ref="setRef"
                data-type="plus"
                @click.prevent.stop="handle('plus', item, 'single')">
                <img class="icon" :src="buttonStates[item.id]?.plus ? AddIconActive : AddIcon" />
              </div>
              <div class="handle-item air-auto" @click.prevent.stop="handle('auto', item, 'single')">
                <img class="icon" :src="item.isAutoGear ? AutoIconActive : AutoIcon" />
              </div>
            </div>
            <div class="fans-view">
              <div class="volume-top">
                <!-- <span :class="item.gear == 0 ? 'span-active' : ''">0</span> -->
                <span :class="item.gear == 1 ? 'span-active' : ''">1</span>
                <span :class="item.gear == 2 ? 'span-active' : ''">2</span>
                <span :class="item.gear == 3 ? 'span-active' : ''">3</span>
                <span :class="item.gear == 4 ? 'span-active' : ''">4</span>
                <span :class="item.gear == 5 ? 'span-active' : ''">5</span>
              </div>
              <div class="text">{{ $t(`air.风量调节`) }}</div>
            </div>
          </div>
        </div>
        <div v-if="item.isOpen" class="handle-bottom">
          <AirSlider
            isFollow
            showValue
            suffix="℃"
            v-model="item.tempSet"
            :min="airData.minTempSet"
            :max="airData.maxTempSet"
            @onStart="sendEvent(true)"
            @onEnd="sigleAirChange('tempSet', item, 'single')"></AirSlider>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import AddIcon from "@/assets/taiguv1/svg/add_icon.svg"
import AddIconActive from "@/assets/taiguv1/svg/add_icon_active.svg"
import AirIconClose from "@/assets/taiguv1/svg/air_icon_close.svg"
import AirIconOpen from "@/assets/taiguv1/svg/air_icon_open.svg"
import AutoIcon from "@/assets/taiguv1/svg/auto_icon.svg"
import AutoIconActive from "@/assets/taiguv1/svg/auto_icon_active.svg"
import MinusIcon from "@/assets/taiguv1/svg/minus_icon.svg"
import MinusIconActive from "@/assets/taiguv1/svg/minus_icon_active.svg"

import AirSlider from "@/components/slider/air-slider.vue"
import SwitchButton from "@/components/switch-button/SwitchButton.vue"
import useDeviceControl from "@/hooks/useDeviceControl"
import { useStore } from "@/store"
import eventBus from "@/utils/eventBus"
let closeUpdate = false
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue"
const emit = defineEmits(["getStatus"])
const controlBtn = ref([])
const store = useStore()
const setRef = el => {
  if (el) {
    if (!controlBtn.value.includes(el)) {
      controlBtn.value.push(el)
    }
  }
}
const buttonStates = ref({
  minus: false,
  plus: false
})
const initItemButtonStates = itemId => {
  if (!buttonStates.value[itemId]) {
    buttonStates.value[itemId] = {
      minus: false,
      plus: false,
      auto: false
    }
  }
}
const deviceControl = useDeviceControl()
// 接收父组件传递的初始状态
const props = defineProps({
  airList: {
    type: Array,
    default: () => []
  },
  status: {
    type: Object,
    default: function () {
      return {
        isOpen: false,
        gear: 1,
        minTempSet: 16,
        maxTempSet: 32,
        tempSet: 24,
        isAutoGear: false,
        switchLoading: false
      }
    }
  }
})
const airEquipList = ref(props.airList || [])
const airData = ref(props.status)
const airSwitchStatus = computed(() => {
  let statusText = ""
  let switchStatus = false
  let arr = props.airList.filter(item => item.runStatus == 1)
  if (arr.length == 0) {
    statusText = "已关闭"
    switchStatus = false
  } else {
    statusText = arr.length > 0 && arr.length < props.airList.length ? "部分开启" : "已开启"
    switchStatus = true
  }
  return {
    statusText,
    switchStatus
  }
})
const allAirStatus = computed(() => store.state.taiguv1.airSwtichStatus)

watch(
  () => props.status,
  (newVal, oldVal) => {
    if (!newVal || closeUpdate) {
      return
    }
    let { minTempSet, maxTempSet } = airData.value
    airData.value = { ...newVal, minTempSet, maxTempSet }
  },
  { deep: true } // 添加深度监听
)
watch(
  () => props.airList,
  (newVal, oldVal) => {
    if (!newVal || closeUpdate) {
      return
    }
    compareStatus(newVal)
    // 为所有item初始化按钮状态
    newVal.forEach(item => {
      initItemButtonStates(item.id)
    })
  },
  { deep: true }
)

// 对比和store中开关状态
const compareStatus = data => {
  airEquipList.value = data.map(item => {
    const currentStatus = allAirStatus.value[item.id]

    // 基础状态对象
    const baseStatus = {
      ...item,
      isOpen: item.runStatus == 1
    }

    if (!currentStatus) {
      return baseStatus
    }

    // 如果最后切换状态与当前运行状态相同，重置状态
    if (currentStatus.lastSwitchStatus == item.runStatus) {
      store.dispatch("taiguv1/setAirStatus", {
        id: item.id,
        status: {
          loading: false,
          lastSwitchStatus: null
        }
      })
      return baseStatus
    }

    // 如果有待处理的切换状态，使用该状态
    return {
      ...item,
      isOpen: currentStatus.lastSwitchStatus ?? item.runStatus == 1
    }
  })
}

// 整体开关
const handleSwitch = (type, value) => {
  airData.value.isOpen = value
  setAirStatus(type)
}

// 单个空调开关
const sigleAirChange = (type, source, all) => {
  if (type == "isOpen") {
    store.dispatch("taiguv1/setAirStatus", {
      id: source.id,
      status: {
        loading: true,
        lastSwitchStatus: source.isOpen
      }
    })
  }
  if (all == "single") {
    const params = deviceControl.assemblyAirCommand(source[type], type, source)
    deviceControl.sendCommands(params, () => {
      debouncedSendEvent(false)
    })
  }
}
const setAirStatus = type => {
  if (type == "isOpen") {
    store.dispatch("taiguv1/setAirStatus", {
      id: "all",
      status: {
        loading: true,
        lastSwitchStatus: airData.value.isOpen
      }
    })
    airEquipList.value.forEach(item => {
      item.isOpen = airData.value.isOpen
      sigleAirChange(type, item, "all")
    })
  }
  const params = deviceControl.assemblyAirCommand(airData.value[type], type, airEquipList.value)
  deviceControl.sendCommands(params, () => {
    debouncedSendEvent(false)
  })
}

const debouncedSetAirStatus = deviceControl.debounce(setAirStatus, 1500)
const debouncedSigleAirChange = deviceControl.debounce(sigleAirChange, 1500)

const handle = (type, data, all) => {
  // 确保该item的按钮状态已初始化
  initItemButtonStates(data.id)
  // 设置当前item的对应按钮状态为激活
  buttonStates.value[data.id][type] = true
  // 200ms后恢复非激活状态
  setTimeout(() => {
    buttonStates.value[data.id][type] = false
  }, 200)

  if (!data.gear) data.gear = 0
  if (type === "minus") {
    // data.gear -= 1
    // if (data.gear < 0) {
    //   data.gear = 0
    // }
    data.gear = Math.max(data.gear - 1, 1) // 确保 gear 不小于 1
    data.isAutoGear = false
  } else if (type === "plus") {
    data.gear += 1
    if (data.gear > 5) {
      data.gear = 5
    }
    data.isAutoGear = false
  } else if (type === "auto") {
    data.isAutoGear = true
  }
  sendEvent(true)
  if (all == "all" && type == "auto") {
    debouncedSetAirStatus("auto", all)
  } else if (all == "all" && type !== "auto") {
    debouncedSetAirStatus("gear", all)
  } else if (all == "single" && type !== "auto") {
    debouncedSigleAirChange("gear", data, all)
  } else if (all == "single" && type == "auto") {
    debouncedSigleAirChange("auto", data, all)
  }
}
const sendEvent = close => {
  closeUpdate = close
  eventBus.emit("close_deviece_timer", { close })
}
const debouncedSendEvent = deviceControl.debounce(sendEvent, 1500)
onMounted(() => {
  nextTick(() => {
    controlBtn.value.forEach(button => {
      button.addEventListener("touchstart", handleTouchStart)
      button.addEventListener("click", handleTouchStart)
    })
  })
})

// 添加 touchstart 处理函数
const handleTouchStart = event => {
  console.log("debugger111")
  const button = event.currentTarget
  const type = button.getAttribute("data-type") // 获取按钮类型
  button.classList.add("active")
  if (type) {
    buttonStates.value[type] = true
  }
  setTimeout(() => {
    button.classList.remove("active")
    if (type) {
      console.log("debugger")
      buttonStates.value[type] = false
    }
  }, 200)
}

// 添加 onUnmounted 钩子
onUnmounted(() => {
  controlBtn.value.forEach(button => {
    button.removeEventListener("touchstart", handleTouchStart)
    button.removeEventListener("click", handleTouchStart)
  })
})
</script>
<style lang="scss" scoped>
.more-box {
  .air-more-top {
    display: flex;
    align-items: center;
    margin-bottom: 36px;
    .left {
      margin-right: 36px;
      .air-box {
        width: 110px;
        height: 110px;
        background: rgba(255, 255, 255, 0.4);
        border-radius: 50%;
        text-align: center;
        margin-right: 27px;
        display: flex;
        justify-self: center;
        align-items: center;
        img {
          width: 30px;
          height: 30px;
          margin: 0 auto;
        }
      }
      .air-name {
        //styleName: Chi/Body Large;
        margin-top: 12px;
        font-family: PingFang SC;
        width: 110px;
        font-size: 16px;
        font-weight: 300;
        line-height: 22px;
        letter-spacing: 0.02em;
        text-align: center;
        color: rgba(0, 20, 40, 1);
      }
    }
    .right {
      height: 92px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .control {
        width: 100px;
        height: 40px;
        line-height: 40px;
        border-radius: 50px;
        border-radius: 50px;
        background: #e1e1df;
        box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.05);
        color: #001428;
        //styleName: Chi/Body Small;
        font-family: PingFang SC;
        font-size: 12px;
        font-weight: 400;
        letter-spacing: 0.04em;
        text-align: center;
      }
      .control.active {
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px 10px 20px 0px rgba(0, 20, 40, 0.1);
      }
    }
  }
  .air-middle {
    // height: 100px;
    // background: #fff;
    .bright-slider {
      width: 100%;
      height: 62px;

      background: rgba(255, 255, 255, 0.6);
      margin-bottom: 12px;
      border-radius: 12px;
    }
    .temp-slider {
      display: flex;
      width: 296px;
      height: 65px;
      padding: 0px 24px;
      justify-content: space-between;
      align-items: center;
      flex-shrink: 0;
      border-radius: 24px 24px 60px 24px;
      background: rgba(255, 255, 255, 0.6);
      .handle-box {
        display: flex;
        gap: 6px;
        .handle-item {
          display: flex;
          align-items: center;
          width: 40px;
          height: 40px;
          text-align: center;
          .icon {
            margin-top: 8px;
            width: 28.3px;
            height: 28.3px;
            margin: 0 auto;
          }
        }
      }
      .fan-speed {
        .volume-top {
          padding-bottom: 2px;
          height: 3.33vh;
          line-height: 1;
          span {
            //styleName: En/Body Small;
            display: inline-block;
            margin-right: 5px;
            font-family: Jost;
            font-size: 12px;
            font-weight: 400;
            line-height: 17px;
            color: rgba(116, 128, 141, 1);
          }
          .span-active {
            color: rgba(0, 20, 40, 1);
            font-size: 16px;
            line-height: 22px;
          }
        }
        .text {
          //styleName: Chi/Body XS;
          font-family: PingFang SC;
          font-size: 11px;
          font-weight: 400;
          line-height: 15px;
          letter-spacing: 0.02em;
          color: rgba(0, 20, 40, 1);
        }
      }
    }
  }

  .divider {
    height: 24px;
    display: flex;
    align-items: center;
  }
  .air-bottom {
    // margin-top: 36px;
    .item-box {
      display: flex;
      width: 300px;
      padding: 20px 24px;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 12px;
      margin-bottom: 12px;
      border-radius: 24px 24px 60px 24px;
      background: rgba(255, 255, 255, 0.2);
      box-shadow: 0px 10px 20px 0px rgba(0, 20, 40, 0.05);
      .handle-top {
        width: 100%;
        .switch-box {
          width: 100%;
          display: flex;
          height: 28px;
          justify-content: space-between;
          .name {
            color: var(--Blue, #001428);
            font-family: "PingFang SC";
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            letter-spacing: 0.36px;
          }
          .switch {
            width: 50px;
          }
        }
      }
      .handle-bottom {
        margin-top: 12px;
        display: flex;
        width: 243px;
        height: 48px;
        padding: 2px;
        align-items: center;
        gap: 10px;
        border-radius: 14px;
        background: var(--White-White-60, rgba(255, 255, 255, 0.6));
      }
    }
    .handle-box {
      display: flex;
      gap: 6px;
      .handle-item {
        width: 40px;
        height: 40px;
        text-align: center;
        .icon {
          margin-top: 8px;
          width: 28.3px;
          height: 28.3px;
        }
      }
    }
    .fan-speed {
      margin-top: 12px;
      &.air-card {
        display: flex;
        justify-content: space-between;
      }
      .volume-top {
        padding-bottom: 2px;
        height: 3.33vh;
        line-height: 1;
        span {
          //styleName: En/Body Small;
          display: inline-block;
          margin-right: 5px;
          font-family: Jost;
          font-size: 12px;
          font-weight: 400;
          line-height: 17px;
          color: rgba(116, 128, 141, 1);
        }
        .span-active {
          color: rgba(0, 20, 40, 1);
          font-size: 16px;
          line-height: 22px;
        }
      }
      .text {
        //styleName: Chi/Body XS;
        font-family: PingFang SC;
        font-size: 11px;
        font-weight: 400;
        line-height: 15px;
        letter-spacing: 0.02em;
        color: rgba(0, 20, 40, 1);
      }
    }
    .item-active {
      background: rgba(255, 255, 255, 0.6);
    }
  }
  .switch-btn {
    margin-top: 0;
    width: 50px !important;
    height: 28px !important;
    border: none;
  }
}
</style>
<style lang="scss">
// .more-box {
//   .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>
