<template>
  <view class="category-selector">
    <!-- 一级分类 -->
    <scroll-view class="first-level" scroll-y>
      <view
          v-for="item in categoryList"
          :key="item.id"
          class="first-item"
          :class="{ active: currentFirstLevel === item.id || isFirstLevelAllSelected(item) }"
          @click="selectFirstLevel(item)"
      >
        <view class="item-content">
          <text class="category-name">{{ item.name }}</text>
          <text v-if="getSelectedChildCount(item) > 0" class="selected-count">
            ({{ getSelectedChildCount(item) }})
          </text>
        </view>
        <view class="checkbox">
          <text v-if="isFirstLevelAllSelected(item)" class="checked">✓</text>
          <text v-else-if="getSelectedChildCount(item) > 0" class="partial">-</text>
          <text v-else class="unchecked">○</text>
        </view>
      </view>
    </scroll-view>

    <!-- 二级分类 -->
    <scroll-view class="second-level" scroll-y v-if="hasSecondLevel">
      <view
          v-for="child in currentSecondLevel"
          :key="child.id"
          class="second-item"
          :class="{ active: selectedSecondLevel.includes(String(child.id)) }"
          @click="toggleSecondLevel(child)"
      >
        <text class="category-name">{{ child.name }}</text>
        <view class="checkbox">
          <text v-if="selectedSecondLevel.includes(child.id)" class="checked">✓</text>
          <text v-else class="unchecked">○</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import {ref, computed, watch} from 'vue'

const props = defineProps({
  categoryList: {
    type: Array,
    default: () => []
  },
  // 初始选中的分类ID数组
  selectedIds: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['change'])

// 当前显示的一级分类ID（用于右侧显示）
const currentFirstLevel = ref(null)
// 选中的二级分类ID
const selectedSecondLevel = ref([])

// 当前显示的二级分类列表
const currentSecondLevel = computed(() => {
  if (!currentFirstLevel.value) return []
  const parent = props.categoryList.find(item => item.id === currentFirstLevel.value)
  return parent?.child || []
})

// 是否有二级分类显示
const hasSecondLevel = computed(() => currentSecondLevel.value.length > 0)

// 获取一级分类下选中的子分类数量
const getSelectedChildCount = (firstLevelItem) => {
  if (!firstLevelItem.child) return 0
  return firstLevelItem.child.filter(child =>
      selectedSecondLevel.value.includes(String(child.id))  // 转为字符串
  ).length
}

// 检查一级分类是否全部选中
const isFirstLevelAllSelected = (firstLevelItem) => {
  if (!firstLevelItem.child || firstLevelItem.child.length === 0) {
    // 如果一级分类没有子分类，直接检查是否选中
    return selectedSecondLevel.value.includes(String(firstLevelItem.id))  // 转为字符串
  }

  const childCount = firstLevelItem.child.length
  const selectedCount = getSelectedChildCount(firstLevelItem)
  return childCount > 0 && selectedCount === childCount
}

// 选择一级分类（仅用于显示右侧内容）
const selectFirstLevel = (item) => {
  if (item.child && item.child.length > 0) {
    currentFirstLevel.value = item.id
  } else {
    currentFirstLevel.value = null
    // 如果没有子分类，点击一级分类相当于选择/取消选择
    toggleSecondLevel(item)
  }
}

// 切换二级分类选中状态
const toggleSecondLevel = (child) => {
  const childId = String(child.id)
  const index = selectedSecondLevel.value.indexOf(childId)

  if (index > -1) {
    // 取消选中
    selectedSecondLevel.value.splice(index, 1)
  } else {
    // 选中
    selectedSecondLevel.value.push(childId)
  }

  emitSelectionChange()
}

// 获取所有选中的分类ID（根据规则：全选父类才包含父类ID，否则只包含子类ID）
const getSelectedIds = () => {
  console.log('当前选中状态:', {
    allCategories: props.categoryList,
    selectedChildren: selectedSecondLevel.value
  })

  const result = []

  // 遍历一级分类
  for (const category of props.categoryList) {
    const parentId = String(category.id)

    if (category.child && category.child.length > 0) {
      // 有子分类的情况
      const allChildIds = category.child.map(child => String(child.id))
      const isAllSelected = allChildIds.every(id =>
          selectedSecondLevel.value.includes(id)
      )

      if (isAllSelected) {
        // 全选子类，只添加父类ID
        result.push(parentId)
      } else {
        // 非全选，添加选中的子类
        allChildIds.forEach(id => {
          if (selectedSecondLevel.value.includes(id)) {
            result.push(id)
          }
        })
      }
    } else {
      // 没有子分类，直接检查是否选中
      if (selectedSecondLevel.value.includes(parentId)) {
        result.push(parentId)
      }
    }
  }

  console.log('计算出的选中IDs:', result)
  return result
}

// 发射选择变化事件
const emitSelectionChange = () => {
  const selectedIds = getSelectedIds()
  emit('change', {
    selectedIds,
    secondLevel: selectedSecondLevel.value
  })
}
// 统一设置选中状态的方法
const setSelectedState = (ids) => {
  selectedSecondLevel.value = []
  currentFirstLevel.value = null

  console.log('设置选中IDs:', ids)
  console.log('可用分类数据:', props.categoryList)

  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    initDefaultView()
    return
  }

  // 将传入的ID统一转换为字符串
  const stringIds = ids.map(id => String(id))

  // 首先处理所有选中的分类
  stringIds.forEach(id => {
    let found = false

    // 先查找二级分类
    for (const parent of props.categoryList) {
      if (parent.child) {
        const child = parent.child.find(c => String(c.id) === id)
        if (child) {
          if (!selectedSecondLevel.value.includes(id)) {
            selectedSecondLevel.value.push(id)
          }
          found = true
          break
        }
      }
    }

    // 如果没有找到对应的二级分类，检查是否是一级分类
    if (!found) {
      const firstLevel = props.categoryList.find(item => String(item.id) === id)
      if (firstLevel) {
        // 如果是一级分类，检查是否有子分类
        if (firstLevel.child && firstLevel.child.length > 0) {
          // 有子分类的一级分类：选中所有子分类
          firstLevel.child.forEach(child => {
            const childId = String(child.id)
            if (!selectedSecondLevel.value.includes(childId)) {
              selectedSecondLevel.value.push(childId)
            }
          })
        } else {
          // 没有子分类的一级分类：直接选中
          if (!selectedSecondLevel.value.includes(id)) {
            selectedSecondLevel.value.push(id)
          }
        }
      }
    }
  })

  console.log('设置后的选中子分类:', selectedSecondLevel.value)

  // 设置当前显示的选中项
  setCurrentView()

  // 触发选择变化事件
  emitSelectionChange()
}

// 设置当前显示视图
const setCurrentView = () => {
  // 查找第一个有选中项的一级分类
  const firstWithSelected = props.categoryList.find(item => {
    if (item.child) {
      return item.child.some(child =>
          selectedSecondLevel.value.includes(String(child.id))  // 转为字符串
      )
    }
    return selectedSecondLevel.value.includes(String(item.id))  // 转为字符串
  })

  if (firstWithSelected) {
    currentFirstLevel.value = firstWithSelected.id
  } else {
    initDefaultView()
  }
}

// 初始化默认视图
const initDefaultView = () => {
  const firstWithChildren = props.categoryList.find(item => item.child && item.child.length > 0)
  if (firstWithChildren) {
    currentFirstLevel.value = firstWithChildren.id
  }
}

// 清空所有选择
const clearSelection = () => {
  selectedSecondLevel.value = []
  currentFirstLevel.value = null
  initDefaultView()
  emitSelectionChange()
}

// 设置选中状态的方法（暴露给父组件）
const setSelectedIds = (ids) => {
  setSelectedState(ids)
}

// 监听props变化
watch(() => props.selectedIds, (newVal) => {
  console.log('props.selectedIds 变化:', newVal)
  setSelectedState(newVal)
}, {immediate: true})

watch(() => props.categoryList, (newVal) => {
  console.log('分类数据变化:', newVal)
  if (newVal && newVal.length > 0) {
    // 重新应用选中状态
    setSelectedState(props.selectedIds)
  }
})

// 暴露方法给父组件
defineExpose({
  getSelectedIds,
  clearSelection,
  setSelectedIds
})
</script>

<style scoped>
.category-selector {
  display: flex;
  height: 600rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
}

.first-level {
  width: 40%;
  background-color: #f8f8f8;
}

.second-level {
  width: 60%;
  background-color: #fff;
}

.first-item, .second-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  cursor: pointer;
}

.first-item.active {
  background-color: #fff;
  font-weight: bold;
  color: #F8C008;
}

.second-item.active {
  background-color: #f0f8ff;
  color: #F8C008;
}

.item-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.category-name {
  font-size: 28rpx;
}

.selected-count {
  font-size: 24rpx;
  color: #F8C008;
  margin-left: 10rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checked {
  color: #F8C008;
  font-weight: bold;
}

.partial {
  color: #FFA500; /* 橙色表示部分选中 */
  font-weight: bold;
}

.unchecked {
  color: #ccc;
}
</style>