<template>
	<view class="d-content">
		<!-- 01. 轮播区 -->
		<view class="swiper-area w-full">
			<swiper class="h-full pos-r" indicator-dots circular="true" duration="400">
				<swiper-item v-for="(item, index) in goods.imgList" :key="index">
					<view class="wh-full">
						<image :src="item.url" class="wh-full loaded" lazy-load="true" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="d-content">
			<!-- 02. 商品数据区 -->
			<view class="goods-area bg-main padding">
				<view class="price-box dflex-b">
					<view>
						<text class="price fwb fs-big">{{ goods.minPrice || '' }} ~ {{ goods.maxPrice || ''}}</text>
					</view>
					<!-- <view class="dflex fs-sm ft-dark">
						<view class="margin-right-sm dflex" @click="">
							<uni-icons type="headphones" size="24" color="#999"></uni-icons>
						</view>
						<view class="margin-right-sm dflex">
							<uni-icons type="heart" size="24" color="#999"></uni-icons>
						</view>
						<view class="margin-right-sm dflex" @click="">
							<uni-icons type="redo" size="24" color="#999"></uni-icons>
						</view>
					</view> -->
				</view>
				<view class="container">
					<u-tag type="error" icon="coupon"></u-tag>
					<u-tag text="平台活动" type="error" plain plainFill></u-tag>
				</view>
				<!-- <view class="coupon">
					<view class="mj-tag">
						<view class="mj-icon padding-lr-xs">
							<u-icon name="rmb-circle" color="#FFF"></u-icon>
						</view>
						<text class="padding-lr-xs">优惠满减</text>
					</view>
					<text class="coupon-name">满30减20</text>
				</view> -->
				<view class="title fs">{{goods.spuName}}</view>
				<view class="sale">月销量：236</view>
			</view>

			<!-- 06. 详情区 -->
			<view class="gap"></view>
			<view class="spec-cell">
				<u-cell title="已选" isLink clickable @click="clickSpec" :border="false">
					<text slot="value" class="u-slot-value">{{specValue}}</text>
				</u-cell>
			</view>
			<!-- <view class="gap"></view>
			<view class="spec-cell">
				<u-cell title="发货" isLink clickable :border="false">
					<text slot="value" class="u-slot-value">预计5天内发货</text>
				</u-cell>
			</view> -->
			<view class="gap"></view>

			<view class="detail-area bg-main">
				<view class="d-header padding dflex-c"><text>图文详情</text>
				</view>

				<rich-text class="pro-detail" :nodes="goods.desc"></rich-text>
				<image mode="aspectFit" :src="goods.imgList[0].url"></image>
			</view>
		</view>
		<my-gap :height="130" bg="#f5f5f5" />
		<!-- 07. 操作区 -->
		<view class="cart-bottom padding-sm dflex-b">
			<view style="width: 60px;">
				<u-icon :name="service" label="客服" labelPos="bottom" size="32" @click="call"></u-icon>
			</view>
			<view style="width: 60px;">
				<uni-badge size="small" :text="buyCount" absolute="rightTop">
					<u-icon :name="shoppingCart" label="购物车" labelPos="bottom" size="32" @click="showCart"></u-icon>
				</uni-badge>
			</view>
			<view class="go-cart dflex-c" @click="toShop">加入购物车</view>
			<view class="go-buy dflex-c background-gradient" @click="toBuy">立即购买</view>
		</view>

		<!-- 置顶 -->
		<use-totop ref="usetop" bottom="120"></use-totop>
		<specPopup ref="specPopup" :cardMsg="cardMsg" @seChanged="seChanged" @addShop="carListMeg"></specPopup>
		<cartPopupVue ref="cartPopup" @selected-changed="handleSelectedChanged" />
	</view>
</template>

<script>
	import specPopup from '@/components/specPopup.vue'
	import cartPopupVue from '../../components/cartPopup.vue'
	import shoppingCart from '../../static/shoppingCart.png'
	import service from '../../static/service.png'
	export default {
		components: {
			specPopup,
			cartPopupVue
		},
		data() {
			return {
				cardMsg: {},
				buyCount: 0,
				total: 0,
				carList: {},
				detailMsg: {},
				shoppingCart: shoppingCart,
				service: service,
				specValue: '',
				// 商品ID
				id: 0,
				// 商品数据
				goods: {},
				// 轮播图
				scrollTop: 0,
				count: 1,
				dataDel: {},
				toList:[]
			}
		},
		onLoad(option) {
			// 解码 URL 编码的字符串
			var dataString = decodeURIComponent(option.data);
			// 尝试将字符串转换为 JSON 对象
			var data = JSON.parse(dataString);
			this.dataDel = data
			// 打印解码后的数据
			console.log('eeeeeeeeeeeee============data', data);
			this.fatchDate()
			const e = uni.getStorageSync('carl')
			this.cList = e
			this.buyCount = data.tobyC
		},
		methods: {
			call() {
				console.log('eeeeeeeeeeeeeeee===============', this.cPhone)
				const e = uni.getStorageSync('info')
				this.cPhone = e
				if (this.cPhone.customerPhone) {
					uni.makePhoneCall({
						phoneNumber: this.cPhone.customerPhone
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: '暂无商家电话'
					})
				}
			},
			handleSelectedChanged(selectedItems) {
				console.log('选中的数据:', selectedItems)
				//this.carList = selectedItems
				this.carListMeg()

			},
			clickSpec() {
				this.cardMsg = this.goods
				this.$nextTick(() => {
					this.$refs.specPopup.open(true);

				});
			},
			showCart() {
				this.$refs.cartPopup.setShow(true)
				this.$refs.cartPopup.openShop(true)
			},
			toShop() {
				const e = uni.getStorageSync('carl')
				const userId = uni.getStorageSync('appUserId')
				const params = {
					storeId: e.id,
					storeName: e.name,
					skuId: this.detailMsg.skuId,
					basePrice: this.detailMsg.retailPrice,
					price: this.detailMsg.retailPrice,
					quantity: this.count,
					extendProps: userId
				}
				console.log('params', params)
				this.$request('post', `/front/shoppingCart`, params, true).then(response => {
					// 请求成功
					console.log('response', response)
					if (response.code = 200) {
						// 弹出消息
						uni.showToast({
							title: '加入购物车成功',
							icon: 'success',
							duration: 2000
						})
						this.carListMeg()
					} else if (response.code = 500) {
						uni.showToast({
							title: response.msg,
							icon: 'warning',
							duration: 2000
						})
					}
				}).catch(error => {
					// 请求失败
					console.error('请求失败:', response.msg);
				})
			},
			async carListMeg() {
				const res = await this.$request('get', `/front/shoppingCart/list`, {
					storeId: this.cList.id
				})
				console.log('res.data==============', res.data)
				if (res) {
					this.carList = res.data
					this.buyCount = this.carList.length
				}
			},
			//获取详情列表
			async fatchDate() {
				const id = this.dataDel.spuId
				const res = await this.$request('get', `/item/spu/queryProduct/${id}`)
				if (res) {
					this.goods = res.data
				}
				console.log('res', res.data)
			},
			//根据skuid获取选择商品信息
			async seChanged(e) {
				console.log('==================3e', e)
				this.specValue = e.item
				this.count = e.count
				const res = await this.$request('get', `/item/sku/${e.id}`)
				this.detailMsg = res.data
				console.log('this.detailMsg', this.detailMsg)
			},
			totalPrice() {
				const e = uni.getStorageSync('carl')
				const userId = uni.getStorageSync('appUserId')
				const toList = {
					storeId: e.id,
					storeName: e.name,
					skuId: this.detailMsg.skuId,
					basePrice: this.detailMsg.retailPrice,
					price: this.detailMsg.retailPrice,
					quantity: this.count,
					extendProps: userId,
					imgUrl: this.detailMsg.img,
					spuId: this.detailMsg.spuId,
					skuName: this.detailMsg.skuName,
					skuProperties: this.detailMsg.skuProperties,
					skuTitle: this.detailMsg.title,
				}
				let total = 0;
				// 如果 selected 属性不存在，直接计算所有商品
				let priceInCents = Math.round(toList.price * 100);
				let quant = toList.quantity;
				total += priceInCents * quant;
				
				this.toList.push(toList)
				// 将总价格转换回浮点数（以元为单位）
				this.total = (total / 100).toFixed(2);
			},
			// 去购买
			toBuy() {
				this.totalPrice()
				const carlist = {
					carlist: this.toList,
					total: this.total
				}
				uni.navigateTo({
					url: `/pages/order/submitOrder/submitOrder?data=${encodeURIComponent(JSON.stringify(carlist))}`
				})
				this.toList = []
				// uni.navigateTo({
				// 	url: `/pages/order/submitOrder/submitOrder`
				// })
			}
		}
	}
</script>

<style scoped lang="scss">
	.d-content {
		background: $page-color-base;
		width: 100%;
	}

	.fixed-top {
		bottom: 230rpx;
	}

	/* 01. 轮播区 */
	.swiper-area {
		height: 500rpx;
		z-index: -1;
		width: 100%;
	}

	/* 02. 商品数据区 */
	.goods-area {
		// margin-top: 720rpx;

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

		.title {
			color: $font-color-dark;
			// height: 46rpx;
			// line-height: 46rpx;
			font-weight: 700;
		}
	}

	/* 06. 详情区 */
	.detail-area {
		.d-header {
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			position: relative;

			text {
				padding: 0 20rpx;
				background: #fff;
				position: relative;
				z-index: 1;
			}

			&:after {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%);
				width: 300rpx;
				height: 0;
				content: '';
				border-bottom: 1px solid #ccc;
			}
		}

		/* 产品详情 */
		.pro-detail {
			width: 100%;
			overflow: hidden;
			-webkit-touch-callout: none;

			img {
				width: 100%;
				max-width: 100%;
				overflow: hidden;
			}
		}
	}


	/* 优惠券区 */
	.coupon-area {
		max-height: 60vh;
		min-height: 30vh;

		.coupon-item {
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}

			.content {
				&:after {
					position: absolute;
					left: 0;
					bottom: 0;
					content: '';
					width: 100%;
					height: 0;
					border-bottom: 1px dashed #f3f3f3;
					transform: scaleY(50%);
				}
			}

			.circle {
				position: absolute;
				bottom: -10rpx;
				z-index: 10;
				width: 20rpx;
				height: 20rpx;
				background: #f5f5f5;
				border-radius: 50%;

				&.r {
					right: -6rpx;
				}

				&.l {
					left: -6rpx;
				}
			}
		}
	}

	.sale {
		color: #999;
		font-size: 12px;
		padding-top: 10upx;
	}

	.spec-cell {
		background: #FFF;
	}

	.u-slot-value {
		font-size: 12px;
	}

	.cart-bottom {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		height: 130rpx;
		box-sizing: border-box;
		background-color: #FFF;
		z-index: 10;
		box-shadow: 0px -4px 16px 0px rgba(0, 0, 0, 0.15);

		.go-cart {
			height: 80%;
			box-sizing: border-box;
			border: solid 1px #FF0000;
			font-size: 14px;
			color: #FF0000;
			border-radius: 50upx;
			margin: 0 10px;
			width: 45%;
		}

		.go-buy {
			height: 80%;
			width: 45%;
			background-color: #FF0000;
			color: #FFF;
			border-radius: 50upx;
			font-size: 14px;
		}
	}

	.container {
		display: flex;
		// justify-content: space-between;
		margin: 10px 0;
		/* 添加一些外边距以便查看 */
	}
</style>