<template>
  <div class="volumn-box" :class="airData.isOpen ? 'activeShow' : ''">
    <div>
      <div class="top">
        <img :src="parseImgUrl('taiguv1/envmonitor', airData.isOpen ? 'active/air-con.svg' : 'air-con.svg')" alt="" />
        <SwitchButton
          :loading="allAirStatus.all?.loading"
          @click.stop
          @change="setAirStatus('isOpen')"
          v-model="airData.isOpen" />
      </div>
      <div class="filter-box" v-if="equipList.length > 1">
        <div class="filter-item" @click="searchMore">
          <img :src="FilterIcon" alt="" />
        </div>
      </div>
    </div>

    <div class="bottom">
      <div class="air-info">
        <div class="left">
          <div class="text">{{ $t(`air.空调`) }}</div>
          <div class="status">{{ $t("air." + airSwitchStatus.statusText) }}</div>
        </div>
        <div class="temp" v-if="airData.isOpen">{{ airData.tempSet || 16 }}<sup>℃</sup></div>
      </div>
      <!--温度⏭️-->
      <div class="temp-box" id="sliderAirId" v-if="airData.isOpen">
        <Slider
          v-model="airData.tempSet"
          :min="airData.minTempSet"
          :max="airData.maxTempSet"
          @onStart="sendEvent(true)"
          @onEnd="setAirStatus('tempSet')"></Slider>
      </div>

      <!--风量调整-->
      <div class="air-volume" v-show="airData.isOpen">
        <div class="volume-left">
          <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 class="volume-right">
          <div class="control-item" :ref="setRef" data-type="minus" @click.prevent.stop="handle('minus')">
            <img class="icon" :src="buttonStates.minus ? MinusIconActive : MinusIcon" />
          </div>
          <div class="control-item" :ref="setRef" data-type="plus" @click.prevent.stop="handle('plus')">
            <img class="icon" :src="buttonStates.plus ? AddIconActive : AddIcon" />
          </div>
          <div class="control-item" @click.prevent.stop="handle('auto')">
            <img class="icon" :src="airData.isAutoGear ? AutoIconActive : AutoIcon" />
          </div>
        </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 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 FilterIcon from "@/assets/taiguv1/svg/filter_icon.svg"
import Slider from "@/components/slider/Slider.vue"
import SwitchButton from "@/components/switch-button/SwitchButton.vue"
import useDeviceControl from "@/hooks/useDeviceControl"
import { useStore } from "@/store"
import { parseImgUrl } from "@/utils"
import eventBus from "@/utils/eventBus"
import { computed, onMounted, onUnmounted, nextTick, ref, watch } from "vue"
let closeUpdate = false
const store = useStore()
const deviceControl = useDeviceControl()
const controlBtn = ref([])
const setRef = el => {
  if (el) {
    if (!controlBtn.value.includes(el)) {
      controlBtn.value.push(el)
    }
  }
}

const props = defineProps({
  status: {
    type: Object,
    default: function () {
      return {
        isOpen: false,
        gear: 1,
        minTempSet: 16,
        maxTempSet: 32,
        tempSet: 24,
        isAutoGear: false,
        switchLoading: false
      }
    }
  },
  equipList: {
    type: Array,
    default: function () {
      return []
    }
  }
})
const airData = ref({
  isOpen: false,
  gear: 1,
  minTempSet: 16,
  maxTempSet: 32,
  tempSet: 16,
  isAutoGear: false,
  switchLoading: false
})
watch(
  () => props.status,
  (newVal, oldVal) => {
    if (!newVal || closeUpdate) {
      return
    }
    compareStatus(newVal)
  },
  { deep: true } // 添加深度监听
)
const compareStatus = data => {
  let { minTempSet, maxTempSet } = airData.value
  const updateAirData = () => {
    airData.value = {
      ...data,
      isOpen: data.runStatus === 1,
      minTempSet,
      maxTempSet
    }
  }
  if (allAirStatus.value.all) {
    const { lastSwitchStatus } = allAirStatus.value.all
    if (lastSwitchStatus == data.runStatus) {
      store.dispatch("taiguv1/setAirStatus", {
        id: "all",
        status: {
          loading: false,
          lastSwitchStatus: null
        }
      })
      updateAirData()
    } else if (lastSwitchStatus === null) {
      console.log("debugger")
      updateAirData()
    } else {
      airData.value = {
        ...data,
        isOpen: lastSwitchStatus,
        minTempSet,
        maxTempSet
      }
    }
  } else {
    updateAirData()
  }
  emit("getStatus", airData.value.isOpen)
}

const airSwitchStatus = computed(() => {
  let statusText = ""
  let switchStatus = false
  let arr = props.equipList.filter(item => item.runStatus == 1)
  if (arr.length == 0) {
    statusText = "已关闭"
    switchStatus = false
  } else {
    statusText = arr.length > 0 && arr.length < props.equipList.length ? "部分开启" : "已开启"
    switchStatus = true
  }
  return {
    statusText,
    switchStatus
  }
})
const allAirStatus = computed(() => store.state.taiguv1.airSwtichStatus)

const emit = defineEmits(["getStatus"])

const buttonStates = ref({
  minus: false,
  plus: false
})
const sendEvent = close => {
  closeUpdate = close
  eventBus.emit("close_deviece_timer", { close })
}
onMounted(() => {
  nextTick(() => {
    controlBtn.value.forEach(button => {
      button.addEventListener("touchstart", handleTouchStart)
    })
  })
})

const handleTouchStart = event => {
  const button = event.currentTarget
  const type = button.dataset.type
  button.classList.add("active")
  buttonStates.value[type] = true

  setTimeout(() => {
    button.classList.remove("active")
    buttonStates.value[type] = false
  }, 200)
}

onUnmounted(() => {
  controlBtn.value.forEach(button => {
    button.removeEventListener("touchstart", handleTouchStart)
  })
})
const debouncedSendEvent = deviceControl.debounce(sendEvent, 1500)
const setAirStatus = type => {
  if (type == "isOpen") {
    store.dispatch("taiguv1/setAirStatus", {
      id: "all",
      status: {
        loading: true,
        lastSwitchStatus: airData.value.isOpen
      }
    })
  }
  const params = deviceControl.assemblyAirCommand(airData.value[type], type, props.equipList)
  deviceControl.sendCommands(params, () => {
    debouncedSendEvent(false)
  })

  emit("getStatus", airData.value.isOpen)
}
const debouncedSetAirStatus = deviceControl.debounce(setAirStatus, 1500)
const handle = type => {
  if (!airData.value.gear) airData.value.gear = 1
  sendEvent(true)
  if (type === "minus") {
    airData.value.gear = Math.max(airData.value.gear - 1, 1)
    airData.value.isAutoGear = false
    debouncedSetAirStatus("gear")
  } else if (type === "plus") {
    airData.value.gear += 1
    if (airData.value.gear > 5) {
      airData.value.gear = 5
    }
    airData.value.isAutoGear = false
    debouncedSetAirStatus("gear")
  } else if (type === "auto") {
    // TODO:自动风量
    airData.value.isAutoGear = true
    debouncedSetAirStatus("auto")
  }
}
const searchMore = () => {
  emit("showMore", "air", true)
}
</script>
<style lang="scss" scoped>
.volumn-box {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 16px;
  width: 100%;
  height: 100%;
  border-radius: 24px 24px 44px 24px;
  background-color: rgba(255, 255, 255, 0.2);
  -webkit-backdrop-filter: blur(40px);
  backdrop-filter: blur(40px);
  box-shadow: 0px 10px 20px 0px rgba(0, 20, 40, 0.1);
  .filter-box {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .filter-item {
      display: flex;
      width: 36px;
      height: 36px;
      justify-content: center;
      align-items: center;
      gap: 10px;
      flex-shrink: 0;
      border-radius: 60px;
      background: var(--White-White-40, rgba(255, 255, 255, 0.4));
    }
  }
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      width: 30px;
      height: 30px;
    }
  }
  .bottom {
    width: 100%;
    .air-info {
      display: flex;
      justify-content: space-between;
      align-items: end;
      .temp {
        font-family: Jost;
        font-size: 20px;
        font-weight: 300;
        line-height: 28px;
        color: rgba(0, 20, 40, 1);
        sup {
          font-family: Jost;
          font-size: 11px;
          font-weight: 400;
          line-height: 15px;
          color: rgba(0, 20, 40, 1);
        }
      }
    }
    .text {
      font-family: PingFang SC;
      font-size: 16px;
      font-weight: 300;
      line-height: 22px;
      letter-spacing: 0.02em;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: rgba(255, 255, 255, 1);
      padding-bottom: 2px;
    }
    .status {
      font-family: PingFang SC;
      font-size: 11px;
      font-weight: 400;
      line-height: 15px;
      letter-spacing: 0.02em;
      color: rgba(255, 255, 255, 0.4);
    }
    .temp-box {
      margin-top: 8px;
      background: rgba(255, 255, 255, 0.6);
      width: 100%;
      height: 34px;
      border-radius: 12px;
    }
  }
  .switch-btn {
    margin-top: 0;
    width: 50px !important;
    height: 28px !important;
    border: none;
  }
}
.activeShow {
  background: rgba(255, 255, 255, 0.8);
  //   -webkit-backdrop-filter: blur(40px);
  //   backdrop-filter: blur(40px);
  box-shadow: 0px 10px 20px 0px rgba(0, 20, 40, 0.1);

  .bottom {
    .text {
      color: rgba(0, 20, 40, 1);
    }
    .status {
      color: rgba(116, 128, 141, 1);
    }
  }
}
.air-volume {
  display: flex;
  margin-top: 4px;
  .volume-left {
    width: 69px;
    .volume-top {
      padding-bottom: 2px;
      height: 3.33vh;
      line-height: 1;
      span {
        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 {
      font-family: PingFang SC;
      font-size: 11px;
      font-weight: 400;
      line-height: 15px;
      letter-spacing: 0.02em;
      color: rgba(0, 20, 40, 1);
    }
  }
  .volume-right {
    width: 120px;
    display: flex;
    justify-content: space-between;
    .control-item {
      width: 40px;
      height: 40px;
      text-align: center;
      .icon {
        margin-top: 8px;
        width: 28.3px;
        height: 28.3px;
      }
    }
  }
}
</style>
