<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: selectedFirstLevel.includes(item.id) }"
          @click="toggleFirstLevel(item)"
      >
        <view class="item-content">
<!--          <image-->
<!--              v-if="item.extra"-->
<!--              :src="item.extra"-->
<!--              class="category-icon"-->
<!--              mode="aspectFit"-->
<!--          />-->
          <text class="category-name">{{ item.name }}</text>
        </view>
        <view class="checkbox">
          <text v-if="selectedFirstLevel.includes(item.id)" class="checked">✓</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(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 selectedFirstLevel = ref([])
// 选中的二级分类ID
const selectedSecondLevel = ref([])

// 当前显示二级分类的一级分类
const currentFirstLevel = ref(null)
// 当前显示的二级分类列表
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 initSelected = () => {
  selectedFirstLevel.value = []
  selectedSecondLevel.value = []

  props.selectedIds.forEach(id => {
    // 检查是否是一级分类
    const firstLevel = props.categoryList.find(item => item.id === id)
    if (firstLevel) {
      selectedFirstLevel.value.push(id)
    }

    // 检查是否是二级分类
    for (const parent of props.categoryList) {
      if (parent.child) {
        const secondLevel = parent.child.find(child => child.id === id)
        if (secondLevel) {
          selectedSecondLevel.value.push(id)
          // 如果选中了二级分类，自动选中对应的一级分类
          if (!selectedFirstLevel.value.includes(parent.id)) {
            selectedFirstLevel.value.push(parent.id)
          }
        }
      }
    }
  })
}

// 切换一级分类选中状态
const toggleFirstLevel = (item) => {
  const index = selectedFirstLevel.value.indexOf(item.id)

  if (index > -1) {
    // 取消选中
    selectedFirstLevel.value.splice(index, 1)
    // 如果取消选中一级分类，同时取消选中其下的所有二级分类
    if (item.child) {
      item.child.forEach(child => {
        const childIndex = selectedSecondLevel.value.indexOf(child.id)
        if (childIndex > -1) {
          selectedSecondLevel.value.splice(childIndex, 1)
        }
      })
    }
  } else {
    // 选中
    selectedFirstLevel.value.push(item.id)
  }

  // 设置当前显示的一级分类
  if (item.child && item.child.length > 0) {
    currentFirstLevel.value = item.id
  } else {
    currentFirstLevel.value = null
  }

  emitSelectionChange()
}

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

  if (index > -1) {
    selectedSecondLevel.value.splice(index, 1)
  } else {
    selectedSecondLevel.value.push(child.id)
    // 如果选中二级分类，确保对应的一级分类也被选中
    const parentId = getParentId(child.id)
    if (parentId && !selectedFirstLevel.value.includes(parentId)) {
      selectedFirstLevel.value.push(parentId)
    }
  }

  emitSelectionChange()
}

// 根据二级分类ID获取一级分类ID
const getParentId = (childId) => {
  for (const parent of props.categoryList) {
    if (parent.child) {
      const child = parent.child.find(item => item.id === childId)
      if (child) return parent.id
    }
  }
  return null
}

// 发射选择变化事件
const emitSelectionChange = () => {
  const selectedIds = [...selectedFirstLevel.value, ...selectedSecondLevel.value]
  emit('change', {
    selectedIds,
    firstLevel: selectedFirstLevel.value,
    secondLevel: selectedSecondLevel.value
  })
}

// 获取所有选中的分类ID
const getSelectedIds = () => {
  return [...selectedFirstLevel.value, ...selectedSecondLevel.value]
}

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

// 监听props变化
watch(() => props.selectedIds, (newVal) => {
  initSelected()
})

watch(() => props.categoryList, (newVal) => {
  initSelected()
})

// 初始化
initSelected()

// 暴露方法给父组件
defineExpose({
  getSelectedIds,
  clearSelection
})
</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;
}

.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-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
}

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

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

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

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