<template>
	<view>
		<u-popup v-model="visible" mode="bottom" border-radius="24" :safe-area-inset-bottom="true" :mask-close-able="false"
			@close="close">
			<view class="popup-content" @click.stop>
			<!-- Header -->
			<view class="header">
				<text class="title">选择商品品相</text>
				<image src="/pages-sell/static/select-good/icon-close.png" class="close-icon" @click="close"></image>
			</view>

			<!-- Product Info -->
			<view class="product-info">
				<image :src="currentProduct.cover" class="book-cover" mode="aspectFill"></image>
				<view class="info-right">
					<view class="price-row">
						<text class="currency">¥</text>
						<text class="price">{{ displayUnitPrice }}</text>
						<view class="drop-tag">
							<text>↓可降至 ¥{{ displayMinPrice }}</text>
						</view>
					</view>
					<view class="tag-row">
						<view class="quality-tag">
							<text>品相{{ currentQualityName }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- Tips -->
			<view class="tips-row">
				<text>不同品相有什么区别</text>
				<image src="/pages-sell/static/select-good/icon-tips.png" class="tips-icon"></image>
			</view>

			<!-- Promo Note -->
			<view class="promo-note">
				<text>下单时用书购余额支付可享余额价 ( 售价 8 折优惠 )</text>
			</view>

			<!-- Options -->
			<view class="options-list">
				<view class="option-item" v-for="(opt, index) in qualityOptions" :key="index"
					:class="{ active: currentQuality === opt.conditionType, disabled: isOptionDisabled(opt) }"
					@click="selectQuality(opt)">
					<image v-if="currentQuality === opt.conditionType && !isOptionDisabled(opt)"
						src="/pages-sell/static/select-good/selected.png" class="bg-image"></image>
					<view class="left">
						<text class="opt-name">{{ opt.conditionType | conditionText }}</text>
						<view class="opt-discount"
							:class="{ active: currentQuality === opt.conditionType && !isOptionDisabled(opt) }">
							<text>{{ opt.discount }}折</text>
						</view>
					</view>
					<view class="right">
						<text v-if="!isOptionDisabled(opt)">¥{{ opt.price }} ( 余额价 ¥{{ opt.balanceMoney }} )</text>
						<text v-else>无货</text>
					</view>
				</view>
			</view>

			<!-- Quantity -->
			<view class="quantity-row">
				<text class="label">数量</text>
				<u-number-box v-model="quantity" :min="1" :max="99"></u-number-box>
			</view>

			<!-- Footer Buttons -->
			<view class="footer-btns">
				<view class="btn btn-orange" @click="handleShareAction">
					<text class="price">¥{{ currentProduct.maxReducePrice }}</text>
					<text class="desc">分享一人可降 {{ currentProduct.reducePrice }} 元</text>
				</view>
				<view class="btn btn-green" @click="handleAction" :class="{ 'btn-gray': !hasStock && currentProduct.hasArrivalNotice === 1 }">
					<text v-if="hasStock" class="price">¥{{ displayTotalPrice }}</text>
					<text class="desc" :class="{ 'notice': !hasStock }">{{ hasStock ? '加入购物车' : (currentProduct.hasArrivalNotice === 1 ? '取消到货通知' : '到货通知') }}</text>
				</view>
			</view>
			</view>
		</u-popup>

		<price-reduction-popup ref="reducePopup" @scan="handleScan"></price-reduction-popup>
		<reduce-qrcode ref="reduceQrcode"></reduce-qrcode>
	</view>
</template>

<script>
import PriceReductionPopup from '@/components/price-reduction-popup/price-reduction-popup.vue';
import ReduceQrcode from '@/components/reduce-qrcode/reduce-qrcode.vue';

export default {
	name: 'SelectGoodPopup',
	components: {
		PriceReductionPopup,
		ReduceQrcode
	},
	data() {
		return {
			visible: false,
			quantity: 1,
			currentQuality: 1,
			currentProduct: {},
			qualityOptions: [],
			sourceFrom: 0,
			isSubmitting: false, // 防重复提交标志
		};
	},
	computed: {
		currentQualityName() {
			const opt = this.$conditionMap[this.currentQuality];
			return opt || '未知';
		},
		selectedOption() {
			return this.qualityOptions.find(o => o.conditionType === this.currentQuality) || {};
		},
		displayUnitPrice() {
			return this.formatPrice(this.selectedOption.price);
		},
		displayMinPrice() {
			return this.formatPrice(this.selectedOption.balanceMoney);
		},
		displayTotalPrice() {
			const total = Number(this.selectedOption.price || 0) * this.quantity;
			return this.formatPrice(total);
		},
		hasStock() {
			const stock = this.selectedOption.stockNum;
			if (stock === 0) return false;
			if (stock === undefined || stock === null || stock === '') return true;
			return Number(stock) > 0;
		}
	},
	methods: {
		open(product, sourceFrom) {
			this.visible = true;
			this.quantity = 1;
			this.sourceFrom = sourceFrom || 0;
			if (product.isbn) {
				this.getGoodQualityInfo(product.isbn);
			}
		},
		//根据 isbn 获取商品品相信息
		getGoodQualityInfo(isbn) {
			uni.$u.http.get('/token/shop/bookDetail', { isbn }).then(res => {
				console.log(res);
				if (res.code === 200) {
					this.currentProduct = res.data || {};
					this.qualityOptions = res.data.skuList || [];
					if (this.qualityOptions.length > 0) {
						this.currentQuality = this.qualityOptions[0].conditionType
					}
				}
			});
		},

		close() {
			this.visible = false;
		},
		isOptionDisabled(opt) {
			const stock = opt.stockNum;
			if (stock === 0) return true;
			if (stock === undefined || stock === null || stock === '') return false;
			return Number(stock) <= 0;
		},
		selectQuality(opt) {
			if (this.isOptionDisabled(opt)) {
				this.$u.toast('该品相暂无库存');
				return;
			}
			this.currentQuality = opt.conditionType;
		},
		handleAction() {
			if (!this.hasStock) {
				this.handleNotify();
				return;
			}
			this.handleConfirm();
		},
		handleNotify() {
			const isCancel = this.currentProduct.hasArrivalNotice === 1;
			const apiUrl = isCancel ? '/token/shop/user/noticeArrivalCancel' : '/token/shop/user/noticeArrival';
			
			uni.$u.http.post(apiUrl, {
				isbn: this.currentProduct.isbn,
			}).then(res => {
				if (res.code === 200) {
					const newValue = isCancel ? 0 : 1;
					this.$set(this.currentProduct, 'hasArrivalNotice', newValue);
					this.$emit('notice-change', newValue);
					this.$u.toast(isCancel ? '已取消到货通知' : '到货通知设置成功');
				}
			}).finally(() => {
				this.close();
			});
		},
		handleConfirm() {
			if (this.isSubmitting) return; // 防止重复提交
			
			if (!this.currentProduct.isbn) {
				this.$u.toast('商品信息缺失');
				return;
			}

			const selectedOption = this.selectedOption;
			const conditionType = selectedOption.conditionType || this.currentQuality;

			if (!conditionType) {
				this.$u.toast('请选择品相');
				return;
			}

			this.isSubmitting = true; // 设置提交中状态

			this.$u.api.addShopCartAjax({
				isbn: this.currentProduct.isbn,
				quantity: this.quantity,
				conditionType: conditionType,
				sourceFrom: this.sourceFrom
			}).then(res => {
				if (res.code === 200) {
					this.$u.toast('加入购物车成功');
					this.$updateCartBadge();
					this.$emit('confirm', {
						product: this.currentProduct,
						quality: this.currentQuality,
						quantity: this.quantity
					});
					this.close();
				} else {
					this.$u.toast(res.msg || '加入购物车失败');
				}
			}).finally(() => {
				this.isSubmitting = false; // 重置提交状态
			});
		},
		handleShareAction() {
			if (this.isSubmitting) return; // 防止重复提交
			
			if (!this.currentProduct.isbn) {
				this.$u.toast('商品信息缺失');
				return;
			}

			const selectedOption = this.selectedOption;
			const conditionType = selectedOption.conditionType || this.currentQuality;

			if (!conditionType) {
				this.$u.toast('请选择品相');
				return;
			}

			this.isSubmitting = true; // 设置提交中状态

			this.$u.api.addShopCartAjax({
				isbn: this.currentProduct.isbn,
				quantity: this.quantity,
				conditionType: conditionType,
				sourceFrom: this.sourceFrom
			}).then(res => {
				if (res.code === 200) {
					this.$u.toast('加入购物车成功');
					this.$updateCartBadge();
					this.$emit('confirm', {
						product: this.currentProduct,
						quality: this.currentQuality,
						quantity: this.quantity
					});
					this.close();
					
					// 打开减价弹窗
					setTimeout(() => {
						if (this.$refs.reducePopup) {
							this.$refs.reducePopup.open({
								isbn: this.currentProduct.isbn,
								conditionType: conditionType
							});
						}
					}, 300);
				} else {
					this.$u.toast(res.msg || '加入购物车失败');
				}
			}).finally(() => {
				this.isSubmitting = false; // 重置提交状态
			});
		},
		handleScan(bookInfo) {
			this.$refs.reduceQrcode.open(bookInfo);
		},
		formatPrice(value) {
			if (value === undefined || value === null) return '0.00';
			const num = Number(value);
			return Number.isFinite(num) ? num.toFixed(2) : '0.00';
		}
	}
};
</script>

<style lang="scss" scoped>
.popup-content {
	padding: 30rpx 30rpx 20rpx;
	background-color: #fff;
	position: relative;
}

.header {
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	margin-bottom: 30rpx;
	padding-bottom: 30rpx;
	border-bottom: 2rpx dashed #eee;

	.title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
	}

	.close-icon {
		position: absolute;
		right: 0;
		top: 0;
		width: 24rpx;
		height: 24rpx;
		padding: 10rpx;
		box-sizing: content-box;
	}
}

.product-info {
	display: flex;
	margin-bottom: 30rpx;

	.book-cover {
		width: 140rpx;
		height: 180rpx;
		border-radius: 8rpx;
		margin-right: 24rpx;
		background-color: #f5f5f5;
	}

	.info-right {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 10rpx 0;

		.price-row {
			display: flex;
			align-items: center;

			.currency {
				font-size: 36rpx;
				color: #D81A00;
				font-weight: bold;
			}

			.price {
				font-size: 40rpx;
				color: #D81A00;
				font-weight: bold;
				margin-right: 20rpx;
				line-height: 1;
			}

			.drop-tag {
				background: #E8F9EA;
				padding: 4rpx 12rpx;
				border-radius: 4rpx;

				text {
					color: #38C248;
					font-size: 24rpx;
					font-weight: 500;
				}
			}
		}

		.tag-row {
			.quality-tag {
				display: inline-block;
				background: linear-gradient(0deg, #FFAB26 0%, #FFD426 100%);
				border-radius: 21rpx 0px 21rpx 0px;
				padding: 2rpx 24rpx;
				margin-bottom: 24rpx;

				text {
					color: #fff;
					font-size: 24rpx;
					font-weight: 500;
				}
			}
		}
	}
}

.tips-row {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;

	text {
		font-size: 26rpx;
		color: #8D8D8D;
		margin-right: 10rpx;
	}

	.tips-icon {
		width: 36rpx;
		height: 36rpx;
	}
}

.promo-note {
	margin-bottom: 40rpx;

	text {
		font-size: 26rpx;
		color: #8D8D8D;
	}
}

.options-list {
	margin-bottom: 40rpx;

	.option-item {
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: #ffffff;
		border-radius: 12rpx;
		padding: 24rpx 30rpx;
		margin-bottom: 24rpx;
		border: 2rpx solid #dfdfdf;
		transition: all 0.2s;

		&.active {
			border-color: transparent;
		}

		&.disabled {
			background: #F0F0F0;
			border-color: #E0E0E0;
			opacity: 0.7;

			.opt-name,
			.right text {
				color: #999;
			}

			.opt-discount {
				background: #CCCCCC;
			}
		}

		.bg-image {
			position: absolute;
			top: -6rpx;
			left: -1%;
			width: 102%;
			height: 110rpx;
			z-index: 0;
		}

		.left,
		.right {
			position: relative;
			z-index: 1;
		}

		.left {
			display: flex;
			align-items: center;

			.opt-name {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-right: 16rpx;
			}

			.opt-discount {
				background: #D8D8D8;
				padding: 0 20rpx;
				border-radius: 0 20rpx 0 20rpx;

				text {
					color: #fff;
					font-size: 24rpx;
					display: inline-block;
				}

				&.active {
					background: linear-gradient(0deg, #30E030 0%, #28C445 100%);
				}
			}
		}

		.right {
			text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}
}

.quantity-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 50rpx;

	.label {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}
}

.footer-btns {
	display: flex;
	justify-content: space-between;
	padding-bottom: 10rpx;

	.btn {
		flex: 1;
		height: 100rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-family: Source Han Sans SC;
		font-weight: 500;
		border: none;
		outline: none;
		padding: 0;
		margin: 0;
		-webkit-tap-highlight-color: transparent;

		.price {
			font-size: 38rpx;
			color: #fff;
			line-height: 32rpx;
		}

		.desc {
			font-size: 24rpx;
			color: #fff;
			line-height: 32rpx;
		}

		.notice {
			font-size: 32rpx;
			color: #fff;
		}

		&.btn-orange {
			background: linear-gradient(0deg, #EFA941 0%, #FFB84F 100%);
			width: 340rpx;
			border-radius: 50rpx 0 0 50rpx;
		}

		&.btn-green {
			width: 340rpx;
			background: linear-gradient(0deg, #38C248 0%, #5FEA6F 100%);
			border-radius: 0 50rpx 50rpx 0;
		}

		&.btn-gray {
			background: #ccc !important;
		}
	}
}
</style>
