<!-- 商品的详情页 -->
<template>
	<view class="">
		<u-navbar leftIconColor="#888888" autoBack :bgColor="bgColor" :title="navTitle"
			titleStyle="color: #000000"></u-navbar>
		<!-- 添加动画小球 -->
		<view class="cart-ball" :class="{ active: ballShow }" :style="ballStyle" v-show="ballShow">
			<view class="inner"></view>
		</view>
		<!-- 产品主图轮播 -->
		<swiper class="swiper" :style="{height: '750rpx'}" :indicator-dots="true" :autoplay="true" :interval="3500"
			@change="e => (currentNum = e.detail.current)">
			<swiper-item v-for="(item, index) in imageList" :key="index">
				<image :src="item" mode="aspectFill" style="width: 100%; height: 100%;"></image>
			</swiper-item>
		</swiper>

		<!-- 商品信息 -->
		<view class="product-info">
			<view class="product-main">
				<!-- 价格区域 -->
				<view class="price-section">
					<text class="current-price">￥{{detail.price}}</text>
					<text class="price-suffix" v-if="skuNum != 0">起</text>
					<text class="original-price">￥{{detail.originalPrice}}</text>
				</view>

				<!-- 商品名称 -->
				<text class="product-name">{{detail.name}}</text>

				<!-- 销量库存信息 -->
				<view class="product-stats">
					<text class="stat-item">销量 {{detail.salesTotal}}件</text>
					<view class="divider"></view>
					<text class="stat-item">剩余 {{detail.stock}}件</text>
				</view>
			</view>

			<!-- 分享按钮 -->
			<view class="share-section">
				<button open-type="share" class="share-btn">
					<u-icon name="share" size="22" label="分享" labelPos="bottom" labelSize="12"></u-icon>
				</button>
			</view>
		</view>

		<!-- 商品属性 -->
		<view class="productStats">
			<view class="mar-b-30">
				<text class="font28">服务</text>
				<text class="font28 font-666 mar-lr-32 flex-1">快递:免运费</text>
			</view>
			<view @click="skuPopUp">
				<view class="mar-b-20 flex-items flex-sp-between">
					<view>
						<text class="font28">选择</text>
						<text class="font28 font-666 mar-lr-32 flex-1">规格</text>
					</view>
					<view class="mar-r-8">
						<view class="flex-items">
							<view class="guige">
								共{{skuNum}}种规格可选
							</view>
							<uni-icons color="#d0d7df" type="right" size="20"></uni-icons>
						</view>
					</view>
				</view>
				<view class="mar-b-30 mar-lr-64 flex-items">
					<view v-for="(item,index) in detail.sku">
						<image class="skuImg" :src="item.skuImage" mode="aspectFit"></image>
					</view>
				</view>
			</view>

			<view>
				<text class="font28">参数</text>
				<text class="font28 font-666 mar-lr-32 flex-1">{{detail.parameter}}</text>
			</view>
		</view>

		<!-- 评价 -->
		<view class="productStats" @click="goScore">
			<view class="flex-items flex-sp-between">
				<view class="font30 font-bold">
					评价 ({{scoreList.length}})
				</view>
				<view class="mar-r-16">
					<uni-icons color="#d0d7df" type="right" size="20"></uni-icons>
				</view>
			</view>

			<view class="mar-b-30 mar-t-40" v-for="(item,index) in scoreList" :key="index">
				<view class="flex-items flex-sp-between">
					<view class="flex-items">
						<view class="mar-r-14">
							<image class="avatar" :src="item.avatar||'../../../static/images/avatar.png'"
								mode="aspectFill">
							</image>
						</view>
						<view class="font28">
							{{item.account}}
							<uni-rate activeColor="#E2A28A" size="16" :value="item.score" allow-half />
						</view>
					</view>
					<view class="font-gray mar-r-14">
						{{item.scoreTime}}
					</view>
				</view>
				<view class="mar-t-30 font28 mar-l-80">
					{{item.content}}
				</view>
				<view class="flex-items mar-l-80">
					<view class="mar-t-30 font28 mar-r-14" v-for="(item,index) in item.imgList">
						<image v-if="item&&index<3" class="scoreImg" :src="item" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 详情和规格 -->
		<view class="bg-white font32 pad-32 text-align font-gray">
			—— 商品详情 ——
		</view>
		<view class="bg-white">
			<u-parse :content="detail.context" :tagStyle="style"></u-parse>
		</view>
		<view class="height104"></view>

		<!-- 底部操作栏 -->
		<view class="navigation">
			<view class="flex">
				<view class="left">
					<view class="item" @tap="goOrder">
						<u-icon name="order" size="22"></u-icon>
						<view class="text u-line-1">订单</view>
					</view>
					<view class="item" @tap="goCart">
						<view class="cart-icon-wrapper">
							<u-icon name="shopping-cart" size="24"></u-icon>
							<view class="cart-badge" v-if="cartCount > 0">{{cartCount}}</view>
						</view>
						<view class="text u-line-1">购物车</view>
					</view>
					<view class="item" @click="handlerCollect">
						<u-icon :name="isCollect? 'star-fill' :'star'" :color="isCollect? '#F95B5B' : ''"
							size="22"></u-icon>
						<view class="text u-line-1">收藏</view>
					</view>
				</view>
				<view class="right">
					<view class="cart cartBtn u-line-1" :class="{ 'disabled': !detail.stock || detail.stock <= 0 }"
						@click="addCart">加入购物车</view>
					<view class="buy buyBtn u-line-1" :class="{ 'disabled': !detail.stock || detail.stock <= 0 }"
						@click="goPay">立即购买</view>
				</view>
			</view>

			<!-- 规格选择弹窗 -->
			<uni-popup borderRadius="20rpx 20rpx 0 0" ref="popup" background-color="#fff">
				<view class="popup">
					<view class="flex-items">
						<view>
							<image class="prpupImg" :src="skuSelect.skuImage" mode="aspectFit"
								@click="previewImage(skuSelect.skuImage)"></image>
						</view>
						<view class="mar-l-20">
							<view class="font32 pad-b-24">
								{{detail.name}}
							</view>
							<view class="pad-t-10">
								<text class="font40 font-red font-bold">￥{{skuSelect.price}}</text>
							</view>
							<view class="pad-t-15">
								<text class="font28 font-gray">剩余{{skuSelect.skuStock}}件</text>
							</view>
						</view>
					</view>
					<!-- 线条 -->
					<view class="gray-line mar-tb-8"></view>
					<view class="font38 font-bold mar-tb-20">
						请选择规格
					</view>
					<view class="flex-container">
						<view class="hotBg"
							:style="selectId==item.id ? {backgroundColor: '#F2D0A2' } : {backgroundColor: '#ebebeb' }"
							v-for="(item, index) in detail.sku" :key="index" @click="selectRadio(item,index)">
							<view class="font28 ">
								{{item.skuName}}
							</view>
						</view>
					</view>

					<view class="flex-items flex-sp-between mar-b-60">
						<view class="mar-l-16 font32">
							购买数量
						</view>
						<view class="mar-r-16">
							<u-number-box v-model="count"></u-number-box>
						</view>
						<button class="fixed-button" @click="goSettle">{{popupText}}</button>
					</view>
				</view>
			</uni-popup>
			<u-safe-bottom></u-safe-bottom>
		</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex';
	import {
		productCartCount,
		productDetail,
		productAddCollect,
		productClearCollect,
		scoreList,
		productCartSave
	} from '../../../config/api.js';
	import {
		MAIN_COLOR
	} from '../../../common/config.js'
	export default {
		computed: {
			...mapGetters(['isLogin']),
			navTitle() {
				return this.bgColor !== 'transparent' ? '商品详情' : ''
			},
			navIconColor() {
				return this.bgColor !== 'transparent' ? '#FFFFFF' : '#cecece'
			}
		},
		data() {
			return {
				count: 1,
				skuNum: 0,
				popupText: "立即购买",
				selectId: "",
				skuSelect: {},
				bgColor: 'transparent',
				currentSkuText: '',
				currentNum: 0,
				buyType: 'sku',
				params: {
					current: 1,
					size: 2,
					productId: "",
					images: 1
				},
				imgList: [],
				isCollect: false,
				list: ['商品详情'],
				curNow: 0,
				radios: [],
				detail: {},
				imageList: [],
				scoreList: [],
				user: {},
				cartCount: 0,
				style: {
					img: 'width: 100%; vertical-align: top;',
				},
				showShare: false,
				ballShow: false,
				ballStyle: {
					left: '0px',
					top: '0px'
				}
			};
		},
		onPageScroll(e) {
			if (e.scrollTop >= 100) {
				this.bgColor = "#FFF"
			} else {
				this.bgColor = 'transparent'
			}
		},
		onLoad(opt) {
			this.params.productId = opt.id
			this.getDetail(this.params.productId)
			this.getScoreList()
			if (this.isLogin) {
				this.getCartCount()
			}
			setTimeout(() => {
				if (opt.skuId) {
					this.onceOrder(opt.skuId)
				}
			}, 300)
		},
		// 分享功能
		onShareAppMessage() {
			return {
				title: this.detail.name || '商品详情',
				path: `/packageShop/pages/detail/index?id=${this.params.productId}`,
				imageUrl: this.imageList && this.imageList.length > 0 ? this.imageList[0] : ''
			}
		},
		methods: {
			goCart() {
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/packageUser/pages/login/index'
					});
					return;
				}
				this.$route('/packageShop/pages/cart/index')
			},
			goOrder() {
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/packageUser/pages/login/index'
					});
					return;
				}
				this.$route('/packageOrder/pages/list/index?status=0')
			},
			getCartCount() {
				if (!this.isLogin) return;
				productCartCount().then((res) => {
					this.cartCount = res.data
				})
			},
			goSettle() {
				if (this.buyType === 'buy') {
					if (!this.skuSelect || !this.skuSelect.id) {
						return uni.$u.toast('请选择商品规格');
					}
					// 检查选中规格的库存
					if (!this.skuSelect.skuStock || this.skuSelect.skuStock <= 0) {
						return uni.$u.toast('该规格库存不足，无法购买');
					}
					// 检查购买数量是否超过库存
					if (this.count > this.skuSelect.skuStock) {
						return uni.$u.toast(`该规格仅剩${this.skuSelect.skuStock}件，请调整购买数量`);
					}
					if (!this.isLogin) {
						uni.navigateTo({
							url: '/packageUser/pages/login/index'
						});
						return;
					}
					this.skuSelect.count = this.count;
					this.skuSelect.productName = this.detail.name;
					const sku = JSON.stringify(this.skuSelect);
					uni.navigateTo({
						url: `/packageShop/pages/settle/index?sku=${encodeURIComponent(sku)}`,
					});
				} else {
					if (!this.skuSelect || !this.skuSelect.id) {
						return uni.$u.toast('请选择商品规格');
					}
					// 检查选中规格的库存
					if (!this.skuSelect.skuStock || this.skuSelect.skuStock <= 0) {
						return uni.$u.toast('该规格库存不足，无法加入购物车');
					}
					// 检查购买数量是否超过库存
					if (this.count > this.skuSelect.skuStock) {
						return uni.$u.toast(`该规格仅剩${this.skuSelect.skuStock}件，请调整数量`);
					}
					if (!this.isLogin) {
						uni.navigateTo({
							url: '/packageUser/pages/login/index'
						});
						return;
					}
					productCartSave({
						skuId: this.skuSelect.id,
						count: this.count
					}).then((res) => {
						if (res.code == 200) {
							this.startAddCartAnim();
							this.$refs.popup.close();
							this.getCartCount();
							uni.$u.toast("加入购物车成功");
						}
					})
				}
			},
			goScore() {
				this.$route('/packageOrder/pages/score/product-score?productId=' + this.params.productId)
			},
			skuPopUp(buyType) {
				this.$refs.popup.open("bottom")
				this.buyType = buyType;
				this.skuSelect = this.detail.sku[0]
				this.selectId = this.skuSelect.id
			},
			onceOrder(skuId) {
				console.log(skuId, "skuid")
				this.$refs.popup.open("bottom");
				this.buyType = "buy";
				const matchedSku = this.detail.sku.find(item => item.id === skuId);
				if (matchedSku) {
					this.skuSelect = matchedSku;
					this.selectId = this.skuSelect.id;
				} else {
					uni.$u.toast("该规格已下架")
				}
			},
			getScoreList() {
				scoreList(this.params).then((res) => {
					this.scoreList = res.data.records
					this.scoreList.forEach(item => {
						item.imgList = item.images.split(",")
					})
				})
			},
			async getDetail(id) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				try {
					const res = await productDetail({
						id
					})
					if (res.code === 200) {
						this.detail = res.data
						this.skuNum = this.detail.sku.length
						this.imageList = res.data.carouselImg.split(",");
						this.isCollect = res.data.isCollect
					} else if (res.code === 401) {
						uni.navigateTo({
							url: '/packageUser/pages/login/index'
						});
					}
				} catch (e) {
					console.error('获取商品详情失败:', e);
					if (e.code === 401) {
						uni.navigateTo({
							url: '/packageUser/pages/login/index'
						});
					} else {
						uni.$u.toast('获取商品详情失败');
					}
				}
				uni.hideLoading()
			},
			navigationTo(routerName) {
				if (routerName) {
					this.$route(routerName);
				}
			},
			async handlerCollect() {
				if (this.isCollect) {
					try {
						await productClearCollect({
							productId: this.params.productId
						})
						this.$u.toast('取消收藏成功！')
						this.isCollect = !this.isCollect
					} catch (e) {
						this.$u.toast('取消收藏失败！')
					}
				} else {
					try {
						await productAddCollect({
							productId: this.params.productId
						})
						this.$u.toast('收藏成功！')
						this.isCollect = !this.isCollect
					} catch (e) {
						this.$u.toast('收藏失败！')
					}
				}
			},
			addCart() {
				// 检查商品总库存
				if (!this.detail.stock || this.detail.stock <= 0) {
					return uni.$u.toast('商品库存不足，暂不能加入购物车');
				}
				this.skuPopUp('cart')
				this.popupText = "加入购物车"
			},
			goPay() {
				// 检查商品总库存
				if (!this.detail.stock || this.detail.stock <= 0) {
					return uni.$u.toast('商品库存不足，暂不能购买');
				}
				this.skuPopUp('buy')
				this.popupText = "立即购买"
			},
			sectionChange(index) {
				this.curNow = index;
			},
			selectRadio(item, index) {
				this.selectId = item.id;
				this.skuSelect = this.detail.sku[index]
			},
			// 预览图片
			previewImage(imageSrc) {
				uni.previewImage({
					urls: [imageSrc],
					current: imageSrc
				});
			},
			startAddCartAnim() {
				const query = uni.createSelectorQuery();
				query.select('.prpupImg').boundingClientRect();
				query.select('.cart-icon-wrapper').boundingClientRect();
				query.exec(([productRect, cartRect]) => {
					if (productRect && cartRect) {
						const startX = productRect.left + productRect.width / 2;
						const startY = productRect.top + productRect.height / 2;

						this.ballStyle = {
							left: startX + 'px',
							top: startY + 'px'
						}

						this.ballShow = true;

						setTimeout(() => {
							this.ballStyle = {
								left: cartRect.left + cartRect.width / 2 + 'px',
								top: cartRect.top + cartRect.height / 2 + 'px'
							}

							setTimeout(() => {
								this.ballShow = false;
							}, 450);
						}, 50);
					}
				});
			},
		}
	};
</script>

<style lang="scss">
	.popup {
		position: relative;
		padding: 30rpx;
		padding-bottom: 120rpx;
		/* 给底部按钮留出空间 */
		background-color: #fff;
	}

	.prpupImg {
		border-radius: 20rpx;
		width: 220rpx;
		height: 220rpx;
		cursor: pointer;
		transition: transform 0.2s ease;
	}

	.prpupImg:active {
		transform: scale(0.95);
	}

	.guige {
		background-color: #F5F5F5;
		padding: 10rpx;
		border-radius: 15rpx;
	}

	.skuImg {
		width: 60rpx;
		height: 60rpx;
		margin-right: 30rpx;
	}

	.productStats {
		margin: 25rpx 15rpx 25rpx 15rpx;
		border-radius: 20rpx;
		padding: 32rpx;
		background-color: #FFFFFF;
	}

	.vertical-line {
		margin-left: 20rpx;
		margin-right: 20rpx;
		width: 1px;
		height: 20rpx;
		background-color: #a8a8a8;
	}

	.productInfo {
		background-color: white;
		padding: 20rpx;
		margin: 25rpx 15rpx 25rpx 15rpx;
		border-radius: 20rpx;
	}

	/* 新的商品信息样式 */
	.product-info {
		background-color: #ffffff;
		padding: 32rpx 24rpx;
		margin: 24rpx 16rpx;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
	}

	.product-main {
		flex: 1;
		margin-right: 24rpx;
	}

	.price-section {
		display: flex;
		align-items: baseline;
		margin-bottom: 16rpx;
	}

	.current-price {
		font-size: 48rpx;
		font-weight: bold;
		color: #ff4757;
		margin-right: 8rpx;
	}

	.price-suffix {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff4757;
		margin-right: 16rpx;
	}

	.original-price {
		font-size: 28rpx;
		color: #999999;
		text-decoration: line-through;
	}

	.product-name {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
		line-height: 1.4;
		margin-bottom: 16rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.product-stats {
		display: flex;
		align-items: center;
	}

	.stat-item {
		font-size: 25rpx;
		color: #666666;
	}

	.divider {
		width: 2rpx;
		height: 24rpx;
		background-color: #e0e0e0;
		margin: 0 16rpx;
	}

	.share-section {
		flex-shrink: 0;
	}

	.share-btn {
		background: #ffffff;
		border: 2rpx solid #f0f0f0;
		border-radius: 20rpx;
		padding: 0;
		transition: all 0.25s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 80rpx;
		height: 80rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		position: relative;
	}

	.share-btn::after {
		content: '';
		position: absolute;
		top: -2rpx;
		left: -2rpx;
		right: -2rpx;
		bottom: -2rpx;
		background: linear-gradient(45deg, #667eea, #764ba2, #f093fb, #f5576c);
		border-radius: 20rpx;
		z-index: -1;
		opacity: 0;
		transition: opacity 0.25s ease;
	}

	.share-btn:active::after {
		opacity: 1;
	}

	.share-btn:active {
		transform: scale(0.92);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
		border-color: transparent;
	}

	.share-btn .u-icon {
		color: #666666;
		transition: all 0.25s ease;
		font-size: 24rpx;
	}

	.share-btn:active .u-icon {
		color: #ffffff;
		transform: rotate(15deg) scale(1.1);
	}

	.swiper {
		width: 100%;
		position: relative;
	}

	.navigation {
		position: fixed;
		bottom: 0;
		width: 100%;
		border: solid 2rpx #f2f2f2;
		background-color: #ffffff;
		padding: 16rpx 0;

		.flex {
			display: flex;
			flex-direction: row;

			.left {
				width: 40%;
				display: flex;
				font-size: 20rpx;
				justify-content: space-around;

				.item {
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					flex: 1;

					.tabbar-slot-icon {
						width: 44rpx;
						height: 44rpx;
						margin: 0 auto;
					}
				}
			}

			.right {
				width: 60%;
				display: flex;
				font-size: 28rpx;
				align-items: center;

				.cartBtn {
					width: 210rpx;
					height: 72rpx;
					font-size: 28rpx;
					text-align: center;
					line-height: 72rpx;
					border-radius: 36rpx 0rpx 0rpx 36rpx;
					color: #ffffff;
				}

				.buyBtn {
					font-size: 28rpx;
					width: 210rpx;
					height: 72rpx;
					text-align: center;
					line-height: 72rpx;
					border-radius: 0rpx 36rpx 36rpx 0rpx;
					color: #ffffff;
				}

				.buy {
					background: #F95B5B
				}

				.cart {
					background: #F9AE5B
				}

				.disabled {
					background: #cccccc !important;
					color: #999999 !important;
					cursor: not-allowed;
				}
			}
		}
	}

	.gray-line {
		height: 1px;
		background-color: #f9f9f9;
		width: 100%;
	}

	.flex-container {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 30rpx;
	}

	.hotBg {
		margin-bottom: 10rpx;
		margin-right: 30rpx;
		padding: 10px;
		font-size: 28rpx;
		border-radius: 5px;
	}

	.selected {
		background-color: orange;
	}

	.fixed-button {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 15rpx;
		background-color: #F95B5B;
		color: white;
		border: none;
	}

	.avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.scoreImg {
		width: 150rpx;
		height: 150rpx;
	}

	.cart-icon-wrapper {
		position: relative;
		display: inline-block;
	}

	.cart-badge {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		background-color: #FF4B4B;
		color: #fff;
		font-size: 20rpx;
		padding: 2rpx 8rpx;
		border-radius: 20rpx;
		min-width: 28rpx;
		height: 28rpx;
		text-align: center;
		line-height: 28rpx;
	}

	.cart-ball {
		position: fixed;
		z-index: 999;
		pointer-events: none;
		transition: all 0.45s cubic-bezier(0.49, -0.29, 0.75, 0.41);

		.inner {
			width: 16px;
			height: 16px;
			border-radius: 50%;
			background: #ff6b81;
			transition: all 0.45s linear;
		}
	}

	.cart-ball.active .inner {
		animation: ball-circular 0.45s linear;
	}

	@keyframes ball-circular {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(0.8);
		}

		100% {
			transform: scale(0.5);
		}
	}

	.custom-share-btn {
		background: #ffffff;
		border: 2rpx solid #e3e3e3;
		border-radius: 20rpx;
		padding: 0;
		transition: all 0.25s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 80rpx;
		height: 80rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		position: relative;
	}

	.custom-share-btn::after {
		content: '';
		position: absolute;
		top: -2rpx;
		left: -2rpx;
		right: -2rpx;
		bottom: -2rpx;
		background: linear-gradient(45deg, #667eea, #764ba2, #f093fb, #f5576c);
		border-radius: 20rpx;
		z-index: -1;
		opacity: 0;
		transition: opacity 0.25s ease;
	}

	.custom-share-btn:active::after {
		opacity: 1;
	}

	.custom-share-btn:active {
		transform: scale(0.92);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
		border-color: transparent;
	}

	.custom-share-btn .u-icon {
		color: #666666;
		transition: all 0.25s ease;
		font-size: 24rpx;
	}

	.custom-share-btn:active .u-icon {
		color: #ffffff;
		transform: rotate(15deg) scale(1.1);
	}
</style>