<template>
	<view class="container">
	  <!-- 左侧分类导航 -->
	  <scroll-view class="left-nav" scroll-y :scroll-top="leftScrollTop">
		<view 
		  v-for="category in categories" 
		  :key="category.id"
		  class="nav-item"
		  :class="{ active: activeCategory === category.id }"
		  @click="handleNavClick(category.id)"
		>
		  {{ category.name }}
		</view>
	  </scroll-view>
  
	  <!-- 右侧商品列表 -->
	  <scroll-view 
		class="right-list" 
		scroll-y 
		:scroll-top="rightScrollTop"
		@scroll="handleRightScroll"
		:scroll-with-animation="true"
	  >
		<view 
		  v-for="category in categories" 
		  :key="category.id"
		  :id="'cat-' + category.id"
		  class="category-section"
		>
		  <view class="category-title">{{ category.name }}</view>
		  <view 
			v-for="item in category.items"
			:key="item.id"
			class="goods-item"
		  >
			<!-- 商品项内容 -->
			{{ item.name }}
		  </view>
		</view>
	  </scroll-view>
	</view>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue'
  
  interface Category {
	id: number
	name: string
	items: GoodsItem[]
  }
  
  interface GoodsItem {
	id: number
	name: string
	price: number
  }
  
  // 响应式数据
  const activeCategory = ref<number>(1)
  const leftScrollTop = ref<number>(0)
  const rightScrollTop = ref<number>(0)
  const categoryPositions = reactive<Map<number, number>>(new Map())
  const instance = getCurrentInstance()
  
  // 模拟数据
  const categories = reactive<Category[]>([
	{
	  id: 1,
	  name: '热销套餐',
	  items: [{
		id:1,
		name:'adf',
		price:1.1
	  },{
		id:2,
		name:'adf2',
		price:1.2
	  },{
		id:3,
		name:'adf3',
		price:1.13
	  },{
		id:4,
		name:'adf4',
		price:1.14
	  }], // 填充商品数据
	},
	{
	  id: 10,
	  name: '测试套餐',
	  items: [{
		id:11,
		name:'adf',
		price:1.1
	  },{
		id:22,
		name:'adf2',
		price:1.2
	  },{
		id:33,
		name:'adf3',
		price:1.13
	  },{
		id:44,
		name:'adf4',
		price:1.14
	  }], // 填充商品数据
	},
	{
	  id: 20,
	  name: '测试套餐2',
	  items: [{
		id:211,
		name:'adf',
		price:1.1
	  },{
		id:222,
		name:'adf2',
		price:1.2
	  },{
		id:233,
		name:'adf3',
		price:1.13
	  },{
		id:244,
		name:'adf4',
		price:1.14
	  }], // 填充商品数据
	},
	// 更多分类...
  ])
  
  // 点击左侧分类
  const handleNavClick = (categoryId: number) => {
	activeCategory.value = categoryId
	scrollToCategory(categoryId)
  }
  
  // 滚动到指定分类
  const scrollToCategory = (categoryId: number) => {
	const query = uni.createSelectorQuery()
	query.select(`#cat-${categoryId}`).boundingClientRect()
	query.exec((res) => {
	  if (res[0]) {
		// 获取目标位置并转换为px（假设设计稿750rpx）
		const position = res[0].top * (uni.upx2px(750) / 750)
		rightScrollTop.value = position
	  }
	})
  }
  
  // 右侧滚动事件
  const handleRightScroll = (e: any) => {
	const scrollTop = e.detail.scrollTop
	let currentCategoryId = 1
	
	// 查找当前显示的分类
	for (const [id, pos] of categoryPositions) {
	  if (pos <= scrollTop + 50) { // 50为缓冲值
		currentCategoryId = id
	  } else {
		break
	  }
	}
	
    console.log(categoryPositions, activeCategory, currentCategoryId)
	if (activeCategory.value !== currentCategoryId) {
	  activeCategory.value = currentCategoryId
	  adjustNavPosition(currentCategoryId)
	}
  }
  
  // 调整左侧导航位置
  const adjustNavPosition = (categoryId: number) => {
	const query = uni.createSelectorQuery().in(instance)
	query.select('.nav-item.active').boundingClientRect()
	query.exec((res) => {
	  if (res[0]) {
		const itemTop = res[0].top
		const viewHeight = uni.getSystemInfoSync().windowHeight
		if (itemTop < 0 || itemTop > viewHeight / 2) {
		  leftScrollTop.value = res[0].top
		}
	  }
	})
  }
  
  // 初始化分类位置信息
  const initCategoryPositions = async () => {
    console.log(categoryPositions, 'initCategoryPositions')
  try {
    // // 重置右侧滚动位置确保测量准确
    // rightScrollTop.value = 0
    // await nextTick()

    const query = uni.createSelectorQuery().in(instance)
    console.log(query, categories, categoryPositions, 'initCategoryPositions1')
    // 批量添加查询
    categories.forEach(category => {
        query.select('#cat-'+category.id).boundingClientRect((res) => {
          console.log(res, category, 'initCategoryPositions2')
        if (res) {
          // 存储相对于滚动容器顶部的绝对位置
          categoryPositions.set(category.id, res?.top)
        }
      }).exec();
    })

    // query.exec((res) => {
    //     console.log(res, categories, categoryPositions, 'initCategoryPositions2')
    //   categories.forEach((category, index) => {
    //     const rect = res[index]
    //     if (rect) {
    //       // 存储相对于滚动容器顶部的绝对位置
    //       categoryPositions.set(category.id, rect.top)
    //     }
    //   })
    // })
  } catch (e) {
    console.error('初始化分类位置失败:', e)
  }
}
  
  onMounted(() => {
	initCategoryPositions()
  })
  </script>
  
  <style lang="less">
  .container {
	display: flex;
	height: 100vh;
	background-color: #f8f8f8;
  }
  
  .left-nav {
	width: 160rpx;
	background-color: #fff;
	
	.nav-item {
	  height: 100rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-size: 28rpx;
	  color: #666;
	  border-left: 6rpx solid transparent;
	  
	  &.active {
		color: #ff4444;
		background-color: #f8f8f8;
		border-left-color: #ff4444;
	  }
	}
  }
  
  .right-list {
	flex: 1;
	padding: 20rpx 30rpx;
	
	.category-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  padding: 20rpx 0;
	}
	
	.goods-item {
		height:100px;
	  background-color: #fff;
	  margin-bottom: 20rpx;
	  padding: 20rpx;
	  border-radius: 12rpx;
	  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	}
  }
  </style>