<template>
	<view class="content">
		<!-- 商品列表 -->
		<view class="goods-list">
			<view class="item" v-for="(item,index) in carts" :key="index">
				<view class="choose" @click.stop="checkChange(item,index)">
					<image src="https://hdtobs.obs.cn-north-4.myhuaweicloud.com/fs/20250729/1753758788583.png" v-show="item.checked"></image>
					<image src="https://hdtobs.obs.cn-north-4.myhuaweicloud.com/fs/20250729/1753758821601.png" v-show="!item.checked"></image>
				</view>
				<image class="goods-img" :src="item.imgUrl" mode="aspectFit" @click="showProduct(item)"></image>
				<view class="info-box" @click="showProduct(item)">
					<view>
						<view class="title-box">
							<view class="title ellipsis">{{ item.goodsName }}</view>
						</view>
					</view>
					<view class="price-num">
						<view class="price">
							<text class="text" >{{item.newIntegral}}</text>
							<text class="unit">积分</text>
							<text class="unit">+</text>
							<text class="text" >{{item.newCash.toFixed(2)}}</text>
							<text class="unit">元</text>
						</view>
						<view class="num-box" @click.stop>
							<u-number-box v-model="item.cartNum" buttonSize="48rpx" integer :step="1" :min="1" :max="100000" @change="changeCartNum($event,item)"></u-number-box>
						</view>
					</view>
				</view>
			</view>
		</view>
	 
		<view v-if="carts.length == 0" class="no-data-box">
			<image src="https://hdtobs.obs.cn-north-4.myhuaweicloud.com/hdtappimgs/cf4a86b913a04341bb44e34bb4d37aa2.png" mode="aspectFit"></image>
			<view class="empty-title">购物车为空</view>
			<view class="empty-cart-btn x-f" @click="goPage">去逛逛</view>
		</view>
		<!-- 猜你喜欢 -->
		 
		<!-- <view class="like-product">
			<likeProduct  ref="product" />
		</view> -->
		<!-- 底部按钮 -->
		<view class="btn-foot">
			<view class="left">
				<view class="choose" @click="handleCheckAll()">
					<image src="https://hdtobs.obs.cn-north-4.myhuaweicloud.com/fs/20250729/1753758788583.png" v-show="checkAll"></image>
					<image src="https://hdtobs.obs.cn-north-4.myhuaweicloud.com/fs/20250729/1753758821601.png" v-show="!checkAll"></image>
				</view>
				<text class="text">全选</text>
				<text class="text" @click="delCart()">删除</text>
			</view>
			<view class="right">
				<view>
					<view class="total">
						<text class="label">合计：</text>
						<view class="price">
							<text class="unit">¥</text>
							<text class="num">{{totalMoney.toFixed(2)}}</text>
						</view>
					</view>
					<view class="total">
						<text class="label">所需积分：</text>
						<view class="price">
							<text class="num">{{totalIntegral}}</text>
						</view>
					</view>
				</view>
				<view class="btn" @click="submit">结算</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import { getCarts,addOrUpdateCart,delCart } from '@/api/integral.js'
	// import likeProduct from '@/components/likeProduct.vue'
	export default {
		// components: {
		// 	likeProduct
		// },	
		data() {
			return {
				totalMoney:0.00,
				totalIntegral: 0,
				carts:[],
				checkAll:false,
			}	
		},
		onLoad() {
 // this.getCarts();
		},
		onShow() {
		this.getCarts();	
		},
		onReachBottom() {
			// this.$refs.product.getGoodsProducts();
		},
		methods: {
			delCart(){
				var selectCarts=this.carts.filter(ele => ele.checked==true).map(ele => {
				  return ele.id
				});
				if(selectCarts.length==0){
					uni.showToast({
						icon:'none',
						title: "请选择商品删除",
					});
					return;
				}
				let data = {ids:selectCarts};
				delCart(selectCarts).then(
					res => {
						if(res.code==200){
							uni.showToast({
								icon:'success',
								title: "操作成功",
							});
							this.getCarts()
						}else{
							
							uni.showToast({
								icon:'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},
			computedMoney(){
				let totalIntegral = 0;
				let totalMoney = 0;	
				let arry = this.carts.filter(item=>item.checked)
				arry.forEach(item => {
				  totalIntegral += item.newIntegral * item.cartNum;
				  totalMoney += item.newCash * item.cartNum;
				});
				this.totalIntegral = totalIntegral;
				this.totalMoney = totalMoney;
			},
			handleCheckAll(){
				this.checkAll=!this.checkAll;
				var that=this;
				this.carts.forEach((item,index,arr)=>{
				     item.checked=that.checkAll;
				})
				this.computedMoney();
			},
			checkChange(item,index){
				item.checked=!item.checked;
				this.checkAll =  this.carts.length > 0 &&this.carts.every(item=>item.checked)
				this.computedMoney();
			},
			changeNum(e,item) {
				item.cartNum = e.detail.value.replace(/\D/g, '')
				if (item.cartNum <= 1) {
				  uni.showToast({
				    title: "已经是底线啦!",
				    icon: "none",
				    duration: 2000
				  });
				  return;
				}
				if(item.cartNum < 1) {
					item.cartNum = 1
				}
				if(item.cartNum>=item.stock){
					item.cartNum=item.stock;
				}
				this.changeCartNum(item)
			},
			getCarts(){
				getCarts().then(
					res => {
						if(res.code==200){
							 this.carts=res.carts;
							 this.carts.forEach((item,index,arr)=>{
							      item.checked=false;
							 })
							 this.checkAll =  this.carts.length > 0 &&this.carts.every(item=>item.checked)
							 this.computedMoney();
						}else{
							uni.showToast({
								icon:'none',
								title: "请求失败",
							});
						}
					},
					rej => {}
				);
			},
			changeCartNum(e, item) {
			  // 保存原始数量和索引
			  const originalNum = item.cartNum;
			  const itemIndex = this.carts.findIndex(cart => cart.id === item.id);
			  
			  // 先更新本地UI（立即响应）
			  item.cartNum = e.value;
			  
			  let data = { cartNum: e.value, goodsId: item.goodsId, isCart: 1 };
			  addOrUpdateCart(data).then(
			    res => {
			      if (res.code == 200) {
			        this.computedMoney();
			      } else {
			        // 库存不足等错误情况
			        // 恢复原始数量
			        this.carts[itemIndex].cartNum = originalNum;
			        
			        // 如果需要，可以更新库存信息
			        if (res.data && res.data.stock) {
			          this.carts[itemIndex].stock = res.data.stock;
			        }
			        
			        // 强制刷新
			        this.$forceUpdate();
			        
			        // 计算总额
			        this.computedMoney();
			        
			        uni.showToast({
			          icon: 'none',
			          title: res.msg,
			          duration: 2000
			        });
			      }
			    },
			    rej => {
			      // 网络错误
			      this.carts[itemIndex].cartNum = originalNum;
			      this.$forceUpdate();
			      this.computedMoney();
			      
			      uni.showToast({
			        icon: 'none',
			        title: '网络错误，请重试',
			        duration: 2000
			      });
			    }
			  );
			},
			// 结算
			submit() {
				var selectCarts=this.carts.filter(ele => ele.checked==true).map(ele => {
				  return ele.id
				});
				if(selectCarts.length==0){
					uni.showToast({
						icon:'none',
						title: "请选择商品",
					});
					return;
				}
				uni.navigateTo({
					url: '/pages_user/user/confirmIntegralOrder?type=cart&cartIds='+selectCarts.toString()
				})
			},
			showProduct(item){
				console.log("这个item")
				uni.navigateTo({
					url: '/pages_user/user/integralGoodsDetails?goodsId='+item.goodsId
				})
			},
			goPage() {
				uni.navigateTo({
					url: '/pages_user/integralGoodsList'
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}
	.content{
		height: 100%;
		padding: 20upx;
		.goods-list{
			.item{
				box-sizing: border-box;
				background: #FFFFFF;
				border-radius: 16upx;
				margin-bottom: 20upx;
				padding: 30upx;
				display: flex;
				align-items: center;
				&:last-child{
					margin-bottom: 0;
				}
				.goods-img{
					width: 160upx;
					height: 160upx;
					background: #FFFFFF;
					margin-right: 30upx;
					flex-shrink: 0;
				}
				.info-box{
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					width: calc(100% - 255upx);
					.title-box{
						width: 100%;
						display: flex;
						align-items: center;
						.title{
							flex: 1;
							font-size: 28upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #111111;
							line-height: 1;
						}
					}
					.price-num{
						margin-top: 24rpx;
						.price{
							margin-bottom: 24rpx;
							display: flex;
							align-items: flex-end;
							.unit{
								font-size: 24upx;
								font-family: PingFang SC;
								font-weight: 500;
								color: #2BC7B9;
								line-height: 1.2;
								margin-right: 4upx;
							}
							.text{
								font-size: 32upx;
								font-family: PingFang SC;
								font-weight: bold;
								color: #2BC7B9;
								line-height: 1;
							}
						}
						.num-box{
							display: flex;
							align-items: center;
							justify-content: flex-end;
							.img-box{
								width: 60upx;
								height: 60upx;
								// border-radius: 4upx;
								border: 1px solid #dddddd;
								display: flex;
								align-items: center;
								justify-content: center;
								image{
									width: 25rpx;
									height: 25rpx;
								}
							}
							input{
								width: 60upx;
								height: 60upx;
								line-height: 60upx;
								font-size: 28upx;
								font-family: PingFang SC;
								font-weight: 500;
								color: #111111;
								// border-radius: 4upx;
								border-top: 1px solid #dddddd;
								border-bottom: 1px solid #dddddd;
								text-align: center;
								// margin: 0 16upx;
							}
						}
					}
				}
			}
		}
		.like-product{
			padding-bottom: 120upx;
		}
		.btn-foot{
			box-sizing: border-box;
			width: 100%;
			height: 121upx;
			background: #FFFFFF;
			padding: 16upx 30upx 16upx 30upx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 99;
			.left{
				display: flex;
				align-items: center;
				.text{
					margin-left: 14upx;
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #666666;
					line-height: 1;
				}
			}
			.right{
				display: flex;
				align-items: center;
				.total{
					display: flex;
					align-items: flex-end;
					margin-right: 36upx;
					.label{
						font-size: 26upx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #999999;
						line-height: 1.5;
					}
					.price{
						display: flex;
						align-items: flex-end;
						.unit{
							font-size: 24upx;
							font-family: PingFang SC;
							font-weight: bold;
							color: #2BC7B9;
							line-height: 1.2;
							margin-right: 10upx;
						}
						.num{
							font-size: 32rpx;
							font-family: PingFang SC;
							font-weight: bold;
							color: #2BC7B9;
							line-height: 1;
						}
					}
				}
				.btn{
					width: 200upx;
					height: 88upx;
					line-height: 88upx;
					text-align: center;
					font-size: 30upx;
					font-family: PingFang SC;
					font-weight: bold;
					color: #FFFFFF;
					background: #2BC7B9;
					border-radius: 44upx;
				}
			}
		}
	}
	.choose {
		margin-right: 20rpx;
		image{
			width: 36rpx;
			height: 36rpx;
			flex-shrink: 0;
		}
	}
	.empty-cart-btn {
		border: 1rpx solid #2BC7B9;
		color: #2BC7B9;
		padding: 10rpx 30rpx;
		border-radius: 40rpx;
		margin-bottom: 20vh;
		margin-top: 50rpx;
		display: inline-block;
	}
</style>
