<template>
	<!-- 商品明细弹窗 -->
	<view v-if="showDetailPopup" class="detail-popup-mask" @click.self="close">
		<view class="detail-popup" @click.stop>
			<view class="detail-popup-header">
				<text class="detail-popup-close" @click="close">关闭</text>
				<text class="detail-popup-title">商品明细</text>
			</view>
			
			<!-- 商品基本信息 -->
			<view class="product-basic-info">
				<image :src="productInfo.image" class="product-image" mode="aspectFit" />
				<view class="product-info">
					<text class="product-name">{{ productInfo.name }}</text>
					<text class="brand-name">品牌：{{ brandInfo.name }}</text>
				</view>
			</view>
			
			<!-- 款式列表 -->
			<scroll-view class="style-list" scroll-y>
				<view v-for="(style, index) in styleList" :key="style.id" class="style-item">
					<image :src="style.image" class="style-image" mode="aspectFit" />
					<view class="style-info">
						<text class="style-name">{{ style.name }}</text>
						<view class="style-price">
							<text class="price-symbol">¥</text>
							<text class="price-value" v-if="style.minPrice === style.maxPrice">{{ style.minPrice }}</text>
							<text class="price-value" v-else>{{ style.minPrice }}-{{ style.maxPrice }}</text>
							<text class="price-unit">/件</text>
						</view>
					</view>
					<view class="style-quantity">
						<button class="btn-minus" @click="updateQuantity(index, -1)">-</button>
						<text class="quantity">{{ style.quantity || 0 }}</text>
						<button class="btn-plus" @click="updateQuantity(index, 1)">+</button>
					</view>
				</view>
			</scroll-view>
			
			<!-- 价格统计 -->
			<view class="price-summary">
				<view class="summary-left">
					<text class="summary-label">已选 <text class="summary-count">{{ totalQuantity }}</text> 件，预计可得</text>
					<view class="amount-row">
						<text class="amount" v-if="totalPriceRange.min === totalPriceRange.max">¥{{ totalPriceRange.min }}</text>
						<text class="amount" v-else>¥{{ totalPriceRange.min }}-{{ totalPriceRange.max }}</text>
					</view>
				</view>
			</view>
			
			<!-- 底部按钮 -->
			<view class="detail-popup-footer">
				<button class="confirm-btn" @click="confirmChanges">确认修改</button>
			</view>
			
			<!-- 浮窗按钮 -->
			<view class="floating-btn" @click="openStyleSelector">
				<text class="floating-btn-text">+</text>
			</view>

			<product-style-selector ref="styleSelector" @style-confirm="onStyleConfirm" @close="onStyleSelectorClose"></product-style-selector>
			<!-- 款式选择器组件 -->

		</view>
		
	</view>
</template>

<script>
import productStyleSelector from './product-style-selector.vue'
export default {
	name: 'ProductDetailPopup',
	components: {
		productStyleSelector
	},
	data() {
		return {
			showDetailPopup: false,
			productInfo: {
				id: '',
				name: '',
				image: ''
			},
			brandInfo: {
				id: '',
				name: '',
				logo: ''
			},
			styleList: [],
			originalQuantities: {} // 保存原始数量，用于取消时恢复
		}
	},
	computed: {
		// 计算总价格范围
		totalPriceRange() {
			const result = this.styleList.reduce((sum, style) => {
				const quantity = style.quantity || 0
				if (quantity > 0) {
					const minPrice = Number(style.minPrice) || 0
					const maxPrice = Number(style.maxPrice) || Number(style.minPrice) || 0
					sum.min += quantity * minPrice
					sum.max += quantity * maxPrice
				}
				return sum
			}, { min: 0, max: 0 })
			
			return {
				min: result.min.toFixed(1),
				max: result.max.toFixed(1)
			}
		},
		// 计算总数量
		totalQuantity() {
			return this.styleList.reduce((sum, style) => sum + (style.quantity || 0), 0)
		}
	},
	methods: {
		// 打开商品明细弹窗
		open(productInfo, brandInfo, existingQuantities = {}, styleCache = {}) {
			if (!productInfo || !brandInfo) {
				console.error('productInfo and brandInfo are required')
				return
			}
			
			this.productInfo = productInfo
			this.brandInfo = brandInfo
			this.originalQuantities = { ...existingQuantities }
			
			// 直接基于已选择的款式构建列表
			this.buildStyleListFromExisting(existingQuantities, styleCache)
			this.showDetailPopup = true
		},
		
		// 关闭弹窗
		close() {
			this.showDetailPopup = false
			this.styleList = []
			this.productInfo = { id: '', name: '', image: '' }
			this.brandInfo = { id: '', name: '', logo: '' }
			this.originalQuantities = {}
			this.$emit('close')
		},
		
		// 更新数量
		updateQuantity(index, delta) {
			const style = this.styleList[index]
			if (!style) return
			
			let newQuantity = (style.quantity || 0) + delta
			if (newQuantity < 0) newQuantity = 0
			
			this.$set(style, 'quantity', newQuantity)
		},
		
		// 基于已选择的款式构建列表
		buildStyleListFromExisting(existingQuantities, styleCache) {
			const styleList = []
			
			// 从父组件传入的已选择数据中提取款式信息
			Object.entries(existingQuantities).forEach(([uniqueKey, quantity]) => {
				if (quantity > 0 && uniqueKey.startsWith(`${this.brandInfo.id}_`)) {
					// 从styleCache中获取完整的款式信息
					const cacheInfo = styleCache[uniqueKey]
					if (cacheInfo && cacheInfo.styleInfo) {
						const styleInfo = cacheInfo.styleInfo
						styleList.push({
							id: styleInfo.id,
							name: styleInfo.name,
							image: styleInfo.image || '/static/default-product.png',
							minPrice: styleInfo.minPrice,
							maxPrice: styleInfo.maxPrice,
							brandId: styleInfo.brandId || this.brandInfo.id,
							shopId: styleInfo.shopId,
							quantity: quantity
						})
					}
				}
			})
			
			this.styleList = styleList
		},
		
		// 确认修改
		confirmChanges() {
			const updatedStyles = this.styleList.filter(style => (style.quantity || 0) > 0)
			
			this.$emit('confirm-changes', {
				productInfo: this.productInfo,
				brandInfo: this.brandInfo,
				updatedStyles: updatedStyles
			})
			
			this.close()
		},
		
		// 打开款式选择器
		openStyleSelector() {
			// 获取当前品牌下已有的款式数量
			const existingQuantities = {}
			this.styleList.forEach(style => {
				if (style.quantity > 0) {
					const uniqueKey = `${this.brandInfo.id}_${style.id}`
					existingQuantities[uniqueKey] = style.quantity
				}
			})
			
			// 直接打开内部的款式选择器
			this.$refs.styleSelector.open(this.brandInfo, this.productInfo.id, existingQuantities)
		},
		
		// 处理款式确认事件
		onStyleConfirm(data) {
			if (data.selectedStyles && data.selectedStyles.length > 0) {
				// 更新当前的款式列表
				const newStyleList = []
				
				data.selectedStyles.forEach(style => {
					if (style.quantity > 0) {
						newStyleList.push({
							id: style.id,
							name: style.name,
							image: style.image || '/static/default-product.png',
							minPrice: style.minPrice,
							maxPrice: style.maxPrice,
							brandId: style.brandId || this.brandInfo.id,
							shopId: style.shopId,
							quantity: style.quantity
						})
					}
				})
				
				this.styleList = newStyleList
				// 不关闭当前弹窗，保持商品明细弹窗打开状态
			}
		},
		
		// 处理款式选择器关闭事件
		onStyleSelectorClose() {
			// 款式选择器关闭时的处理逻辑
		}
	}
}
</script>

<style lang="scss" scoped>
.detail-popup-mask {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0,0,0,0.25);
	z-index: 5000;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}

.detail-popup {
	position: relative;
	width: 100%;
	max-width: 750px;
	background: #fff;
	border-radius: 32rpx 32rpx 0 0;
	box-shadow: 0 -4rpx 24rpx rgba(0,0,0,0.08);
	padding-bottom: 40rpx;
	height: 84vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.detail-popup-header {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 32rpx 24rpx 0 24rpx;
	font-size: 32rpx;
	font-weight: bold;
	position: relative;
	border-bottom: 1px solid #f0f0f0;
	padding-bottom: 20rpx;
}

.detail-popup-close {
	position: absolute;
	left: 24rpx;
	font-size: 28rpx;
	color: #888;
}

.detail-popup-title {
	font-size: 32rpx;
	color: #222;
	font-weight: bold;
}

.product-basic-info {
	display: flex;
	align-items: center;
	padding: 24rpx;
	border-bottom: 1px solid #f0f0f0;
}

.product-image {
	width: 80rpx;
	height: 80rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
	background: #f8f8f8;
	flex-shrink: 0;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.product-name {
	font-size: 30rpx;
	color: #222;
	font-weight: bold;
	margin-bottom: 8rpx;
}

.brand-name {
	font-size: 26rpx;
	color: #666;
}

.style-list {
	flex: 1;
	overflow-y: auto;
	padding: 0 24rpx;
	box-sizing: border-box;
	max-height: calc(84vh - 200rpx);
	scrollbar-width: none;
	-ms-overflow-style: none;
	&::-webkit-scrollbar {
		width: 0 !important;
		display: none;
	}
}

.style-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
}

.style-image {
	width: 100rpx;
	height: 100rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
	background: #f8f8f8;
	flex-shrink: 0;
}

.style-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	min-width: 0;
}

.style-name {
	font-size: 28rpx;
	color: #222;
	font-weight: bold;
	margin-bottom: 8rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

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

.price-symbol {
	font-size: 24rpx;
	color: #ff7a0e;
}

.price-value {
	font-size: 28rpx;
	color: #ff7a0e;
	font-weight: bold;
	margin: 0 4rpx;
}

.price-unit {
	font-size: 24rpx;
	color: #999;
}

.style-quantity {
	display: flex;
	align-items: center;
	flex-shrink: 0;
}

.btn-minus, .btn-plus {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: #f8f8f8;
	border: 1px solid #e0e0e0;
	color: #666;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0;
	padding: 0;
	
	&::after {
		border: none;
	}
	
	&:active {
		background: #e0e0e0;
	}
}

.quantity {
	width: 60rpx;
	text-align: center;
	font-size: 28rpx;
	color: #333;
	margin: 0 16rpx;
}

.price-summary {
	padding: 20rpx 24rpx;
	border-top: 1px solid #f0f0f0;
	background: #fff;
}

.summary-left {
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.summary-label {
	font-size: 26rpx;
	color: #333;
}

.summary-count {
	color: #ff9c00;
	font-weight: bold;
	font-size: 28rpx;
}

.amount-row {
	display: flex;
	align-items: center;
	margin-top: 4rpx;
}

.amount {
	color: #ff9c00;
	font-size: 44rpx;
	font-weight: bold;
	vertical-align: middle;
}

.detail-popup-footer {
	padding: 24rpx;
	border-top: 1px solid #f0f0f0;
	background: #fff;
}

.confirm-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(to right, #ffd01e, #ff8917);
	border-radius: 44rpx;
	color: #fff;
	font-size: 32rpx;
	font-weight: bold;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&::after {
		border: none;
	}
	
	&:active {
		opacity: 0.9;
	}
}

.floating-btn {
	position: absolute;
	right: 24rpx;
	bottom: 180rpx;
	width: 100rpx;
	height: 100rpx;
	background: linear-gradient(to right, #ffd01e, #ff8917);
	border-radius: 50%;
	box-shadow: 0 4rpx 16rpx rgba(255, 156, 0, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
	
	&:active {
		opacity: 0.9;
		transform: scale(0.95);
	}
}

.floating-btn-text {
	font-size: 48rpx;
	color: #fff;
	font-weight: bold;
	line-height: 1;
}
</style>