<template>
  <div class="more-box">
    <div class="light-more-top">
      <div class="left">
        <div class="light-box">
          <img
            :src="lampData.isOpen ? lampOpenIcon : lampCloseIcon"
            alt=""
            :style="lampData.isOpen ? { width: '58px', height: '62px' } : ''"
          />
        </div>
        <div class="light-name">{{ $t(`lamp.${lampData.lampStatusText}`) }}</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="light-middle"
      v-if="lampData.isOpen"
    >
      <div class="bright-slider">
        <Slider
          :min="min"
          :max="max"
          type="light"
          v-model="lampData.brightValue"
          isFollow
          showValue
          suffixNormal
          suffix="%"
          @onStart="sendEvent(true)"
          @onEnd="setLampStatus('brightValue')"
        />
      </div>
      <!-- <div class="temp-slider">
        <LampSlider v-model="lampData.colorTempValue" @onEnd="setLampStatus('colorTempValue')" />
      </div> -->
    </div>

    <div
      class="divider"
      v-if="lampData.isOpen"
    >
      <img
        src="@/assets/svg/line.svg"
        alt=""
      />
    </div>

    <div class="light-bottom">
      <div
        class="item-box"
        :class="item.brightValue ? 'light-box-active' : ''"
        v-for="(item, index) in lampList"
      >
        <div class="name">{{ item.localName }}</div>
        <div style="width: 100rpx">
          <SwitchButton
            :loading="allLampStatus[item.id]?.loading"
            v-model="item.isOpen"
            @change="sigleLampChange('isOpen', item, 'single')"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import lampCloseIcon from '@/assets/taiguv1/svg/lamp_close_p_icon.svg';
import lampOpenIcon from '@/assets/taiguv1/svg/lamp_open_p_icon.svg';
import Slider from '@/components/slider/Slider.vue';
import SwitchButton from '@/components/switch-button/SwitchButton.vue';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import eventBus from '@/utils/eventBus';
import useDeviceControl from '@/hooks/useDeviceControl';
import { customRound } from '@/utils';
import { useStore } from '@/store';
import { type } from 'os';
const store = useStore();
const deviceControl = useDeviceControl();
const min = 0;
const max = 100;
let closeUpdate = false;
// 接收父组件传递的初始状态
const props = defineProps({
  lampStatus: {
    type: Object,
    default: () => {
      return {
        isOpen: false,
        brightValue: 0,
      };
    },
  },
  equipList: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const controlBtn = ref([]);
const setRef = (el) => {
  if (el) {
    if (!controlBtn.value.includes(el)) {
      controlBtn.value.push(el);
    }
  }
};

const lampList = ref(props.equipList || []);
const lampData = ref(props.lampStatus);

const allLampStatus = computed(() => store.state.taiguv1.lampSwitchStatus);

// const lampSwitchStatus = 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
//   }
// })
watch(
  () => props.lampStatus,
  (newVal, oldVal) => {
    if (!newVal || closeUpdate) {
      return;
    }
    // newVal.brightValue = customRound(newVal.brightValue, 20);
    lampData.value = { ...newVal };
  },
  { deep: true } // 添加深度监听
);
watch(
  () => props.equipList,
  (newVal, oldVal) => {
    if (!newVal || closeUpdate) {
      return;
    }
    compareStatus(newVal);
  },
  { deep: true }
);

// 对比和store中开关状态
const compareStatus = (data) => {
  lampList.value = data.map((item) => {
    const currentStatus = allLampStatus.value[item.id];
    let isOpen = item.brightValue !== 0;
    // 基础状态对象
    const baseStatus = {
      ...item,
      isOpen: isOpen,
    };

    if (!currentStatus) {
      return baseStatus;
    }

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

    // 如果有待处理的切换状态，使用该状态
    return {
      ...item,
      isOpen: currentStatus.lastSwitchStatus ?? isOpen,
    };
  });
};
// 整体开关
const handleSwitch = (type, value) => {
  lampData.value.isOpen = value;
  setLampStatus(type);
};

// 单个开关
const sigleLampChange = (type, source, all) => {
  if (type == 'isOpen') {
    store.dispatch('taiguv1/setLampStatus', {
      id: source.id,
      status: {
        loading: true,
        lastSwitchStatus: source.isOpen,
      },
    });
  }
  if (all == 'single') {
    const params = deviceControl.assemblyLampCommand(source[type], type, source);
    deviceControl.sendCommands(params);
  }
};
const setLampStatus = (type) => {
  if (type == 'isOpen') {
    store.dispatch('taiguv1/setLampStatus', {
      id: 'all',
      status: {
        loading: true,
        lastSwitchStatus: lampData.value.isOpen,
      },
    });
    lampList.value.forEach((item) => {
      item.isOpen = lampData.value.isOpen;
      sigleLampChange(type, item, 'all');
    });
  }else {
    lampData.value[type]=customRound(lampData.value[type],20)
  }
  const params = deviceControl.assemblyLampCommand(lampData.value[type], type, lampList.value);
  deviceControl.sendCommands(params, () => {
    debouncedSendEvent(false);
  });
};
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);
    });
  });
});

// 添加 touchstart 处理函数
const handleTouchStart = (event) => {
  const button = event.currentTarget;
  button.classList.add('active');
  setTimeout(() => {
    button.classList.remove('active');
  }, 200);
};
// 添加 onUnmounted 钩子
onUnmounted(() => {
  controlBtn.value.forEach((button) => {
    button.removeEventListener('touchstart', handleTouchStart);
  });
});
</script>
<style lang="scss" scoped>
.more-box {
  .light-more-top {
    display: flex;
    align-items: center;
    margin-bottom: 36px;
    .left {
      margin-right: 36px;
      .light-box {
        width: 110px;
        height: 110px;
        background: rgba(255, 255, 255, 0.4);
        border-radius: 50%;
        text-align: center;
        margin-right: 27px;
        img {
          width: 36px;
          height: 36px;
          margin: 0 auto;
          margin-top: 37px;
        }
      }
      .light-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);
      }
    }
  }
  .light-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 {
      width: 100%;
      height: 58px;
      padding: 2px;
      border-radius: 12px;
      background: var(--White-White-60, rgba(255, 255, 255, 0.6));
      margin-bottom: 12px;
    }
  }
  .divider {
    height: 24px;
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  .light-bottom {
    // margin-top: 36px;
    .item-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 300px;
      height: 68px;
      box-sizing: border-box;
      padding: 20px 24px;
      border-radius: 24px 24px 44px 24px;
      background: rgba(255, 255, 255, 0.2);
      box-shadow: 0px 10px 20px 0px rgba(0, 20, 40, 0.05);
      margin-bottom: 12px;
      .name {
        //styleName: Chi/Body Regular;
        font-family: PingFang SC;
        font-size: 14px;
        font-weight: 400;
        line-height: 19px;
        letter-spacing: 0.02em;
        color: rgba(0, 20, 40, 1);
      }
    }
    .light-box-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>
