<template>
	<view>
		<view class="header">
			<view class="searchBox" :style="{ height: localHeight + 'px', paddingTop: top + 'px' }">
				<view class="searchBox_left" @click="back">
					<u-icon name="arrow-left" size="20px" color="#000"></u-icon>
				</view>
			</view>
		</view>
		<view class="swiper">
			<view v-if="currentGG.is_same_day" class="tag tag-img">
				当日达
			</view>
			<swiper :indicator-dots="false" :autoplay="true" :interval="3000" :duration="1000" @change="changeIndex">
				<swiper-item v-for="(item, index) in currentGG.goods_carousel" :key="index">
					<image :src="picUrl + item"></image>
				</swiper-item>
			</swiper>

			<view class="NumDot">
				{{ currentIndex }} / {{ currentGG.goods_carousel ? currentGG.goods_carousel.length : 0 }}
			</view>
		</view>

		<view class="Money">
			<view class="MoneyMark">￥</view>
			{{ currentGG.sales_price }}
			<view class="MoneyUnit">/{{ currentGG.goods_unit }}</view>

			<view class="oldMoney">￥{{ currentGG.market_price }}</view>
			<view class="integral" v-if="currentGG.available_points_count > 0">可得{{ currentGG.available_points_count }}个积分</view>
		</view>

		<!-- 规格 -->
		<!-- @click="changeGG2(item, index)" :class="index == currentGGIndex ? 'active' : ''"> -->
		<view class="GGBox">
			<view class="GG_left">
				<view class="GG_Item" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
					@click="changeGG(item, index)" :class="index == currentGGIndex ? 'active' : ''">
					{{ item.goods_spec }} / {{ item.goods_unit }}
				</view>
			</view>
			<view class="GG_rigth" @click="showSizePopup">
				共{{ info.commodity_goods_info_list ? info.commodity_goods_info_list.length : 0 }}款
				<u-icon size="26rpx" name="arrow-right"></u-icon>
			</view>
		</view>

		<!-- 优惠劵区域 -->
		<view class="coupon_container" v-if="coupons.length > 0">
			<view class="coupon" :class="{ 'coupon_used1': coupon.is_received }" v-for="(coupon, index) in coupons"
				:key="index">
				<view class="coupon_amount">¥{{ coupon.money }}</view>
				<view class="coupon_condition" v-if="coupon.full_amount != 0">满{{ coupon.full_amount }}元可用</view>
				<view class="coupon_condition" v-else>无门槛</view>
				<view class="coupon_status" @click="handleCouponClick(coupon)">{{ coupon.is_received ? '已领' : '领取' }}
				</view>
			</view>
			<view class="more_coupon" @click="showCouponPopup = true">
				<view class="more_text">更多优惠</view>
				<u-icon name="arrow-right" color="#FF370B" size="28" />
			</view>
		</view>

		<view class="Tit">
			<view class="isDay" v-if="currentGG.is_same_day">当日达</view>
			<view>{{ currentGG.goods_name }}</view>
		</view>
		<view class="Msg">{{ currentGG.commodity_brief }}</view>

		<view class="fenge"></view>

		<!-- 促销信息区域 -->
		<!-- <view class="promotions-container">
			<view class="promotion-item">
				<view class="promotion-tag">优惠</view>
				<view class="promotion-content promotion-content1">满100减10</view>
			</view>
			<view class="promotion-item">
				<view class="promotion-tag">限购</view>
				<view class="promotion-content">限购5件</view>
			</view>
			<view class="promotion-item">
				<view class="promotion-tag">阶梯价</view>
				<view class="promotion-content">1~9件 9.5元/件;>10件 8.0元/件</view>
			</view>
			<view class="promotion-item">
				<view class="promotion-tag">满赠</view>
				<view class="promotion-content">满5赠1，满10赠3</view>
			</view>
			<view class="promotion-item">
				<view class="promotion-tag">满减</view>
				<view class="promotion-content">满100减5，满200减20</view>
			</view>
		</view> -->

		<view class="fenge"></view>

		<view class="Msg_Item">
			<view class="Msg_ItemTit">质检</view>
			<view class="Msg_ItemCon">质检报告</view>
		</view>
		<view class="Msg_Item">
			<view class="Msg_ItemTit">押金</view>
			<view class="Msg_ItemCon">需另付押金:￥30.00(30天可退)</view>
		</view>
		<view class="Msg_Item">
			<view class="Msg_ItemTit">配送</view>
			<view class="Msg_ItemCon"> 12:00前下单,预计8月21日送达; </view>
		</view>
		<view class="fenge"></view>

		<!-- 评价部分 -->
		<view class="reviews-section">
			<view class="reviews-header">
				<h3>评价({{ comments.length ? comments.length : 0 }})</h3>
				<view class="view-all" @click="showPopup">查看全部 ></view>
			</view>
			<view class="reviews-list" v-if="comments.length > 0">
				<view class="review-item" v-for="(comment, index) in comments" :key="index">
					<view class="review-user">
						<image :src="comment.mpuser.avatar" class="user-avatar"></image>
						<view class="user-info">
							<view class="user-name">{{ comment.mpuser.nick_name }}</view>
						</view>
						<view class="review-time">{{ comment.create_time }}</view>
					</view>
					<view class="user-purchase">已购 {{ comment.goods_name.goods_name }}{{ comment.goods_name.goods_spec
					}}</view>
					<view class="review-content">{{ comment.user_review }}</view>
					<view class="review-images" v-if="comment.review_image.length > 0">
						<image :src="img" class="review-img" v-for="(img, idx) in comment.review_image" :key="idx">
						</image>
					</view>
				</view>
			</view>
		</view>

		<view class="fenge"></view>

		<h3 class="GoodsMsg">商品详情</h3>

		<view class="Msg_Item">
			<view class="Msg_ItemTit">商品编号</view>
			<view class="Msg_ItemCon" @click="copys(currentGG.goods_no)">
				{{ currentGG.goods_no }}
				<image src="https://static.hshuishang.com/property-img-file/shop_copy.png">
				</image>
			</view>
		</view>
		<view class="Msg_Item">
			<view class="Msg_ItemTit">规格说明</view>
			<view class="Msg_ItemCon">{{ currentGG.goods_spec }}</view>
		</view>
		<view class="Msg_Item">
			<view class="Msg_ItemTit">售卖单位</view>
			<view class="Msg_ItemCon">{{ currentGG.goods_unit }}</view>
		</view>

		<view class="GoosMsg">
			<image v-for="item in currentGG.goods_detail_pic" :src="picUrl + item" :key="item" mode="widthFix"></image>
		</view>

		<view class="priceInfo">
			<h3 class="priceInfo-title">价格说明</h3>
			<view class="priceInfo-content">
				<view>
					<text class="priceInfo-content-title">划线价格：</text>
					指商品的厂商指导价、正品零售价、市面常见价或该商品曾经展示过的销售价等，并非原价。仅供参考。
				</view>
				<view>
					<text class="priceInfo-content-title">未划线价格：</text>
					指商品的实时价格，不因表述的差异改变性质，具体成交价格根据商品参加活动，或使用优惠券等发生变化最终以订单结算价格为准。
				</view>
			</view>
		</view>

		<!-- 底部购物车 -->
		<view class="Car">
			<view class="car_left">
				<view class="share" @click="share">
					<image src="https://static.hshuishang.com/property-img-file/shop_share.png" mode="widthFix"></image>
					分享
				</view>
				<view class="cars" @click="car">
					<u-badge numberType="limit" :type="type" max="99" :value="carNum"></u-badge>

					<image src="https://static.hshuishang.com/property-img-file/shop_car.png" mode="widthFix"></image>
					购物车
				</view>
			</view>

			<view class="car_right_box">
				<view class="car_right" v-if="
					info.commodity_goods_info_list[currentGGIndex].stock_quantity > 0 &&
					(!info.commodity_goods_info_list[currentGGIndex].cart_count ||
						info.commodity_goods_info_list[currentGGIndex].cart_count.count == 0)
				" @click="addCar">
					加入购物车
				</view>

				<view class="car_right" @click="changeCar" v-if="
					info.commodity_goods_info_list[currentGGIndex].cart_count.count > 0
					&& info.commodity_goods_info_list[currentGGIndex].stock_quantity > 0
				">
					加入购物车
				</view>

				<view class="seckill" v-if="info.commodity_goods_info_list[currentGGIndex].stock_quantity != 0"
					@click="showBuyPopup">
					立即购买
				</view>
			</view>

			<view class="car_right2" v-if="info.commodity_goods_info_list[currentGGIndex].stock_quantity < 1">
				已售罄
			</view>
		</view>

		<!-- 分享 -->
		<view class="shadow" @click.stop="changeShadow" v-if="boxshadow1">
			<view class="shadowBox1">
				<button class="shadowBox1Item_btn" open-type="share" bindtap="onShareButtonClick" />
				<view class="shadowBox1Item" @click="shareFriend">
					<image src="https://static.hshuishang.com/property-img-file/shop_WX.png" mode="aspectFill"></image>
					微信好友
				</view>
				<view class="shadowBox1Item" @click="openSave">
					<image src="https://static.hshuishang.com/property-img-file/shop_saveImg.png" mode="aspectFill">
					</image>
					生成海报
				</view>
			</view>
		</view>
		<!-- 海报 -->
		<view class="shadow" @click="changeShadow2" v-if="boxshadow2">
			<view class="shadowBox2">
				<view class="shadowBox_img">
					<view class="boxshadow_tit">今日商品推荐</view>
					<view class="boxshadow_img">
						<image v-if="currentGG && currentGG.commodity_pic && currentGG.commodity_pic.length > 0"
							:src="picUrl + currentGG.commodity_pic[0]">
						</image>
						<image v-else src="https://static.hshuishang.com/property-img-file/shop_share_img.png">
						</image>
					</view>
					<view class="line"></view>
					<view class="shadowBoxInfo">
						<image class="shadowboxInfo_left"
							:src="qrcodePath || 'https://static.hshuishang.com/property-img-file/qrcode_placeholder.png'"
							mode="aspectFill"></image>
						<view class="shadowboxInfo_right">
							<view class="shadowboxInfo_right_1">{{ currentGG && currentGG.goods_name ?
								currentGG.goods_name : '' }}</view>
							<view class="shadowboxInfo_right_2">
								长按识别小程序 <br />
								数量有限马上抢购
							</view>
						</view>
					</view>
				</view>
				<view class="shadowBox_btn" @click.stop="saveImg(picUrl + currentGG.commodity_pic[0])">保存海报</view>
			</view>
		</view>

		<!-- 评价 查看详情 -->
		<u-popup :show="show" round="20rpx" mode="bottom" @close="close" @open="open" :z-index="10070">
			<view class="reviews-section">
				<view class="popup-header">
					<h3 class="popup-header-h3">评价</h3>
					<view class="popup-header-view" @click="close">取消</view>
				</view>
				<view class="temp">
					<view class="temp1">
						<img class="temp_img" src="https://static.hshuishang.com/pingjia.png" />
						为你展示真实评价
					</view>
					<view class="temp1" @click="showSizePopup">
						款式
						<img class="temp_img1" src="https://static.hshuishang.com/kuanshi.png" />
					</view>
				</view>
				<view class="reviews-list" v-if="comments.length > 0">
					<view class="review-item" v-for="(comment, index) in comments" :key="index">
						<view class="review-user">
							<image :src="comment.mpuser.avatar" class="user-avatar"></image>
							<view class="user-info">
								<view class="user-name">{{ comment.mpuser.nick_name }}</view>
							</view>
							<view class="review-time">{{ comment.create_time }}</view>
						</view>
						<view class="user-purchase">已购 {{ comment.goods_name.goods_name }}{{
							comment.goods_name.goods_spec }}</view>
						<view class="review-content">{{ comment.user_review }}</view>
						<view class="review-images" v-if="comment.review_image.length > 0">
							<image :src="img" class="review-img" v-for="(img, idx) in comment.review_image" :key="idx">
							</image>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 优惠详情弹窗 -->
		<u-popup :show="showCouponPopup" width="650rpx" height="800rpx" round="20rpx">
			<view class="coupon_popup">
				<view class="popup_header">
					<view class="popup_title">优惠详情</view>
					<view class="popup_close" @click="showCouponPopup = false">取消</view>
				</view>
				<view class="popup_content">
					<view class="coupon_item" v-for="(item, index) in couponDetails" :key="index">
						<view class="coupon_item_left">
							<view class="coupon_item_amount">¥{{ item.money }}</view>
							<view class="coupon_item_condition" v-if="item.full_amount != 0">满{{ item.full_amount }}元可用
							</view>
							<view class="coupon_item_condition" v-else>无门槛</view>
						</view>
						<view class="coupon_item_center">
							<view class="coupon_item_name">{{ item.red_package_name }}</view>
							<view class="coupon_item_expire">{{ item.end_time }}到期</view>
						</view>
						<view class="coupon_item_right">
							<view class="coupon_item_button" @click="handleCouponClick(item)">{{ item.is_received ? '已领'
								: '领取' }}</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 选择款式 -->
		<u-popup :show="showSize" round="20rpx" mode="bottom" @close="closeSize" @open="open">
			<!-- <view  round="20rpx" mode="bottom"> -->
			<view class="popup-header">
				<h3 class="popup-header-h3">选择款式</h3>
				<view class="popup-header-view" @click="closeSize">取消</view>
			</view>
			<view class="itemSize_top">
				<image :src="changeImg" class="itemSize-img">
					<view v-if="currentGG.is_same_day" class="isDay"
						style="position: absolute; font-size: 16rpx; height: 20rpx; z-index: 100;">当日达</view>
				</image>
				<view class="itemSize_info">
					<view class="itemSize_name" style="display: flex;">
						<view v-if="currentGG.is_same_day" class="isDay">当日达</view>{{ changeName }}
					</view>
					<view class="itemSize_price">￥{{ changePrice }}/{{ goodsUnit }}</view>
				</view>
			</view>
			<view class="itemSizeBox" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
				@click="changeGG(item, index)">
				<text class="itemSize" :class="index == currentGGIndex ? 'itemSize_active' : ''">{{ item.goods_name }}
					{{ item.goods_spec }} / {{ item.goods_unit }}</text>
			</view>
		</u-popup>

		<!-- 立即购买 -->
		<u-popup :show="showBuy" round="20rpx" mode="bottom" @close="closeBuy">
			<view class="popup-header">
				<h3 class="popup-header-h3">立即购买</h3>
				<view class="popup-header-view" @click="closeBuy">取消</view>
			</view>
			<view class="address-section">
				<view class="address-info" @click="editAddress()">
					<view class="address-main" v-if="defAddress && Object.keys(defAddress).length > 0">
						<view class="address-name-phone">
							<text class="name">{{ defAddress.name }}</text>
							<text class="phone">{{ defAddress.phone }}</text>
						</view>
						<view class="address-detail">
							{{ defAddress.address }}{{ defAddress.house_number }}
							<view class="copy-icon" @click.stop="copyAddress" />
						</view>
					</view>
					<view class="address-main" v-else>
						<view class="address-name-phone">
							<text class="name">请选择收货地址</text>
						</view>
					</view>
					<view class="address-arrow"><u-icon name="arrow-right" size="25"></u-icon></view>
				</view>
			</view>
			<view class="itemSize_top">
				<image :src="changeImg" class="itemSize-img"></image>
				<view class="itemSize_info">
					<view class="itemSize_name">{{ changeName }}</view>
					<view class="itemSize_price">￥{{ changePrice }}/{{ goodsUnit }}</view>
				</view>
				<view class="quantity-control">
					<view class="decrease-btn" @tap.stop="decreaseQuantity()">-</view>
					<view class="quantity">{{ changeCount }}</view>
					<view class="increase-btn" @tap.stop="increaseQuantity()">+</view>
				</view>
			</view>
			<view class="itemSize" v-for="(item, index) in info.commodity_goods_info_list" :key="item.id"
				@click="changeGG(item, index)" :class="index == currentGGIndex ? 'itemSize_active' : ''">
				{{ item.goods_name }} {{ item.goods_spec }} / {{ item.goods_unit }}
			</view>
			<view class="fenge"></view>
			<!-- 支付方式 -->
			<view class="payment-section">
				<view class="payment-item" @click="selectPayment('wechat')">
					<view class="payment-icon">
						<image src="https://static.hshuishang.com/property-img-file/com_wechat.png" mode="aspectFit">
						</image>
					</view>
					<view class="payment-content">
						<view class="payment-name">微信支付</view>
					</view>
					<view class="payment-select" v-if="selectedPayment === 'wechat'">
						<image src="https://static.hshuishang.com/property-img-file/com_check2.png" mode="aspectFit"
							style="width: 30rpx; height: 30rpx;"></image>
					</view>
					<view class="payment-select" v-else>
						<image src="https://static.hshuishang.com/property-img-file/com_check1.png" mode="aspectFit"
							style="width: 30rpx; height: 30rpx;"></image>
					</view>
				</view>
			</view>
			<view class="pay-button" @click="submitBuyOrder">立即支付</view>
		</u-popup>
	</view>
</template>

<script>
import {
	apiArr
} from "../../../api/shop";
import { apiArr as apiArr2 } from "../../../api/user";
import {
	picUrl,
	menuButtonInfo,
	request,
	NavgateTo
} from "../../../utils";
export default {
	data() {
		return {
			picUrl,
			top: "",
			localHeight: "",
			carNum: "",
			prevCarNum: "",
			currentNum: "0", //当前商品的数量
			type: "error",
			boxshadow1: false,
			boxshadow2: false,
			id: "184",
			info: "",
			currentIndex: "1", //当前轮播图

			currentGG: "", //当前选中规格
			currentGGIndex: "", //当前规格index

			carOrderList: [],
			// 新增评论数据
			showReviewPopup: false,
			comments: [],
			show: false,
			showSize: false,
			// 立即购买相关
			showBuy: false,
			changeCount: 0,
			defAddress: {},
			selectedPayment: 'wechat', // 默认微信支付

			changeImg: "",
			changeName: "",
			changePrice: "",
			goodsUnit: "",
			selectedGoods: null, // 保存传入的商品规格信息
			qrcodePath: null, // 存储当前页面的二维码路径
			// 红包相关
			coupons: [],
			couponDetails: [],
			showCouponPopup: false
		};
	},
	methods: {
		changeIndex(e) {
			this.currentIndex = e.detail.current + 1;
		},

		back() {
			uni.navigateBack({
				delta: 1,
			});
		},
		// 分享微信
		shareFriend() {
			this.boxshadow2 = false;
			return;
			// uniapp 分享微信好友
			uni.share({
				provider: "weixin",
				type: "link",
				scene: "session",
				link: "https://uniapp.dcloud.net.cn/",
				title: "商品名称",
				imageUrl: "",
				success: (res) => {
					uni.showToast({
						title: "分享成功",
						icon: "success",
						duration: 2000,
					});
					this.boxshadow1 = false;
				},
				fail: (err) => {
					console.log("分享失败", err);
					this.boxshadow1 = false;
				},
			});
		},
		changeShadow() {
			this.boxshadow1 = false;
		},
		openSave() {
			this.boxshadow1 = false;
			this.boxshadow2 = true;
		},
		// 保存海报
		saveImg(picUrl) {
			this.boxshadow2 = false;
			// 微信小程序保存图片
			uni.downloadFile({
				url: picUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: (res) => {
								uni.showToast({
									title: "保存成功",
									icon: "success",
									duration: 2000,
								});
							},
							fail: (err) => {
								console.log("保存失败", err);
							},
						});
					}
				},
				fail: (err) => {
					console.log("下载失败", err);
				},
			});
		},
		changeShadow2() {
			this.boxshadow2 = false;
		},

		// 点分享按钮
		share() {
			this.boxshadow1 = true;
		},
		//商品详情
		getGoodsInfo() {
			request(apiArr.getGoodsInfo, "POST", {
				id: this.id,
			}).then((res) => {

				// 分割图片
				res.commodity_goods_info_list.forEach((item) => {
					item.goods_detail_pic = item.goods_detail_pic.split(",");
					item.goods_carousel = item.goods_carousel.split(",");
					item.commodity_pic = item.commodity_pic.split(",");
				});

				//根据购物车列表 和 当前商品列表 来更新当前商品列表在购物车中的数量
				if (this.carOrderList) {
					this.carOrderList.forEach((items) => {
						res.commodity_goods_info_list.forEach((item) => {
							if (items.goods_id == item.id) {
								item.cart_count = {
									count: 0
								};
								item.cart_count.count = items.count;
							}
						});
					});
				}
				this.info = res;

				// 检查是否有传入的选中商品信息，如果有则设置为默认选中
				let selectedIndex = 0;
				if (this.selectedGoods) {
					for (let i = 0; i < res.commodity_goods_info_list.length; i++) {
						if (res.commodity_goods_info_list[i].id === this.selectedGoods.id) {
							selectedIndex = i;
							break;
						}
					}
				}

				this.currentGG = res.commodity_goods_info_list[selectedIndex];
				console.log("this.currentGG", this.currentGG);
				this.currentGGIndex = selectedIndex;

				this.changeImg = picUrl + this.currentGG.commodity_pic[0]
				this.changeName = this.currentGG.goods_alias
				this.changePrice = this.currentGG.sales_price
				this.goodsUnit = this.currentGG.goods_unit
			});
		},

		copys(e) {
			uni.setClipboardData({
				data: e,
				success: (res) => {
					uni.showToast({
						title: "复制成功",
						icon: "success",
						duration: 2000,
					});
				},
			});
		},

		// 切换规格
		changeGG(item, index) {
			this.currentGG = item;
			this.currentGGIndex = index;
			if (this.currentGG.cart_count) {
				this.currentNum = this.currentGG.cart_count.count;
			} else {
				this.currentGG.cart_count = {
					count: 0
				};
			}
			this.changeImg = picUrl + item.commodity_pic[0]
			this.changeName = item.goods_alias
			this.changePrice = item.sales_price
			this.goodsUnit = item.goods_unit
			this.getComment(item.goods_id)
		},
		// 立即购买相关方法
		showBuyPopup() {
			this.changeCount = 1;
			this.showBuy = true;
			// 检查是否有选中的地址
			const selectedAddress = uni.getStorageSync('selectedAddress');
			if (selectedAddress && Object.keys(selectedAddress).length > 0) {
				this.defAddress = selectedAddress;
				// 清除选中状态，避免重复应用
				uni.removeStorageSync('selectedAddress');
			} else {
				// 如果没有选中的地址，则获取默认地址
				this.getUserAddress();
			}
		},
		closeBuy() {
			this.showBuy = false;
			uni.removeStorageSync('selectedAddress');
			this.changeCount = 1;
		},
		editAddress() {
			NavgateTo('/packages/shop/address/index');
		},
		// 数量加减
		decreaseQuantity() {
			if (this.changeCount > 1) {
				this.changeCount--;
			}
		},
		increaseQuantity() {
			const stock = this.info.commodity_goods_info_list[this.currentGGIndex].stock_quantity;
			if (this.changeCount < stock) {
				this.changeCount++;
			} else {
				uni.showToast({
					title: '库存不足',
					icon: 'none'
				});
			}
		},
		// 获取默认收货地址
		getUserAddress() {
			request(apiArr.getUserDefAddress, "POST", {}).then(res => {
				this.defAddress = res.default_address;
			});
		},
		// 选择支付方式
		selectPayment(type) {
			this.selectedPayment = type;
		},
		// 复制收货地址
		copyAddress() {
			if (this.defAddress && Object.keys(this.defAddress).length > 0) {
				uni.setClipboardData({
					data: this.defAddress.address + this.defAddress.house_number,
					success: () => {
						uni.showToast({
							title: '地址复制成功',
							icon: 'success'
						});
					}
				});
			}
		},
		car() {
			NavgateTo("../shopCar/index");
		},

		//获取购物车数量
		// getShopCar() {
		// 	request(apiArr.getCarCount, "POST", {}).then((res) => {
		// 		this.prevCarNum = res.total;
		// 	});
		// },

		getShopCarList() {
			return request(apiArr.getCar, "POST", {}).then((res) => {
				// 合并当日达和普通商品数据
				this.carOrderList = [].concat(res.same_day_cart_list, res.normal_cart_list)
					.flatMap(supplier => supplier.commodity_cart_and_goods_model);
				this.carNum = res.total;
				this.prevCarNum = res.total;
				return res;
			});
		},

		addCar() {
			let that = this;
			// 获取当前商品
			const currentGoods = this.info.commodity_goods_info_list[this.currentGGIndex];

			// 获取当前购物车数量和库存数量
			const currentQuantity = currentGoods.cart_count ? currentGoods.cart_count.count : 0;
			const stockQuantity = currentGoods.stock_quantity || 0;

			// 检查库存是否充足
			if (currentQuantity >= stockQuantity) {
				uni.showToast({
					title: "库存不足",
					icon: "none",
					duration: 2000
				});
				return;
			}

			//如果没有当前商品 直接添加一个
			this.info.commodity_goods_info_list[this.currentGGIndex].cart_count = {
				count: currentQuantity + 1,
			};
			const params = {
				goods_id_and_count: [
					{
						goods_id: this.info.commodity_goods_info_list[this.currentGGIndex].id,
						count: this.info.commodity_goods_info_list[this.currentGGIndex].cart_count.count,
					},
				],
			};

			//因为是当前商品没有 调用update就是增加商品。增加商品之后再获取购物车数量
			request(apiArr.updateCar, "POST", params).then((res) => {
				// that.getShopCar();
				that.getShopCarList();
			});
		},

		// 购物车更改
		changeCar() {
			// 直接增加商品数量，与addCar逻辑类似
			const currentGoods = this.info.commodity_goods_info_list[this.currentGGIndex];
			const currentQuantity = currentGoods.cart_count ? currentGoods.cart_count.count : 0;
			const stockQuantity = currentGoods.stock_quantity || 0;

			// 检查库存是否充足
			if (currentQuantity >= stockQuantity) {
				uni.showToast({
					title: "库存不足",
					icon: "none",
					duration: 2000
				});
				return;
			}

			// 增加商品数量
			currentGoods.cart_count = {
				count: currentQuantity + 1,
			};

			const params = {
				user_id: uni.getStorageSync("userId"),
				goods_id_and_count: [{
					goods_id: currentGoods.id,
					count: currentGoods.cart_count.count,
				}],
			};

			request(apiArr.updateCar, "POST", params).then((res) => {
				console.log(res);
				this.getShopCarList();
				// this.getShopCar();
				uni.showToast({
					title: "操作成功！",
					success() { },
				});
			});
		},

		showPopup() {
			this.show = true;
		},

		showSizePopup() {
			this.showSize = true;
		},

		close() {
			this.show = false;
		},

		closeSize() {
			this.showSize = false;
		},
		// 提交立即购买订单
		submitBuyOrder() {
			// 检查是否选择了收货地址
			if (!this.defAddress || !this.defAddress.address) {
				uni.showToast({
					title: '请选择收货地址',
					icon: 'none'
				});
				return;
			}

			// 根据平台设置不同的trans_type值
			// 小程序: 71, App: 51
			const systemInfo = uni.getSystemInfoSync();
			let trans_type = 51; // 默认App环境

			// 运行时判断是否为小程序环境
			if (systemInfo.platform === 'devtools' || systemInfo.platform === 'unknown') {
				trans_type = 71; // 开发工具或未知环境默认为小程序
			}

			// 条件编译：针对不同平台设置不同值
			// #ifdef MP
			trans_type = 71; // 所有小程序平台
			// #endif

			// #ifdef APP-PLUS
			trans_type = 51; // App平台
			// #endif

			// 原始逻辑：创建订单后再进行支付
			const params = {
				user_id: uni.getStorageSync('userId'),
				// 固定设置为1
				order_cate: 1,
				goods_list: [{
					supplier_id: this.info.supplier_id,
					supplier_name: this.info.merchant_info.merchant_name || '',
					is_same_day: this.currentGG.is_same_day,
					receiving_name: this.defAddress.name,
					receiving_phone: this.defAddress.phone,
					receiving_address: this.defAddress.address + this.defAddress.house_number,
					merchant_id: this.defAddress.address_id,
					goods_and_count: [{
						goods_id: this.currentGG.id,
						count: this.changeCount,
						price: this.currentGG.sales_price
					}]
				}]
			}
			console.log("🚀 ~ params:", params)

			request(apiArr.createOrder, "POST", params).then(resVal => {
				const param = {
					order_id: resVal.order_id,
					user_id: uni.getStorageSync('userId'),
					trans_type: trans_type
				}
				request(apiArr.mergePreorder, "POST", param).then(res => {
					this.handleMergePreorderResponse(res, resVal.order_id);
				})
			})
		},
		// 处理mergePreorder接口的响应
		handleMergePreorderResponse(res, orderId) {
			if (res && res.timeStamp && res.nonceStr && res.package && res.signType && res.paySign) {
				// 调用微信支付
				uni.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: (payRes) => {
						const params = {
							order_id: orderId,
							from: 1,
						}
						request(apiArr.queryOrder, "POST", params).then(res => {
							this.verifyCode = res.verification_code
							this.slJin = res.shiliu_money
							this.boxshadow1 = true
						})
					},
					fail: (payErr) => {
						uni.showToast({
							title: payErr.errMsg == 'requestPayment:fail cancel' ? '已取消支付' : '支付失败',
							icon: 'none'
						})
						const params = {
							order_ids: orderId,
						}
						request(apiArr.cancelPay, "POST", params).then(res => {
						})
					},
					complete: () => {
						// 支付完成后的回调，无论成功失败都会执行
					}
				})
			} else {
				console.error("获取支付参数失败，缺少必要参数")
				uni.showToast({
					title: '获取支付信息失败',
					icon: 'none'
				})
			}
		},
		// 获取评论
		getComment(id) {
			let params = {}
			if (id) {
				params = {
					commodity_id: this.id,
					goods_id: id
				}
			} else {
				params = {
					commodity_id: this.id,
				}
			}
			request(apiArr.getComment, "POST", params).then((res) => {
				this.comments = res.commodity_evaluate_list.map(item => ({
					...item,
					review_image: item.review_image ? item.review_image.split(',') : []
				}));
			});
		},
		// 获取优惠券列表
		getCouponList() {
			const params = {
				goods_id: this.id,
			}
			request(apiArr2.redPackageCenter, "POST", params).then(res => {
				this.coupons = res.rows
				this.couponDetails = res.rows
			})
		},
		// 领取红包
		handleCouponClick(item) {
			if (item.is_received) {
				return
			}
			const params = {
				user_id: uni.getStorageSync('userId'),
				red_package_config_id: item.id,
				mch_id: item.belong_role == 1 ? item.merchant_id : ''
			}
			request(apiArr2.redPackageClaim, 'POST', params).then(res => {
				this.getCouponList()
			})
		}
	}, onLoad(options) {
		const itemObj = JSON.parse(decodeURIComponent(options.item));
		const meun = menuButtonInfo();
		this.top = meun.top;
		this.localHeight = meun.height;

		this.id = itemObj.commodity_id ? itemObj.commodity_id : itemObj.id;
		this.selectedGoods = itemObj; // 保存传入的完整商品信息
	},
	onReachBottom() { },
	onShow() {
		this.getShopCarList().then(() => {
			this.getGoodsInfo();
			// this.getShopCar();
			this.getComment();
			this.getCouponList();
		});
	},

	//离开页面的时候直接更新购物车数量(目前接口是 传入商品id 数量。如果有当前商品就更新数量。如果没有就增加商品。如果删除某个商品 count 为0 就删除)
	onHide() {
		let goods_id_and_count = [];
		this.info.commodity_goods_info_list.forEach((item) => {
			if (item.cart_count) {
				goods_id_and_count.push({
					goods_id: item.id,
					count: item.cart_count.count,
				});
			}
		});

		request(apiArr.updateCar, "POST", {
			goods_id_and_count,
		}).then((res) => {
			console.log("Cart updated on hide");
		});
		return;
	},
};
</script>

<style>
@import url("./index.css");
</style>