<template>
	<view class="category-container">
		<!-- 头部搜索与导航 (1:1 还原首页样式) -->
		<view class="header">
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
			<view class="search-section">
				<view class="search-bar-wrap">
					<text class="search-icon">🔍</text>
					<input class="search-input" placeholder="输入关键词或粘贴商品标题" placeholder-class="placeholder-style" />
					<view class="search-btn-red">搜索</view>
				</view>
				<image class="search-right-ad" src="https://img.bc.haodanku.com/cms_web/1651735687" mode="aspectFit" @click="goHome"></image>
			</view>
			<scroll-view scroll-x class="nav-scroll" :show-scrollbar="false">
				<view class="nav-item" :class="{ 'active': currentCatId == item.cat_id }" v-for="(item, index) in navList" :key="index" @click="switchCategory(item)">
					<text class="nav-text">{{ item.name }}</text>
					<view class="nav-line" v-if="currentCatId == item.cat_id"></view>
				</view>
			</scroll-view>
		</view>

		<scroll-view scroll-y class="main-content" @scrolltolower="loadMore">
			<!-- 占位符适配固定头部 -->
			<view class="header-placeholder" :style="{ height: (statusBarHeight + 90) + 'px' }"></view>
			
			<!-- 子分类金刚区 (支持翻页) -->
			<view class="sub-grid-wrap" v-if="subCategories.length > 0">
				<swiper class="sub-swiper" :duration="300" @change="onSubSwiperChange">
					<swiper-item v-for="(group, gIdx) in groupedSubCategories" :key="gIdx">
						<view class="sub-grid">
							<view class="sub-item" v-for="(sub, idx) in group" :key="idx" @click="selectSub(sub)">
								<image class="sub-icon" :src="sub.img_url" mode="aspectFit"></image>
								<text class="sub-text">{{ sub.cate_name.trim() }}</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
				<!-- 进度条指示器 (仅在多页时显示) -->
				<view class="swiper-dot-wrap" v-if="groupedSubCategories.length > 1">
					<view class="swiper-dot-bar">
						<view class="swiper-dot-active" :style="{ left: dotLeft + '%' }"></view>
					</view>
				</view>
			</view>

			<!-- 排序筛选栏 -->
			<view class="filter-bar">
				<view class="filter-item" :class="{ 'active': sortType === 1 }" @click="changeSort(1)">综合</view>
				<view class="filter-item" :class="{ 'active': sortType === 2 }" @click="changeSort(2)">销量</view>
				<view class="filter-item" :class="{ 'active': sortType === 3 }" @click="changeSort(3)">
					券后价
					<view class="price-arrows">
						<text class="up" :class="{ 'hl': sortType === 3 && priceOrder === 'asc' }">▲</text>
						<text class="down" :class="{ 'hl': sortType === 3 && priceOrder === 'desc' }">▼</text>
					</view>
				</view>
			</view>

			<!-- 商品列表 (同步 category_detail 的横向高保真风格) -->
			<view class="goods-list">
				<view class="goods-item" v-for="(goods, idx) in goodsList" :key="idx" @click="goToDetail(goods.id)">
					<view class="g-img-left">
						<image class="goods-img" :src="goods.image" mode="aspectFill"></image>
					</view>
					<view class="goods-info">
						<view class="goods-title-row">
							<image src="https://img-haodanku-com.cdn.fudaiapp.com/FlyOSTvjC3LjrkUoJ0NPxx1qnGz4" class="platform-icon"></image>
							<text class="title-text">{{ goods.title }}</text>
						</view>
						<!-- 标签组 -->
						<view class="labels-row" v-if="goods.labels && goods.labels.length > 0">
							<text class="label-tag" v-for="(label, lIdx) in goods.labels.slice(0, 2)" :key="lIdx">{{ label }}</text>
						</view>
						
						<view class="goods-price-section">
							<view class="price-main">
								<text class="price-tip">{{ goods.couponValue > 0 ? '券后' : '抢购价' }}</text>
								<text class="price-symbol">￥</text>
								<text class="price-integer">{{ goods.finalPrice }}</text>
								<view class="coupon-box" v-if="goods.couponValue > 0">
									<text class="coupon-icon">券</text>
									<text class="coupon-txt">{{ goods.couponValue }}元</text>
								</view>
							</view>
						</view>

						<view class="goods-bottom-info">
							<text class="sales">已售{{ goods.sales }}件</text>
							<text class="split-line">|</text>
							<text class="shop-name">店铺：{{ goods.shopName }}</text>
						</view>
					</view>
				</view>
			</view>

			<view class="loading-more" v-if="loading">加载中...</view>
			<view class="loading-more" v-else-if="goodsList.length === 0">该分类暂无商品</view>
			<view class="loading-more" v-else>-- 到底啦 --</view>
			
			<view class="footer-placeholder"></view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				statusBarHeight: 44,
				currentCatId: 0,
				currentSonId: 0,
				navList: [],
				subCategories: [],
				goodsList: [],
				page: 1,
				sortType: 1,
				priceOrder: 'desc',
				loading: false,
				finished: false,
				subCurrentIndex: 0
			}
		},
		computed: {
			groupedSubCategories() {
				const groups = [];
				for (let i = 0; i < this.subCategories.length; i += 10) {
					groups.push(this.subCategories.slice(i, i + 10));
				}
				return groups;
			},
			dotLeft() {
				if (this.groupedSubCategories.length <= 1) return 0;
				const maxIndex = this.groupedSubCategories.length - 1;
				return (this.subCurrentIndex / maxIndex) * 50; // 50% 是滑块可移动的最大范围（取决于样式）
			}
		},
		onLoad(options) {
			this.currentCatId = options.cat_id || 1;
			const sysInfo = uni.getSystemInfoSync();
			this.statusBarHeight = sysInfo.statusBarHeight || 44;
			
			this.getCategoryTabs();
			this.getProducts(true);
		},
		methods: {
			goHome() {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			getCategoryTabs() {
				uni.request({
					url: 'https://api.cmspro.haodanku.com/index/superCategory?is_get_second=1&cid=qOstW90',
					success: (res) => {
						if (res.data && res.data.code === 200) {
							// 映射为与首页一致的 navList 结构
							const categories = res.data.data.map(item => ({
								name: item.name,
								cat_id: item.cat_id,
								second: item.second || []
							}));
							this.navList = [{ name: '首页', cat_id: 0 }, { name: '推荐', cat_id: -1 }, ...categories];
							
							const currentCat = this.navList.find(c => c.cat_id == this.currentCatId);
							if (currentCat && currentCat.second) {
								this.subCategories = currentCat.second;
							}
						}
					}
				});
			},
			getProducts(refresh = false) {
				if (refresh) {
					this.page = 1;
					this.finished = false;
					this.goodsList = [];
				}
				if (this.loading || this.finished) return;
				
				this.loading = true;
				// 构建 allItemList 排序参数 (0:综合, 3:销量, 8:券后价低到高, 9:券后价高到低)
				let sortParam = 0;
				if (this.sortType === 2) {
					sortParam = 3;
				} else if (this.sortType === 3) {
					sortParam = this.priceOrder === 'asc' ? 8 : 9;
				}

				uni.request({
					url: `https://api.cmspro.haodanku.com/find/allItemList?category_id=${this.currentCatId}&page=${this.page}&sort=${sortParam}&page_size=20&cid=qOstW90`,
					success: (res) => {
						if (res.data && res.data.code === 200 && res.data.data && res.data.data.item_info) {
							const list = res.data.data.item_info.map(item => ({
								id: item.id,
								image: item.itempic,
								title: item.itemshorttitle && item.itemshorttitle.length > 17 ? item.itemshorttitle.substring(0, 17) + '...' : item.itemshorttitle,
								finalPrice: item.itemendprice,
								couponValue: item.couponmoney || 0,
								sales: item.itemsale >= 10000 ? (item.itemsale / 10000).toFixed(1) + '万' : item.itemsale,
								shopType: item.shoptype === 'B' ? '天猫' : '淘宝',
								shopName: item.shopname,
								labels: item.label || []
							}));
							
							if (list.length === 0) {
								this.finished = true;
							} else {
								// 翻页添加数据
								this.goodsList = [...this.goodsList, ...list];
								this.page++;
								// 如果返回的数量小于请求的数量，说明已到最后一页
								if (list.length < 20) {
									this.finished = true;
								}
							}
						} else {
							this.finished = true;
						}
					},
					complete: () => {
						this.loading = false;
					}
				});
			},
			switchCategory(item) {
				if (item.cat_id <= 0) {
					this.goHome();
					return;
				}
				if (this.currentCatId == item.cat_id) return;
				
				this.currentCatId = item.cat_id;
				this.currentSonId = 0;
				this.subCategories = item.second || [];
				this.getProducts(true);
			},
			onSubSwiperChange(e) {
				this.subCurrentIndex = e.detail.current;
			},
			selectSub(sub) {
				const name = encodeURIComponent(sub.cate_name.trim());
				const catId = this.currentCatId;
				const secondCat = sub.second_category;
				
				uni.navigateTo({
					url: `/pages/category/category_detail?cate_name=${name}&id=${catId}&second_category=${secondCat}`
				});
			},
			changeSort(type) {
				if (type === 3 && this.sortType === 3) {
					this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc';
				} else {
					this.sortType = type;
					if (type === 3) this.priceOrder = 'desc';
				}
				this.getProducts(true);
			},
			loadMore() {
				this.getProducts();
			},
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/detail/detail?id=${id}`
				});
			}
		}
	}
</script>

<style scoped>
	.category-container {
		width: 100%;
		height: 100vh;
		background-color: #f5f6f8;
		display: flex;
		flex-direction: column;
	}

	/* 头部区域 (与首页 1:1) */
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		z-index: 100;
		padding-bottom: 10rpx;
	}

	.search-section {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		justify-content: space-between;
	}

	.search-bar-wrap {
		flex: 1;
		height: 72rpx;
		background: #ffffff;
		border: 2rpx solid #ff416c;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding-left: 30rpx;
		padding-right: 4rpx;
		position: relative;
	}

	.search-icon {
		font-size: 30rpx;
		color: #ff416c;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 26rpx;
		color: #333;
	}

	.search-btn-red {
		width: 130rpx;
		height: 64rpx;
		background: linear-gradient(to right, #ff715a, #ff416c);
		color: #ffffff;
		font-size: 28rpx;
		font-weight: bold;
		border-radius: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-right-ad {
		width: 100rpx;
		height: 80rpx;
		margin-left: 20rpx;
	}

	.nav-scroll {
		white-space: nowrap;
		padding: 0 20rpx;
	}

	.nav-item {
		display: inline-block;
		padding: 10rpx 30rpx;
		position: relative;
	}

	.nav-text {
		font-size: 30rpx;
		color: #333;
		transition: all 0.3s;
	}

	.nav-item.active .nav-text {
		color: #ff416c;
		font-size: 34rpx;
		font-weight: bold;
	}

	.nav-line {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 6rpx;
		background-color: #ff416c;
		border-radius: 6rpx;
	}

	.main-content {
		flex: 1;
		height: 100%;
	}

	.header-placeholder {
		width: 100%;
	}

	/* 子分类金刚区 */
	.sub-grid-wrap {
		background: #ffffff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 20rpx 0;
	}

	.sub-swiper {
		height: 300rpx; /* 适应两行 2x5 布局 */
	}

	.sub-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 0 10rpx;
	}

	.sub-item {
		width: 20%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.sub-icon {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 10rpx;
	}

	.sub-text {
		font-size: 22rpx;
		color: #333;
	}

	.swiper-dot-wrap {
		display: flex;
		justify-content: center;
		margin-top: 10rpx;
	}

	.swiper-dot-bar {
		width: 60rpx;
		height: 4rpx;
		background: #eeeeee;
		border-radius: 2rpx;
		position: relative;
		overflow: hidden;
	}

	.swiper-dot-active {
		position: absolute;
		top: 0;
		width: 30rpx;
		height: 4rpx;
		background: #ff416c;
		border-radius: 2rpx;
		transition: left 0.3s;
	}

	/* 筛选栏 */
	.filter-bar {
		display: flex;
		background: #ffffff;
		height: 88rpx;
		align-items: center;
		border-bottom: 1rpx solid #f1f1f1;
		position: sticky;
		top: 0;
		z-index: 90;
	}

	.filter-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.filter-item.active {
		color: #ff416c;
		font-weight: bold;
	}

	.price-arrows {
		display: flex;
		flex-direction: column;
		margin-left: 6rpx;
		line-height: 1;
	}

	.price-arrows text {
		font-size: 16rpx;
		color: #ccc;
	}

	.price-arrows text.hl {
		color: #ff416c;
	}

	/* 商品列表 */
	.goods-list {
		padding: 0;
		background: #ffffff;
	}

	.goods-item {
		display: flex;
		padding: 24rpx;
		border-bottom: 1rpx solid #f8f8f8;
		background: #ffffff;
	}

	.g-img-left {
		flex-shrink: 0;
		width: 240rpx;
		height: 240rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background: #f0f0f0;
	}

	.goods-img {
		width: 100%;
		height: 100%;
	}

	.goods-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 4rpx 0;
	}

	.goods-title-row {
		display: flex;
		align-items: center;
		line-height: 1.4;
	}

	.platform-icon {
		width: 26rpx;
		height: 26rpx;
		margin-right: 8rpx;
		flex-shrink: 0;
	}

	.title-text {
		color: #333333;
		font-size: 24rpx;
		font-weight: bold;
		width: 100%;
		box-sizing: border-box;
		padding-left: 6rpx;
		display: inline-block;
		line-height: 29rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.labels-row {
		display: flex;
		flex-wrap: wrap;
		margin-top: 12rpx;
	}

	.label-tag {
		font-size: 20rpx;
		color: #ff416c;
		background: #fff5f7;
		border: 1rpx solid #ffd6de;
		padding: 2rpx 12rpx;
		border-radius: 20rpx;
		margin-right: 12rpx;
		margin-bottom: 8rpx;
	}

	.goods-price-section {
		margin-top: auto;
		padding-bottom: 8rpx;
	}

	.price-main {
		display: flex;
		align-items: baseline;
	}

	.price-tip {
		font-size: 24rpx;
		color: #ff416c;
		margin-right: 4rpx;
	}

	.price-symbol {
		font-size: 24rpx;
		color: #ff416c;
		font-weight: bold;
	}

	.price-integer {
		font-size: 40rpx;
		color: #ff416c;
		font-weight: bold;
		margin-right: 12rpx;
	}

	.coupon-box {
		display: flex;
		align-items: center;
		background: #ff416c;
		border-radius: 4rpx;
		overflow: hidden;
		height: 32rpx;
	}

	.coupon-icon {
		font-size: 20rpx;
		color: #ffffff;
		background: rgba(255,255,255,0.2);
		padding: 0 6rpx;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.coupon-txt {
		font-size: 20rpx;
		color: #ffffff;
		padding: 0 8rpx;
	}

	.goods-bottom-info {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.split-line {
		margin: 0 10rpx;
		color: #eee;
	}

	.loading-more {
		text-align: center;
		padding: 40rpx 0;
		font-size: 24rpx;
		color: #999;
	}

	.footer-placeholder {
		height: 40rpx;
	}
</style>
