<template>
	<view>
		<z-nav-bar backState="2000" title="购物车"></z-nav-bar>
		<view class="shopCarContent">
			<scroll-view scroll-y="true">
				<view class="cartItem" v-for="(item,index) in cartList" :key="index">
					<view class="select">
						<checkbox :checked="item.checked" @click="checkboxGroupChange(index,item)"
							class="round checkedItem" />
					</view>
					<view class="cartContent">
						<image :src="item.image" mode="" @click="goDetail(item.productId)"></image>
						<view class="itemCenter">
							<view class="cartTitle" @click="goDetail(item.productId)">
								<text>{{item.productName}}</text>
							</view>
							<view class="itemPrice">
								<text v-if="item.activityPrice && item.activityPrice > 0">￥{{item.activityPrice*item.productAmount}}</text>
								<text v-else>￥{{item.price*item.productAmount}}</text>
								<u-number-box v-model="item.productAmount" @change="valChange($event,item)" :input-width="50"
									:input-height="20" :min="1" :max="item.productStock" integer @overlimit='overlimit'></u-number-box>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 底部操作区 -->
		<view class="shopCarFooter">
			<view class="selectAll">
				<checkbox :checked="all" @click="isSelectAll()" class="round checkedItem" />
				<text class="cartCho">全选</text>
				<text class="cartDel" v-if="isCartDelShow" @click="delCart()">删除</text>
			</view>
			<view class="exhibition">
				<text class="total">合计: <b>￥{{totalPrice}}</b></text>
				<view class="settlement" @click="setTment()">
					结算
				</view>
			</view>
		</view>

		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>

		<z-navigation></z-navigation>
		<music-play :playData="playData"></music-play>
	</view>
</template>

<script>
	import musicPlay from '@/components/music.vue'
	import $http from '@/config/requestConfig.js';
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				playData:{},
				totalPrice: 0, // 总价
				all: false, // 是否全选
				isCartDelShow: false, // 是否展示删除按钮
				cartList: [] // 购物车列表
			};
		},
		//第一次加载
		onLoad(e) {
			// 隐藏原生的tabbar
			uni.hideTabBar();
			this.getCartList()
		},
		//页面显示
		onShow() {
			// 隐藏原生的tabbar
			uni.hideTabBar();
			this.getCartList();
			this.all = false;
			this.isCartDelShow = false
			this.totalPrice = 0
		},
		computed: {
			...mapState(['userInfo']),
		},
		components:{
			musicPlay		
		},
		//方法
		methods: {
			// 获取购物车列表
			getCartList() {
				this.$http.post(`book/ordercart/getCartList?userId=${this.userInfo.id}`).then(res => {
					this.cartList = res.cartList
					if (res.cartList.length > 0) {
						res.cartList.forEach((item, index) => {
							item.checked = false
						})
						this.cartList = res.cartList
					}
				})
			},
			// 是否全选
			isSelectAll(e) {
				if (this.cartList.length > 0) {
					this.all = !this.all
					this.cartList.forEach((item, index) => {
						item.checked = this.all
					})
					this.isCartDelShow = this.all
					this.total()
				} else {
					this.all = false
				}
			},
			// 选中单独商品
			checkboxGroupChange(index, item) {
				// 修改当前item的checked
				this.cartList[index].checked = !item.checked
				// 判断是否全选
				this.all = this.cartList.every((item, index) => {
					return item.checked == true
				})
				// 判断是否展示删除按钮
				this.isCartDelShow = this.cartList.some((item, index) => {
					return item.checked == true
				})
				// 计算总价
				this.total()
			},
			// 计算总价
			total() {
				let allprice = 0;
				this.cartList.forEach((item, index) => {
					let price = 0;
					if (item.checked) {
						if(item.activityPrice && item.activityPrice > 0){
							price = item.productAmount * item.activityPrice;
						}else{
							price = item.productAmount * item.price;
						}
					}
					allprice += price
				})
				this.totalPrice = allprice
			},	
			// 超出阈值时
			overlimit(){
				uni.showToast({
					title:'超出商品数量',
					icon: 'error',
					duration: 1000
				})
			},
			valChange(e, item) {
				console.log(e)
				let productItem = {}				
				productItem = item				
				productItem.productAmount = e.value
					this.updateCart(productItem)
					setTimeout(() => {
						this.total()
					}, 300)				
			},
			// 更新购物车
			updateCart(shagnpin){				
				// 已在购物车中添加
				$http.request({
					url: "book/ordercart/update",
					method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
					data: shagnpin,
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					}
				}).then(res => {
					if (res.code == 0) {
						// uni.showToast({
						// 	title: '加入购物车成功',
						// 	duration: 1000,
						// });
					}
				})
			},
			// 删除购物车
			delCart() {
				let cartIdArr = [];
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						cartIdArr.push(item.cartId)
					}
				})
				uni.showModal({
					title: '提示',
					content: '是否删除这个商品',
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '加载中',
								mask: true
							})
							console.log(cartIdArr)
							$http.request({
								url: "book/ordercart/delete",
								method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
								data: cartIdArr,
								header: { //默认 无 说明：请求头
									'Content-Type': 'application/json'
								},
							}).then(res => {
								this.getCartList()
								uni.hideLoading()
							})
						} else {
							console.log('cancel') //点击取消之后执行的代码
						}
					}
				})
			},

			// 跳转结算页面
			setTment() {
				let shangList=[]
				this.cartList.forEach((item, index) => {
					if (item.checked) {
						shangList.push(index)
					}
				})
				// 如果没有勾选
				if(shangList.length == 0){
					uni.showToast({
						title: "请先勾选商品",
						icon: 'error',
						duration: 1000,
					})
				}else{
				uni.navigateTo({
					url: '../bookShop/settlement?type=1&list='+JSON.stringify(shangList)
				});
				}
			},
			
			
			// 商品内容跳转
			goDetail(id) {
				uni.navigateTo({
					url: '../bookShop/commodityDetail?id=' + id
				});
			},
		},

	};
</script>
<style lang="scss" scoped>
	@import '@/style/mixin.scss';

	.shopCarContent {
		width: 100%;
		height: 100%;
		padding-top: 20rpx;

		.cartItem {
			padding: 10rpx 10rpx 10rpx 20rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			background-color: #fff;

			.cartContent {

				flex: 1;
				display: flex;

				image {
					width: 150rpx;
					height: 180rpx;
					border-radius: 10rpx;
					padding: 10rpx;
					margin-right: 15rpx;
				}

				.itemCenter {
					flex: 1;
					flex-direction: column;
					justify-content: space-around;
				}

				.cartTitle {
					font-size: 30rpx;
					margin: 35rpx 0 20rpx 0;
				}

				.itemPrice {
					font-size: 28rpx;
					display: flex;
					justify-content: space-between;
				}
			}
		}
	}

	.shopCarFooter {
		width: 100%;
		height: 100rpx;
		padding: 20rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		bottom: 110rpx;

		.selectAll {

			display: flex;


			.cartCho {
				margin-top: 12rpx;
				font-size: 25rpx;
				color: #888;
			}

			.cartDel {
				font-weight: bold;
				color: #bf0c0c;
				font-size: 14px;
				margin: 12rpx 0 0 20rpx;
			}
		}

		.exhibition {
			display: flex;
			align-items: center;

			.total {
				font-size: 15px;
				padding: 0 40rpx 0 0;
				color: #888;

				b {
					margin-left: 10rpx;
					color: #e97512;
					font-size: 35rpx;
				}
			}

			.settlement {
				font-size: 15px;
				font-weight: 700;
				padding: 10rpx 50rpx;
				background-image: linear-gradient(90deg, #eba00b 0%, #c96713 100%);
				color: #fff;
				border-radius: 40rpx;
			}
		}
	}
</style>
