<template>
	<view class="container">
		<!-- 商品内容区域 -->
		<view class="content">
			<!-- 商品图片轮播 -->
			<view class="goods-carousel" v-if="goodsData.goodsImage && goodsData.goodsImage.length > 0">
				<swiper class="carousel-swiper" :indicator-dots="goodsData.goodsImage.length > 1"
					:autoplay="goodsData.goodsImage.length > 1" :interval="3000" :duration="500"
					indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#fff">
					<swiper-item v-for="(image, index) in goodsData.goodsImage" :key="index">
						<image class="carousel-image" :src="image" mode="aspectFill" @error="handleImageError"
							@load="handleImageLoad"></image>
					</swiper-item>
				</swiper>
			</view>

			<!-- 积分信息卡片 -->
			<view class="points-card">
				<!-- 积分和兑换数量 -->
				<view class="points-row">
					<view class="points-left">
						<text class="points-value">{{ goodsData.points }}</text>
						<text class="points-unit">{{ goodsData.creditsTypeName || '积分' }}</text>
					</view>
					<text class="exchange-count">已兑换{{ formatCount(goodsData.saleCount) }}件</text>
				</view>

				<!-- 会员标签 -->
				<view class="member-tags" v-if="goodsData.vipLimit && goodsData.vipLimit.length > 0">
					<text class="member-level" v-for="(level, index) in goodsData.vipLimit" :key="index">{{ level }}</text>
				</view>
				
				<!-- 购买限制 -->
				<view class="purchase-limit-section" v-if="goodsData.goodsLimit">
					<text class="purchase-limit">每人限{{ goodsData.goodsLimit }}件</text>
				</view>

				<!-- 优惠券名称 -->
				<view class="coupon-title-section">
					<text class="coupon-title-text">{{ goodsData.name }}</text>
				</view>
			</view>

			<!-- 详情信息 -->
			<view class="detail-section">
				<text class="detail-title">详情信息</text>
				<view class="detail-banner" v-if="goodsData.goodsContent">
					<rich-text class="banner-text" :nodes="goodsData.goodsContent"></rich-text>
				</view>
			</view>
		</view>

		<!-- 底部兑换按钮 -->
		<view class="bottom-bar">
			<button class="exchange-btn" :class="getButtonClass()" :disabled="!canExchange" @click="handleExchange">
				{{ getButtonText() }}
			</button>
		</view>

		<!-- 规格选择弹窗 -->
		<view class="spec-modal-overlay" v-if="showSpecModal" @click="closeSpecModal">
			<view class="spec-modal-content" @click.stop>
				<!-- 关闭按钮 -->
				<view class="close-btn" @click="closeSpecModal">
					<text class="close-icon">×</text>
				</view>

				<!-- 商品信息 -->
				<view class="product-info">
					<view class="product-image">
						<text class="image-placeholder">商品图片</text>
					</view>
					<view class="product-details">
						<text class="product-points">{{ goodsData.points }}{{ goodsData.creditsTypeName || '积分'
						}}</text>
						<text class="product-stock">库存 {{ formatCount(goodsData.saleCount) }}件</text>
					</view>
				</view>

				<!-- 净含量选择 -->
				<view class="spec-section">
					<text class="spec-label">净含量</text>
					<view class="spec-options">
						<view class="spec-option" :class="{ active: selectedSpec === spec.value }"
							v-for="spec in specOptions" :key="spec.value" @click="selectSpec(spec.value)">
							<text class="spec-text">{{ spec.label }}</text>
						</view>
					</view>
				</view>

				<!-- 数量选择 -->
				<view class="quantity-section" v-if="!isSeckill">
					<text class="quantity-label">选择数量 <text class="limit-text" v-if="goodsData.goodsLimit">(限购{{ goodsData.goodsLimit }}件)</text></text>
					<view class="quantity-selector">
						<view class="quantity-btn " @click="decreaseQuantity" :disabled="quantity <= 1">-</view>
						<text class="quantity-value">{{ quantity }}</text>
						<view class="quantity-btn " @click="increaseQuantity"
							:disabled="goodsData.goodsLimit && quantity >= parseInt(goodsData.goodsLimit)">+</view>
					</view>
				</view>
				<!-- 秒杀商品数量显示（固定为1） -->
				<view class="quantity-section" v-else>
					<text class="quantity-label">购买数量</text>
					<view class="quantity-display">
						<text class="quantity-value">1</text>
					</view>
				</view>

				<!-- 确认按钮 -->
				<button class="confirm-spec-btn" @click="confirmSpecSelection">确认</button>
			</view>
		</view>

		<!-- 兑换确认弹窗 -->
		<view class="modal-overlay" v-if="showConfirmModal" @click="closeModal">
			<view class="modal-content" @click.stop>
				<view class="modal-title">兑换确认</view>
				<view class="modal-message">本次兑换需要消耗{{ goodsData.points }}{{ goodsData.creditsTypeName || '积分' }}</view>
				<view class="modal-buttons">
					<button class="modal-btn cancel-btn" @click="closeModal">取消</button>
					<button class="modal-btn confirm-btn" @click="confirmExchange">确定</button>
				</view>
				<view class="modal-disclaimer">已发货商品非质量问题不退不换</view>
			</view>
			<!-- 关闭按钮 -->
			<view class="modal-close-btn" @click="closeModal">
				<text class="modal-close-icon">×</text>
			</view>
		</view>
	</view>
</template>

<script>
import { fetchGoodsDetail, fetchSeckillDetail, fetchGoodsPrice, fetchTradeCredits, fetchSeckillTakeOrder } from '@/api/goods.js';
import { useUserStore } from '@/stores/user';
import { jump, JumpType } from '../../utils';

export default {
	data() {
		return {
			goodsData: {
				id: '',
				points: 0,
				exchangeCount: 0,
				saleCount: 0, // 已兑换数量
				memberLevel: '',
				vipLimit: [], // 会员限制数组
				limit: '',
				goodsLimit: false, // 商品购买限制
				name: '',
				couponName: '',
				expireDate: '',
				remainDays: 18,
				isSoldOut: false,
				goodsType: '',
				goodsContent: '',
				goodsDeclare: '',
				goodsIcon: '',
				goodsImage: [],
				creditsType: '',
				creditsTypeName: '',
				priceMarket: '',
				priceSale: '',
				buttonText: '立即兑换',
				address: null,
				phone: '',
				stores: [],
				skus: [],
				amount: [],
				checkRule: {},
				failRule: {},
				exchangeTime: {},
				virtualConfig: {},
				matnr: '',
				groupEnable: false,
				goodsState: 0
			},
			isLoading: true,
			showConfirmModal: false,
			showSpecModal: false,
			userPoints: 0, // 用户当前积分
			userLevel: '', // 用户当前等级
			userBuyLimit: false, // 用户购买限制
			goodsLimit: false, // 商品限购
			// 规格选择相关
			specOptions: [

			],
			selectedSpec: '',
			quantity: 1,
			// 订单相关
			orderParams: {}, // 订单参数
			priceData: null, // 价格计算结果
			orderResult: null, // 下单结果
			// 用户状态
			userStore: null, // 用户store实例
			cfgStatus: {
				isRegister: true, // 登录状态
				showDetail: false // 是否显示详情
			},
			// 兑换类型
			isSeckill: false, // 是否为秒杀兑换
			seckillParams: {
				activityId: '', // 活动ID
				sessionKey: '', // 会话密钥
				appGoodsId: '' // 应用商品ID
			}
		}
	},
	computed: {
		// 是否可以兑换
		canExchange() {
			// 未登录状态保持当前逻辑不变
			if (!this.cfgStatus.isRegister) {
				return true; // 未登录时按钮仍然可点击，会跳转到登录页
			}

			// 已登录用户需要检查各种条件
			// 1. 商品库存不足
			if (this.goodsData.exchangeCount <= 0) {
				return false;
			}

			// 2. 用户积分不足
			if (this.userStore && this.userStore.userInfo) {
				const userCredits = this.userStore.userInfo.credits || 0;
				if (userCredits < this.goodsData.points) {
					return false;
				}
			}

			// 3. 用户等级不足（检查vipLimit数组）
			if (this.goodsData.vipLimit && this.goodsData.vipLimit.length > 0 && this.userStore && this.userStore.userInfo) {
				const userLevel = this.userStore.userInfo.grade || 1;
				const userLevelName = this.getUserLevelName(userLevel);
				// 检查用户等级是否在vipLimit中
				if (!this.goodsData.vipLimit.includes(userLevelName)) {
					return false;
				}
			}

			// 4. 用户达到兑换上限（使用goodsLimit）
			if (this.goodsData.goodsLimit && this.userBuyLimit) {
				return false;
			}

			// 5. 商品状态检查
			if (this.goodsData.goodsState !== 1) {
				return false;
			}

			return true;
		},

		// 兑换状态
		exchangeStatus() {
			// 未登录状态
			if (!this.cfgStatus.isRegister) {
				return 'notLoggedIn';
			}

			// 1. 商品库存不足
			if (this.goodsData.exchangeCount <= 0) {
				return 'soldOut';
			}

			// 2. 用户积分不足
			if (this.userStore && this.userStore.userInfo) {
				const userCredits = this.userStore.userInfo.credits || 0;
				if (userCredits < this.goodsData.points) {
					return 'insufficientCredits';
				}
			}

			// 3. 用户等级不足（检查vipLimit数组）
			if (this.goodsData.vipLimit && this.goodsData.vipLimit.length > 0 && this.userStore && this.userStore.userInfo) {
				const userLevel = this.userStore.userInfo.grade || 1;
				const userLevelName = this.getUserLevelName(userLevel);
				// 检查用户等级是否在vipLimit中
				if (!this.goodsData.vipLimit.includes(userLevelName)) {
					return 'insufficientLevel';
				}
			}

			// 4. 用户达到兑换上限（使用goodsLimit）
			if (this.goodsData.goodsLimit && this.userBuyLimit) {
				return 'exchangeLimit';
			}

			// 5. 商品状态检查
			if (this.goodsData.goodsState !== 1) {
				return 'disabled';
			}

			return 'canExchange';
		}
	},
	onLoad(options) {
		console.log('页面参数:', options);

		// 初始化用户状态
		this.initUserStatus();

		// 判断是否为秒杀兑换
		this.isSeckill = !!(options.activityId || options.sessionKey);
		
		if (this.isSeckill) {
			// 秒杀兑换参数
			this.seckillParams = {
				activityId: options.activityId || '',
				sessionKey: options.sessionKey || '',
				appGoodsId: options.appGoodsId || options.gid || options.id || options.goodsId || ''
			};
			
			// 构建秒杀API请求参数
			const seckillParams = {
				id: this.seckillParams.appGoodsId,
				phone: options.phone || '',
				buyNum: options.buyNum || '1',
				storeId: options.storeId || '',
				amount: options.amount || '',
				channel: options.channel || '',
				addressId: options.addressId || '',
				appGoodsId: this.seckillParams.appGoodsId,
				sessionKey: this.seckillParams.sessionKey
			};

			console.log('秒杀API请求参数:', seckillParams);

			if (seckillParams.id && seckillParams.appGoodsId && seckillParams.sessionKey) {
				this.fetchSeckillDetail(seckillParams);
			} else {
				uni.showToast({
					title: '秒杀参数不完整',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		} else {
			// 普通兑换参数
			const apiParams = {
				gid: options.gid || options.id || options.goodsId || '', // 商品ID (必须)
				skuld: options.skuld || '', // 商品规格ID (可选)
				buy_num: parseInt(options.buy_num) || 1, // 下单数量 (可选，默认1)
				phone: options.phone || '', // 充值号码 (可选)
				amount: options.amount || '', // 充值面额 (可选)
				couponId: options.couponId || '', // 优惠券ID (可选)
				remark: options.remark || '', // 下单备注 (可选)
				addressId: options.addressId || '', // 地址ID (可选)
				storeId: options.storeId || '', // 门店ID (可选)
				projectId: options.projectId || '' // 活动ID (可选)
			};

			console.log('普通兑换API请求参数:', apiParams);

			if (apiParams.gid) {
				this.fetchGoodsDetail(apiParams);
			} else {
				uni.showToast({
					title: '商品ID不能为空',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		}
	},
	onShow() {
		// 每次页面显示时重新检查用户状态
		this.checkUserStatus();
	},
	methods: {
		// 返回上一页
		navigateBack() {
			uni.navigateBack();
		},

		// 初始化用户状态
		async initUserStatus() {
			// 获取用户store实例
			this.userStore = useUserStore();

			// 加载会员信息
			await this.userStore.loadMemberInfo();

			// 检查用户状态
			this.checkUserStatus();
		},

		// 检查用户状态
		checkUserStatus() {
			if (!this.userStore) {
				this.cfgStatus.isRegister = false;
				return;
			}

			// 检查用户信息是否存在且有效
			const userInfo = this.userStore.userInfo;
			const memberId = userInfo?.memberId;

			// 如果memberId为"not_login"或不存在，则未登录
			if (!memberId || memberId === "not_login") {
				this.cfgStatus.isRegister = false;
				this.cfgStatus.showDetail = false;
			} else {
				this.cfgStatus.isRegister = true;
				// 根据宝宝阶段决定是否显示详情
				const babyInfo = this.userStore.babyInfo;
				this.cfgStatus.showDetail = babyInfo?.babyStage ? [1, 2].includes(babyInfo.babyStage) : false;
			}

			console.log('用户状态检查:', {
				userInfo,
				memberId,
				cfgStatus: this.cfgStatus
			});
		},

		// 获取商品详情
		async fetchGoodsDetail(params) {
			this.isLoading = true;
			console.log('开始获取商品详情，请求参数:', params);
			try {
				const response = await fetchGoodsDetail(params);
				console.log('商品详情接口返回:', response);

				if (response.ok && response.data) {
					const data = response.data;

					// 映射API数据到组件数据
					this.goodsData = {
						id: data.id || '',
						points: parseInt(data.credits) || 0,
						exchangeCount: data.stock || 0,
						saleCount: data.saleCount || 0, // 已兑换数量
						memberLevel: this.getMemberLevel(data.state),
						vipLimit: data.vipLimit || [], // 会员限制数组
						limit: data.groupCount ? data.groupCount.toString() : '1',
						goodsLimit: data.goodsLimit || false, // 商品购买限制
						name: data.goodsName || data.name || '',
						couponName: data.goodsName || data.name || '',
						expireDate: data.expireTime && data.expireTime.length > 0 ? data.expireTime[0] : '',
						remainDays: this.calculateRemainDays(data.expireTime),
						isSoldOut: data.stock <= 0,
						isInsufficientCredits: data.buttonText && data.buttonText.includes('积分不足'),
						goodsType: data.goodsType || data.type || '',
						goodsContent: data.goodsContent || data.content || '',
						goodsDeclare: data.goodsDeclare || '',
						goodsIcon: data.goodsIcon || data.icon || '',
						goodsImage: data.goodsImage || data.image || [],
						creditsType: data.creditsType || '',
						creditsTypeName: data.creditsTypeName || '',
						priceMarket: data.priceMarket || data.price_market || '',
						priceSale: data.priceSale || data.price_sale || '',
						buttonText: data.buttonText || data.button_text || '立即兑换',
						address: data.address || null,
						phone: data.phone || '',
						stores: data.stores || [],
						skus: data.skus || [],
						amount: data.amount || [],
						checkRule: data.checkRule || {},
						failRule: data.failRule || {},
						exchangeTime: data.exchangeTime || {},
						virtualConfig: data.virtualConfig || {},
						matnr: data.matnr || '',
						groupEnable: data.groupEnable || false,
						goodsState: data.state || 0
					};

					// 更新用户购买限制状态
					this.userBuyLimit = data.userBuyLimit || false;
					this.goodsLimit = data.goodsLimit || false;

					// 根据商品类型设置规格选项
					this.setSpecOptions(data.skus);

				} else {
					uni.showToast({
						title: response.msg || '获取商品详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取商品详情失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 获取秒杀商品详情
		async fetchSeckillDetail(params) {
			this.isLoading = true;
			console.log('开始获取秒杀商品详情，请求参数:', params);
			try {
				const response = await fetchSeckillDetail(params);
				console.log('秒杀商品详情接口返回:', response);

				if (response.ok && response.data) {
					const data = response.data;

					// 映射API数据到组件数据（秒杀商品数据结构可能与普通商品不同）
					this.goodsData = {
						id: data.id || '',
						points: parseInt(data.credits) || 0,
						exchangeCount: data.stock || 0,
						saleCount: data.saleCount || 0, // 已兑换数量
						memberLevel: this.getMemberLevel(data.state),
						vipLimit: data.vipLimit || [], // 会员限制数组
						limit: data.groupCount ? data.groupCount.toString() : '1',
						goodsLimit: data.goodsLimit || false, // 商品购买限制
						name: data.goodsName || data.name || '',
						couponName: data.goodsName || data.name || '',
						expireDate: data.expireTime && data.expireTime.length > 0 ? data.expireTime[0] : '',
						remainDays: this.calculateRemainDays(data.expireTime),
						isSoldOut: data.stock <= 0,
						isInsufficientCredits: data.buttonText && data.buttonText.includes('积分不足'),
						goodsType: data.goodsType || data.type || '',
						goodsContent: data.goodsContent || data.content || '',
						goodsDeclare: data.goodsDeclare || '',
						goodsIcon: data.goodsIcon || data.icon || '',
						goodsImage: data.goodsImage || data.image || [],
						creditsType: data.creditsType || '',
						creditsTypeName: data.creditsTypeName || '',
						priceMarket: data.priceMarket || data.price_market || '',
						priceSale: data.priceSale || data.price_sale || '',
						buttonText: data.buttonText || data.button_text || '立即兑换',
						address: data.address || null,
						phone: data.phone || '',
						stores: data.stores || [],
						skus: data.skus || [],
						amount: data.amount || [],
						checkRule: data.checkRule || {},
						failRule: data.failRule || {},
						exchangeTime: data.exchangeTime || {},
						virtualConfig: data.virtualConfig || {},
						matnr: data.matnr || '',
						groupEnable: data.groupEnable || false,
						goodsState: data.state || 0
					};

					// 更新用户购买限制状态
					this.userBuyLimit = data.userBuyLimit || false;
					this.goodsLimit = data.goodsLimit || false;

					// 根据商品类型设置规格选项
					this.setSpecOptions(data.skus);

					// 秒杀商品固定数量为1
					this.quantity = 1;

				} else {
					uni.showToast({
						title: response.msg || '获取秒杀商品详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取秒杀商品详情失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},

		// 根据商品状态获取会员等级
		getMemberLevel(goodsState) {
			// 根据goodsState映射到会员等级
			const stateMap = {
				1: '普通会员',
				2: '黄金会员',
				3: '铂金会员',
				4: '钻石会员'
			};
			return stateMap[goodsState] || '普通会员';
		},

		// 根据会员等级名称获取所需等级数字
		getRequiredLevel(memberLevelName) {
			const levelMap = {
				'普通会员': 1,
				'黄金会员': 2,
				'铂金会员': 3,
				'钻石会员': 4
			};
			return levelMap[memberLevelName] || 1;
		},

		// 根据等级数字获取等级名称
		getUserLevelName(level) {
			const levelMap = {
				1: '普通会员',
				2: '黄金会员',
				3: '铂金会员',
				4: '钻石会员'
			};
			return levelMap[level] || '普通会员';
		},

		// 计算剩余天数
		calculateRemainDays(expireTime) {
			if (!expireTime || expireTime.length === 0) return 0;

			const expireDate = new Date(expireTime[0]);
			const now = new Date();
			const diffTime = expireDate.getTime() - now.getTime();
			const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

			return diffDays > 0 ? diffDays : 0;
		},

		// 根据SKU设置规格选项
		setSpecOptions(skus) {
			// 确保 specOptions 始终是一个数组
			this.specOptions = [];

			if (!skus || skus.length === 0) {
				return;
			}

			// 从SKU中提取规格选项
			const specMap = new Map();
			skus.forEach(sku => {
				if (sku.specs && sku.specs.length > 0) {
					sku.specs.forEach(spec => {
						if (!specMap.has(spec.key)) {
							specMap.set(spec.key, []);
						}
						if (!specMap.get(spec.key).includes(spec.attr)) {
							specMap.get(spec.key).push(spec.attr);
						}
					});
				}
			});

			// 转换为规格选项格式
			specMap.forEach((values, key) => {
				values.forEach(value => {
					this.specOptions.push({
						label: value,
						value: value,
						key: key
					});
				});
			});

			// 设置默认选中第一个规格
			if (this.specOptions.length > 0) {
				this.selectedSpec = this.specOptions[0].value;
			}
		},

		// 检查用户等级是否符合要求
		checkUserLevel() {
			const levelMap = {
				'普通会员': 1,
				'黄金会员': 2,
				'铂金会员': 3,
				'钻石会员': 4
			};
			return levelMap[this.userLevel] >= levelMap[this.goodsData.memberLevel];
		},

		// 格式化数量显示
		formatCount(count) {
			if (count >= 10000) {
				return (count / 10000).toFixed(1) + '万';
			}
			return count.toString();
		},

		// 获取按钮样式类
		getButtonClass() {
			const classes = {};
			
			// 未登录状态
			if (!this.cfgStatus.isRegister) {
				return classes; // 未登录时保持正常样式
			}

			// 根据兑换状态添加对应样式
			switch (this.exchangeStatus) {
				case 'soldOut':
					classes['sold-out'] = true;
					break;
				case 'insufficientCredits':
					classes['insufficient-points'] = true;
					break;
				case 'insufficientLevel':
					classes['insufficient-level'] = true;
					break;
				case 'exchangeLimit':
					classes['exchange-limit'] = true;
					break;
				case 'disabled':
					classes['disabled'] = true;
					break;
				case 'canExchange':
				default:
					// 正常状态，不添加额外样式
					break;
			}

			return classes;
		},

		// 获取按钮文本
		getButtonText() {
			// 未登录状态
			if (!this.cfgStatus.isRegister) {
				return '立即兑换';
			}

			// 根据兑换状态返回对应文本
			switch (this.exchangeStatus) {
				case 'soldOut':
					return '已抢完';
				case 'insufficientCredits':
					return '积分不足';
				case 'insufficientLevel':
					return '等级不足';
				case 'exchangeLimit':
					return '已达兑换上限';
				case 'disabled':
					return this.goodsData.buttonText || '无法兑换';
				case 'canExchange':
				default:
					return '立即兑换';
			}
		},

		// 判断是否为实物商品
		isPhysicalGoods() {
			// 根据goodsType判断商品类型
			// Object("实物") - 实物商品
			// Card("卡密"), Charge("直冲"), Link("链接"), Virtual("虚拟") - 非实物商品
			return this.goodsData.goodsType === 'Object';
		},

		// 处理兑换
		handleExchange() {
			if (!this.cfgStatus.isRegister) {
				// 未登录，跳转到登录注册页面
				jump({
					type: JumpType.INNER,
					url: "/pages/activity/register",
				});
				return;
			}
			if (!this.canExchange) {
				this.showStatusMessage();
				return;
			}

			// 根据商品类型决定弹窗流程
			if (this.isPhysicalGoods()) {
				// 实物商品：显示规格选择弹窗
				this.showSpecModal = true;
			} else {
				// 非实物商品：直接显示兑换确认弹窗
				this.showConfirmModal = true;
			}
		},

		// 显示状态提示信息
		showStatusMessage() {
			let message = '';

			// 未登录状态
			if (!this.cfgStatus.isRegister) {
				message = '请先登录后再进行兑换';
			} else {
				// 根据兑换状态显示对应提示
				switch (this.exchangeStatus) {
					case 'soldOut':
						message = '商品库存不足，无法兑换';
						break;
					case 'insufficientCredits':
						message = '积分不足，无法兑换该商品';
						break;
					case 'insufficientLevel':
						message = '等级不足，无法兑换该商品';
						break;
					case 'exchangeLimit':
						message = '已达到兑换上限，无法继续兑换';
						break;
					case 'disabled':
						message = this.goodsData.buttonText || '无法兑换该商品';
						break;
					case 'canExchange':
					default:
						message = '可以兑换';
						break;
				}
			}

			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			});
		},

		// 关闭规格选择弹窗
		closeSpecModal() {
			this.showSpecModal = false;
		},

		// 选择规格
		selectSpec(value) {
			this.selectedSpec = value;
		},

		// 增加数量
		increaseQuantity() {
			if (this.goodsData.goodsLimit && this.quantity >= parseInt(this.goodsData.goodsLimit)) {
				return;
			}
			this.quantity++;
		},

		// 减少数量
		decreaseQuantity() {
			if (this.quantity > 1) {
				this.quantity--;
			}
		},

		// 确认规格选择
		async confirmSpecSelection() {
			this.closeSpecModal();
			
			// 实物商品：跳转到结算页面
			if (this.isPhysicalGoods()) {
				await this.navigateToSettlement();
			} else {
				// 非实物商品：显示兑换确认弹窗
				this.showConfirmModal = true;
			}
		},

		// 关闭弹窗
		closeModal() {
			this.showConfirmModal = false;
		},

		// 确认兑换
		async confirmExchange() {
			this.closeModal();
			
			// 非实物商品：直接下单
			if (!this.isPhysicalGoods()) {
				await this.exchangeGoods();
			}
		},

		// 兑换商品（仅处理非实物商品）
		async exchangeGoods() {
			try {
				uni.showLoading({
					title: '兑换中...'
				});

				if (this.isSeckill) {
					// 秒杀兑换：直接下单，不需要计算价格
					await this.createSeckillOrder();
				} else {
					// 普通兑换：先计算价格，再下单
					await this.calculatePrice();
					await this.createOrder();
				}

			} catch (error) {
				console.error('兑换失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: error.message || '兑换失败，请重试',
					icon: 'none'
				});
			}
		},

		// 计算商品价格
		async calculatePrice() {
			try {
				const priceParams = {
					gid: this.goodsData.id,
					buy_num: this.quantity,
					skuld: this.getSelectedSkuId(),
					...this.orderParams
				};

				console.log('计算价格参数:', priceParams);
				const response = await fetchGoodsPrice(priceParams);
				console.log('价格计算结果:', response);

				if (response.ok && response.data) {
					this.priceData = response.data;
					return response.data;
				} else {
					throw new Error(response.msg || '价格计算失败');
				}
			} catch (error) {
				console.error('价格计算失败:', error);
				throw error;
			}
		},

		// 获取选中的SKU ID
		getSelectedSkuId() {
			// 根据选中的规格找到对应的SKU ID
			if (this.goodsData.skus && this.goodsData.skus.length > 0) {
				const selectedSku = this.goodsData.skus.find(sku => {
					return sku.specs && sku.specs.some(spec =>
						spec.attr === this.selectedSpec
					);
				});
				return selectedSku ? selectedSku.id : '';
			}
			return '';
		},

		// 跳转到结算页面（实物商品）
		async navigateToSettlement() {
			try {
				uni.showLoading({
					title: '计算中...'
				});

				if (this.isSeckill) {
					// 秒杀商品：不需要计算价格，直接跳转
					uni.hideLoading();
				} else {
					// 普通商品：先计算价格
					await this.calculatePrice();
					uni.hideLoading();
				}

				// 构建结算页面参数
				const settlementParams = {
					// 基础订单参数
					gid: this.goodsData.id,
					skuld: this.getSelectedSkuId(),
					buy_num: this.quantity,
					
					// 商品信息
					goodsName: this.goodsData.name,
					goodsImage: this.goodsData.goodsImage && this.goodsData.goodsImage.length > 0 ? this.goodsData.goodsImage[0] : '',
					goodsSpec: this.selectedSpec || '',
					points: this.goodsData.points,
					creditsTypeName: this.goodsData.creditsTypeName || '积分',
					
					// 价格数据（秒杀商品可能没有价格数据）
					priceData: this.priceData ? JSON.stringify(this.priceData) : '',
					
					// 其他参数
					phone: this.orderParams.phone || '',
					amount: this.orderParams.amount || '',
					couponId: this.orderParams.couponId || '',
					remark: this.orderParams.remark || '',
					addressId: this.orderParams.addressId || '',
					storeId: this.orderParams.storeId || '',
					projectId: this.orderParams.projectId || '',
					
					// 秒杀相关参数
					isSeckill: this.isSeckill,
					activityId: this.seckillParams.activityId,
					sessionKey: this.seckillParams.sessionKey,
					appGoodsId: this.seckillParams.appGoodsId
				};

				console.log('结算页面参数:', settlementParams);

				// 跳转到结算页面
				uni.navigateTo({
					url: `/v3/settlementCenter/settlementCenter?${this.buildQueryString(settlementParams)}`
				});
			} catch (error) {
				console.error('跳转结算页面失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: error.message || '计算失败，请重试',
					icon: 'none'
				});
			}
		},

		// 创建订单
		async createOrder() {
			try {
				const orderParams = {
					gid: this.goodsData.id,
					buy_num: this.quantity,
					skuld: this.getSelectedSkuId(),
					...this.orderParams
				};

				console.log('下单参数:', orderParams);
				const response = await fetchTradeCredits(orderParams);
				console.log('下单结果:', response);

				if (response.ok && response.success) {
					this.orderResult = response.data;
					uni.hideLoading();

					// 跳转到支付结果页面
					this.navigateToPayResult(true, response.data);
				} else {
					throw new Error(response.msg || '下单失败');
				}
			} catch (error) {
				console.error('下单失败:', error);
				throw error;
			}
		},

		// 创建秒杀订单
		async createSeckillOrder() {
			try {
				const seckillOrderParams = {
					id: this.goodsData.id,
					phone: this.orderParams.phone || '',
					buyNum: this.quantity.toString(), // 秒杀固定为1
					storeId: this.orderParams.storeId || '',
					amount: this.orderParams.amount || '',
					channel: this.orderParams.channel || '',
					addressId: this.orderParams.addressId || '',
					appGoodsId: this.seckillParams.appGoodsId,
					sessionKey: this.seckillParams.sessionKey
				};

				console.log('秒杀下单参数:', seckillOrderParams);
				const response = await fetchSeckillTakeOrder(seckillOrderParams);
				console.log('秒杀下单结果:', response);

				if (response.ok && response.success) {
					this.orderResult = response.data;
					uni.hideLoading();

					// 跳转到支付结果页面
					this.navigateToPayResult(true, response.data);
				} else {
					throw new Error(response.msg || '秒杀下单失败');
				}
			} catch (error) {
				console.error('秒杀下单失败:', error);
				throw error;
			}
		},

		// 跳转到支付结果页面
		navigateToPayResult(isSuccess, orderData = null) {
			const resultParams = {
				// 基础结果参数
				isSuccess: isSuccess,
				orderId: orderData ? orderData.orderId : '',
				
				// 积分信息
				pointsValue: `${this.goodsData.points}${this.goodsData.creditsTypeName || '积分'}`,
				creditsTypeName: this.goodsData.creditsTypeName || '积分',
				
				// 商品信息
				goodsName: this.goodsData.name,
				goodsImage: this.goodsData.goodsImage && this.goodsData.goodsImage.length > 0 ? this.goodsData.goodsImage[0] : '',
				goodsSpec: this.selectedSpec || '',
				quantity: this.quantity,
				
				// 价格数据（秒杀商品可能没有价格数据）
				priceData: this.priceData ? JSON.stringify(this.priceData) : '',
				
				// 订单参数
				gid: this.goodsData.id,
				skuld: this.getSelectedSkuId(),
				buy_num: this.quantity,
				
				// 秒杀相关参数
				isSeckill: this.isSeckill,
				activityId: this.seckillParams.activityId,
				sessionKey: this.seckillParams.sessionKey,
				appGoodsId: this.seckillParams.appGoodsId
			};

			if (!isSuccess) {
				resultParams.failureReason = '兑换失败，请重试';
			}

			console.log('支付结果页面参数:', resultParams);

			uni.navigateTo({
				url: `/v3/payResultPage/payResultPage?${this.buildQueryString(resultParams)}`
			});
		},

		// 构建查询字符串
		buildQueryString(params) {
			return Object.keys(params)
				.map(key => `${key}=${encodeURIComponent(params[key])}`)
				.join('&');
		},

		// 处理图片加载错误
		handleImageError(e) {
			console.error('图片加载失败:', e);
		},

		// 处理图片加载成功
		handleImageLoad(e) {
			console.log('图片加载成功:', e);
		}
	}
}
</script>

<style scoped>
.container {
	width: 100%;
	min-height: 100vh;
	background-color: #f5f5f5;
	box-sizing: border-box;
}

/* 顶部导航栏 */
.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	background-color: #fff;
	padding: 0 30rpx;
	box-sizing: border-box;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
}

.nav-left,
.nav-right {
	width: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-title {
	font-size: 36rpx;
	font-weight: 500;
	color: #333;
}

.back-icon,
.nav-icon {
	font-size: 40rpx;
	color: #333;
}

.nav-right {
	justify-content: flex-end;
	gap: 30rpx;
}

/* 内容区域 */
.content {
	padding: 0 0 150rpx;
	box-sizing: border-box;
}

/* 商品图片轮播 */
.goods-carousel {
	width: 100%;
	height: 750rpx;
	margin-bottom: 20rpx;
}

.carousel-swiper {
	width: 100%;
	height: 100%;
}

.carousel-image {
	width: 100%;
	height: 100%;
	display: block;
}

/* 优惠券卡片 */
.coupon-card {
	width: 750rpx;
	height: 750rpx;
	background: linear-gradient(135deg, #f4e4bc 0%, #e8d5a3 100%);
	padding: 0;
	box-sizing: border-box;
	position: relative;
	overflow: hidden;
}



.coupon-detail {
	background-color: #d4af37;
	padding: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: relative;
}

.coupon-name {
	font-size: 28rpx;
	font-weight: 500;
	color: #fff;
}

.coupon-time {
	font-size: 24rpx;
	color: #fff;
	opacity: 0.9;
}

.coupon-logo {
	width: 60rpx;
	height: 60rpx;
	background-color: #fff;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.logo-text {
	font-size: 20rpx;
	color: #d4af37;
	font-weight: bold;
}

.coupon-tag {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	background-color: rgba(0, 0, 0, 0.3);
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

.tag-text {
	font-size: 22rpx;
	color: #fff;
}

/* 积分信息卡片 */
.points-card {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

/* 积分行 */
.points-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.points-left {
	display: flex;
	align-items: baseline;
}

.points-value {
	font-size: 48rpx;
	font-weight: bold;
	color: #e6a23c;
	margin-right: 10rpx;
}

.points-unit {
	font-size: 28rpx;
	font-weight: normal;
	color: #e6a23c;
}

.exchange-count {
	font-size: 26rpx;
	color: #999;
}

/* 会员标签 */
.member-tags {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.member-level {
	font-size: 24rpx;
	color: #D3A458;
	background-color: #FCF2E2;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

/* 购买限制区域 */
.purchase-limit-section {
	margin-bottom: 20rpx;
}

.purchase-limit {
	font-size: 24rpx;
	color: #D3A458;
	background-color: #FCF2E2;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
}

/* 优惠券标题 */
.coupon-title-section {
	margin-top: 10rpx;
}

.coupon-title-text {
	font-size: 30rpx;
	color: #333;
	font-weight: bold;
	line-height: 44rpx;
}

/* 详情信息 */
.detail-section {
	background-color: #fff;
	padding: 30rpx;
}

.detail-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 20rpx;
	display: block;
}

.detail-banner {
	width: 100%;
	min-height: 200rpx;
	background-color: #f8f8f8;
	padding: 30rpx;
	border-radius: 10rpx;
}

.banner-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.6;
}

/* 底部兑换按钮 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx 30rpx 40rpx;
	box-sizing: border-box;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.exchange-btn {
	width: 100%;
	height: 90rpx;
	background-color: #e6a23c;
	color: #fff;
	font-size: 32rpx;
	border-radius: 45rpx;
	line-height: 90rpx;
	padding: 0;
	border: none;
	transition: all 0.3s ease;
}

.exchange-btn:active {
	background-color: #d4902b;
}

.exchange-btn.disabled {
	background-color: #ccc;
	color: #999;
}

.exchange-btn.sold-out {
	background-color: #999;
	color: #fff;
}

.exchange-btn.insufficient-points {
	background-color: #f56c6c;
	color: #fff;
}

.exchange-btn.insufficient-level {
	background-color: #909399;
	color: #fff;
}

.exchange-btn.exchange-limit {
	background-color: #909399;
	color: #fff;
}

/* 规格选择弹窗样式 */
.spec-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: flex-end;
	justify-content: center;
	z-index: 1000;
}

.spec-modal-content {
	width: 750rpx;
	height: 1206rpx;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding: 40rpx 30rpx;
	box-sizing: border-box;
	position: relative;
}

.close-btn {
	position: absolute;
	top: 20rpx;
	right: 30rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.close-icon {
	font-size: 40rpx;
	color: #999;
}

/* 商品信息 */
.product-info {
	display: flex;
	align-items: center;
	margin-bottom: 60rpx;
	padding-top: 20rpx;
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.image-placeholder {
	font-size: 24rpx;
	color: #999;
}

.product-details {
	flex: 1;
}

.product-points {
	font-size: 32rpx;
	font-weight: bold;
	color: #e6a23c;
	margin-bottom: 10rpx;
	display: block;
}

.product-stock {
	font-size: 26rpx;
	color: #999;
	display: block;
}

/* 规格选择 */
.spec-section {
	margin-bottom: 60rpx;
}

.spec-label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 20rpx;
	display: block;
}

.spec-options {
	display: flex;
	gap: 20rpx;
}

.spec-option {
	padding: 16rpx 32rpx;
	border-radius: 20rpx;
	background-color: #f5f5f5;
	border: 2rpx solid transparent;
	transition: all 0.3s ease;
}

.spec-option.active {
	background-color: #fcf2e2;
	border-color: #d3a458;
}

.spec-text {
	font-size: 26rpx;
	color: #333;
}

.spec-option.active .spec-text {
	color: #d3a458;
	font-weight: 500;
}

/* 数量选择 */
.quantity-section {
	margin-bottom: 80rpx;
}

.quantity-label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	margin-bottom: 20rpx;
	display: block;
}

.limit-text {
	font-size: 24rpx;
	color: #999;
	font-weight: normal;
}

.quantity-selector {
	display: flex;
	align-items: center;
	gap: 0;
	border: 2rpx solid #A8A8A8;
	border-radius: 8rpx;
	padding: 0;
	width: fit-content;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border-right: 1rpx solid #A8A8A8;
	background-color: #fff;
	color: #A8A8A8;
	font-size: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.quantity-btn:last-child {
	border-right: none;
	border-left: 1rpx solid #A8A8A8;
}

.quantity-btn:disabled {
	border-color: #ccc;
	color: #ccc;
}

.quantity-value {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
	min-width: 80rpx;
	text-align: center;
	padding: 0 20rpx;
}

/* 秒杀商品数量显示 */
.quantity-display {
	display: flex;
	align-items: center;
	gap: 0;
	border: 2rpx solid #A8A8A8;
	border-radius: 8rpx;
	padding: 0;
	width: fit-content;
}

.quantity-display .quantity-value {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
	min-width: 80rpx;
	text-align: center;
	padding: 0 20rpx;
}

/* 确认按钮 */
.confirm-spec-btn {
	width: 680rpx;
	height: 100rpx;
	background-color: #D3A458;
	color: #fff;
	font-size: 32rpx;
	border-radius: 50rpx;
	border: none;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: center;
	position: absolute;
	bottom: 100rpx;
	left: 50%;
	transform: translateX(-50%);
}

.confirm-spec-btn:active {
	background-color: #B8944A;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	width: 546rpx;
	height: 418rpx;
	background: linear-gradient(to bottom, #FFE9C5 0%, #FFFFFF 50%);
	border-radius: 20rpx;
	padding: 40rpx;
	box-sizing: border-box;
	position: relative;
	display: flex;
	flex-direction: column;
}

/* 关闭按钮 */
.modal-close-btn {
	width: 56rpx;
	height: 56rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 40rpx auto 0;
	background-color: #B0B0B0;
	border-radius: 50%;
}

.modal-close-icon {
	font-size: 40rpx;
	color: #fff;
}

.modal-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #D3A458;
	text-align: center;
	margin-bottom: 30rpx;
}

.modal-message {
	font-size: 28rpx;
	color: #333;
	text-align: center;
	margin-bottom: 40rpx;
	line-height: 40rpx;
}

.modal-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: 25rpx;
}

.modal-btn {
	flex: 1;
	height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cancel-btn {
	background-color: #fff;
	color: #D3A458;
	border: 2rpx solid #D3A458;
}

.confirm-btn {
	background-color: #D3A458;
	color: #fff;
}

.modal-disclaimer {
	font-size: 22rpx;
	color: #999;
	text-align: center;
	line-height: 32rpx;
	margin-top: auto;
	padding-bottom: 0;
}
</style>
