<template>
	<view class="category-box box">
		<swiper
			:indicator-dots="false"
			:current="current"
			:style="{ height: swiperHeight + 'rpx' }"
			@change="onSwiperChange"
			class="swiper"
		>
			<swiper-item v-for="(page, pageIndex) in pageList" :key="pageIndex">
				<view class="category-list">
					<view class="category-item" v-for="(item, index) in page" :key="index" @click="handleClick(item)">
						<image :src="item.dictImage" mode="aspectFill"></image>
						<view>{{ item.dictLabel || '' }}</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<view v-if="list.length > perPage" class="indicator">
			<view
				class="indicator-bar"
				:class="{ active: pageIndex === current }"
				v-for="(page, pageIndex) in pageList"
				:key="pageIndex"
			></view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'recommendCategory',
		props: {
			list: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				current: 0
			}
		},
		computed: {
			perPage() {
				return 8
			},
			isSingleRow() {
				return this.pageList.length > 0 && this.pageList.every(page => page.length <= 4)
			},
			swiperHeight() {
				return this.isSingleRow ? 190 : 364
			},
			pageList() {
				const pages = []
				for (let i = 0; i < this.list.length; i += this.perPage) {
					pages.push(this.list.slice(i, i + this.perPage))
				}
				return pages
			}
		},
		methods: {
			onSwiperChange(e) {
				this.current = e.detail.current
			},
			handleClick(item) {
				if (item.dictValue) {
					uni.navigateTo({
						url: '/pages_shopping/home/productList?tuiCateId=' + item.dictValue + '&title=' + encodeURIComponent(item.dictLabel || '')
					})
				} else if (item.page) {
					uni.navigateTo({
						url: item.page
					})
				}
				this.$emit('click', item)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		background: #FFFFFF;
		border-radius: 16rpx;
		margin: 24rpx;
		box-sizing: border-box;
		padding: 26rpx 0 6rpx 0;
	}

	.swiper {
		height: 364rpx;
	}

	.category-list {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		flex-wrap: wrap;
	}

	.category-item {
		width: 25%;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #222222;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;

		image {
			width: 104rpx;
			height: 104rpx;
			margin-bottom: 26rpx;
			border-radius: 16rpx;
		}
	}

	.indicator {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 6rpx;

		.indicator-bar {
			width: 40rpx;
			height: 4rpx;
			border-radius: 2rpx;
			background: rgba(37, 131, 235, 0.3);
			margin: 0 6rpx;
			transition: background 0.3s;

			&.active {
				background: #2583EB;
			}
		}
	}
</style>
