<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 }"
          @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(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(child.id)
  ).length
}

// 检查一级分类是否全部选中
const isFirstLevelAllSelected = (firstLevelItem) => {
  if (!firstLevelItem.child || firstLevelItem.child.length === 0) {
    // 如果一级分类没有子分类，直接检查是否选中
    return selectedSecondLevel.value.includes(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 index = selectedSecondLevel.value.indexOf(child.id)

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

  emitSelectionChange()
}

// 获取所有选中的分类ID（根据规则：全选父类才包含父类ID，否则只包含子类ID）
const getSelectedIds = () => {
  const selectedIds = [...selectedSecondLevel.value]

  // 遍历所有一级分类，检查是否需要添加一级分类ID
  props.categoryList.forEach(firstLevel => {
    if (isFirstLevelAllSelected(firstLevel)) {
      // 如果全部子类选中，添加一级分类ID，并移除所有子分类ID
      selectedIds.push(firstLevel.id)
      // 移除该一级分类下的所有子分类ID
      if (firstLevel.child) {
        firstLevel.child.forEach(child => {
          const childIndex = selectedIds.indexOf(child.id)
          if (childIndex > -1) {
            selectedIds.splice(childIndex, 1)
          }
        })
      }
    }
  })

  return selectedIds
}

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

// 初始化选中状态
const initSelected = () => {
  selectedSecondLevel.value = [];
  currentFirstLevel.value = null;

  console.log('初始化选中IDs:', props.selectedIds);
  console.log('分类数据:', props.categoryList);

  if (!props.selectedIds || !Array.isArray(props.selectedIds) || props.selectedIds.length === 0) {
    // 设置默认显示
    const firstWithChildren = props.categoryList.find(item => item.child && item.child.length > 0);
    if (firstWithChildren) {
      currentFirstLevel.value = firstWithChildren.id;
    }
    return;
  }

  props.selectedIds.forEach(id => {
    // 确保id是字符串类型进行比较
    const idStr = String(id);

    // 检查是否是一级分类（表示该分类下的所有子分类都被选中）
    const firstLevel = props.categoryList.find(item => String(item.id) === idStr);
    if (firstLevel && firstLevel.child) {
      // 如果是一级分类且全选，选中所有子分类
      firstLevel.child.forEach(child => {
        const childIdStr = String(child.id);
        if (!selectedSecondLevel.value.includes(childIdStr)) {
          selectedSecondLevel.value.push(childIdStr);
        }
      });
    } else {
      // 如果是二级分类或没有子分类的一级分类，直接选中
      if (!selectedSecondLevel.value.includes(idStr)) {
        selectedSecondLevel.value.push(idStr);
      }
    }
  });

  console.log('初始化后的选中子分类:', selectedSecondLevel.value);

  // 设置默认显示的第一个有选中项的一级分类
  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 {
    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
  emitSelectionChange()
}
// 设置选中状态的方法
const setSelectedIds = (ids) => {
  selectedSecondLevel.value = [];
  currentFirstLevel.value = null;

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

  if (!ids || !Array.isArray(ids) || ids.length === 0) return;

  ids.forEach(id => {
    // 检查是否是一级分类（表示该分类下的所有子分类都被选中）
    const firstLevel = props.categoryList.find(item => item.id == id);
    if (firstLevel && firstLevel.child) {
      // 如果是一级分类且全选，选中所有子分类
      firstLevel.child.forEach(child => {
        if (!selectedSecondLevel.value.includes(child.id)) {
          selectedSecondLevel.value.push(child.id);
        }
      });
    } else {
      // 如果是二级分类或没有子分类的一级分类，直接选中
      // 确保id是字符串类型（因为分类ID可能是字符串或数字）
      const idStr = String(id);
      if (!selectedSecondLevel.value.includes(idStr)) {
        selectedSecondLevel.value.push(idStr);
      }
    }
  });

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

  // 设置默认显示的第一个有选中项的一级分类
  const firstWithSelected = props.categoryList.find(item => {
    if (item.child) {
      return item.child.some(child => selectedSecondLevel.value.includes(child.id));
    }
    return selectedSecondLevel.value.includes(item.id);
  });

  if (firstWithSelected) {
    currentFirstLevel.value = firstWithSelected.id;
  } else {
    // 如果没有选中项，显示第一个有子分类的一级分类
    const firstWithChildren = props.categoryList.find(item => item.child && item.child.length > 0);
    if (firstWithChildren) {
      currentFirstLevel.value = firstWithChildren.id;
    }
  }

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

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

watch(() => props.categoryList, (newVal) => {
  if (newVal && newVal.length > 0) {
    initSelected()
  }
})

// 暴露方法给父组件
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>