<script lang="ts" setup>
import { deepClone, getImageFullPath } from '@/utils'
import { charge_toolbar_list } from '../config'

const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
})
const emits = defineEmits(['change'])
const dataList = ref(charge_toolbar_list)
const debounceTimer = ref<NodeJS.Timeout | null>(null)
const selectData = reactive({
  sliderValue: [0, 100],
})
const isClick = ref(false) // 限位开关（避免点击事件触发滑动事件）

function handleClick(item: any, index: number) {
  isClick.value = true
  dataList.value[index].active = !item.active
  dataList.value.forEach((item, idx) => {
    if (idx !== index) {
      item.active = false
    }
  })
  selectData.sliderValue = item.active ? item.section : [0, 100]
  const type = dataList.value.find(item => item.active)

  emits('change', {
    chargeType: type ? type.type : 'all',
    value: dataList.value[index].active ? deepClone(item.section) : [0, 100],
  })
  setTimeout(() => {
    isClick.value = false
  }, 100)
}

function handleChange(val: any) {
  selectData.sliderValue = val

  if (isClick.value) {
    return
  }

  // 清除之前的定时器，实现防抖
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
  }

  // 设置新的定时器，延迟 300ms 执行后续逻辑
  debounceTimer.value = setTimeout(() => {
    dataList.value.forEach((item) => {
      item.active = false
    })

    emits('change', {
      chargeType: 'all',
      value: val,
    })
  }, 300) // 延迟时间可根据业务调整，如 200-500ms
}

// 设置不同类别车的数量
function setCarNum(carList: any[]) {
  // 如果 carList 不存在或为空，重置 dataList 的 num 为 0
  if (!carList || carList.length === 0) {
    dataList.value.forEach((item) => {
      item.num = 0
    })
    return
  }

  let lowCount = 0
  let mediumCount = 0
  let highCount = 0
  let offlineCount = 0

  // 统计各类车辆数量
  carList.forEach((car) => {
    if (!car.online) {
      offlineCount++
    }
    else {
      const soc = car.soc ?? 0 // 使用空值合并操作符更安全
      if (soc >= dataList.value[0].section[0] && soc <= dataList.value[0].section[1]) {
        lowCount++
      }
      else if (soc >= dataList.value[1].section[0] && soc <= dataList.value[1].section[1]) {
        mediumCount++
      }
      else if (soc >= dataList.value[2].section[0] && soc <= dataList.value[2].section[1]) {
        highCount++
      }
    }
  })

  // 更新 dataList 中的 num 字段
  dataList.value.forEach((item) => {
    switch (item.name) {
      case '低电量':
        item.num = lowCount
        break
      case '中电量':
        item.num = mediumCount
        break
      case '高电量':
        item.num = highCount
        break
      case '离线':
        item.num = offlineCount
        break
      default:
        break
    }
  })
}

watch(() => props.list, (newVal) => {
  setCarNum(newVal)
}, { immediate: true })

onUnmounted(() => {
  if (debounceTimer.value) {
    clearTimeout(debounceTimer.value)
  }
})
</script>

<template>
  <view
    class="container"
    @touchmove.stop
  >
    <!-- 数据展示 -->
    <view class="data_wrapper">
      <view
        v-for="(item, index) in dataList"
        :key="index"
        class="data_item"
        :style="{
          color: item.color,
          backgroundColor: item.active ? item.activeBgColor : '',
          borderColor: item.active ? `${item.activeColor}` : 'transparent',
        }"
        @click="handleClick(item, index)"
      >
        <view class="item_icon">
          <uv-image :src="getImageFullPath(item.icon)" mode="scaleToFill" width="100%" height="100%" />
        </view>
        <view class="item_name">
          {{ item.name }}
        </view>
        <view class="item_num">
          {{ item.num }}
        </view>
      </view>
    </view>
    <!-- 数据筛选 -->
    <view class="select_wrapper">
      <view class="select_tips">
        只看电量
      </view>
      <view class="select_slider">
        <llt-slider-range
          :model-value="selectData.sliderValue"
          @change="handleChange"
        />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container {
  width: calc(100% - 40rpx);
  padding: 20rpx;
  background-color: white;
  border-radius: 15rpx;

  .data_wrapper {
    width: 100%;
    display: flex;
    justify-content: space-between;
    gap: 20rpx;

    .data_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      flex: 1; /* 关键！让每个子项平均分占空间 */
      padding: 5rpx; /* 可选：增加内边距 */
      border: 1px solid transparent;
      border-radius: 10rpx;
      transition: all 0.1s ease-in-out;

      .item_icon {
        width: 80rpx;
        height: 80rpx;
        overflow: hidden;
      }

      .item_name {
        font-family: PingFangSC-Regular;
        font-size: 24rpx;
        color: #666666;
        font-weight: 400;
      }

      .item_num {
        font-family: PingFangSC-Regular;
        font-size: 28rpx;
        color: #0d162a;
        font-weight: 400;
      }
    }
  }

  .select_wrapper {
    margin-top: 20rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .select_tips {
      font-size: 28rpx;
      color: #8e8e8e;
    }

    .select_slider {
      width: 80%;
    }

    .switch_wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      font-size: 26rpx;
      padding: 10rpx 20rpx;
      border-radius: 20px;
      background-color: #e6f7fe;
      color: #5495eb;
    }
  }
}
</style>
