<template>
	<view class="cart-pages">
		<view class="cart-bar" v-if="cartList.length>0">
			<view>共<text class="special-val">{{count}}</text>件商品</view>
			<view @click="editCart">
				<text class="edit" v-if="!isEdit">管理</text>
				<text class="save" v-else>完成</text>
			</view>
		</view>
		<view class="goods-list">
			<!-- 按分类显示 -->
			<view class="goods-class-box" v-for="(item,cindex) in cartList" :key="item.goodsTypeNo">
				<view class="goods-class-head">
					<view @click="goodsClasChange(cindex)">
						<view 
						class="check-button" 
						v-if="isSxGoodAll(item).length||isEdit"
						:class="item.checked?'checked':'uncheck'">
						</view>
						<view v-else class="check-button disabled"></view>
						<view class="goodClsName">
							{{item.name}}
						</view>
					</view>
					<view class="des" v-if="item.goldLimit>0">
						<view>商品满<text>{{item.goldLimit}}</text></view>
						<image mode="scaleToFill" style="width: 26rpx;height: 26rpx;" src="/static/ledou.png"></image>
						<view>才可购买</view>
					</view>
				</view>
				<view class="goods-class-list">
					<!-- 商品列表 -->
					<view class="goods-item" v-for="(good,index) in item.shoppingCartGoodsList" :key="good.id">
						<view class="checkbox" 
						   @click="goodsChange(good,index,cindex)">
							<view
							class="check-button" 
							v-if="isSxGood(good)||isEdit"
							:class="good.checked?'checked':'uncheck'">
							</view>
							<view v-else class="check-button disabled"></view>
						</view>
						<view class="goods-info">
							<view class="goods-imgs">
								<view v-if="good.goods.inventoryQty==0||good.goods.state == 0" class="goods-staus">
									<text v-if="good.goods.state == 0">已下架</text>
									<text v-if="good.goods.state == 1&&good.goods.inventoryQty==0">已售罄</text>
								</view>
								<u-image border-radius="12" width="158rpx" height="140rpx" :src="good.goods.homeImage+'?x-oss-process=image/resize,m_pad,h_140,w_158,color_ffffff'"></u-image>
							</view>
							<view class="goods-text">
								<view class="good-name">{{good.goods.name}}</view>
								<view class="goods-price">
									<view>
										<text>{{good.goods.sellGold}}</text>
										<image mode="scaleToFill" style="width: 30rpx;height: 30rpx;"src="/static/ledou.png"></image>
									</view>
									<view v-if="good.goods.inventoryQty>0&&good.goods.state==1">
										<uni-numbers-box @change="goodsNumsChange()" :index="cindex+'-'+index" :value="good.buyQty" :max="good.goods.inventoryQty" :min="1"></uni-numbers-box>
									</view>
									<view v-else>
										<view style="width: 100rpx;text-align: center;">×{{good.buyQty}}</view>
									</view>
								</view>
								<view class="goods-kucun" v-if="good.goods.state == 1&&good.goods.inventoryQty==0">库存不足</view>
								<view class="goods-kucun" v-else>库存：<text>{{good.goods.inventoryQty}}</text></view>
							</view>
						</view>
					</view>
					<!-- 小计 -->
					<view class="goods-class-heji">
						<view>合计：<text>{{item.total}}</text></view>
						<image mode="scaleToFill" style="width: 30rpx;height: 30rpx;"src="/static/ledou.png"></image>
					</view>
				</view>
			</view>
			<view class="noData" v-if="!loading&&cartList.length==0">
				<u-empty mode="car">
					<view slot="bottom">
						<u-button size="mini" @click="toBuy">去选商品</u-button>
					</view>
				</u-empty>
			</view>
			<view class="loading" v-if="loading">
				<u-loading :show="loading"></u-loading>
				<view>正在加载...</view>
			</view>
		</view>
		<view class="cart-submit" v-if="cartList.length>0">
			<view @click="checkAllChange()">
				<view 
				class="check-button" 
				:class="checkAll?'checked':'uncheck'">
				</view>
				<view class="checkAll">
					{{checkAll?'取消':'全选'}}
				</view>
			</view>
			<view v-if="!isEdit">
				<view class="heji">
					<view>总计：</view>
					<text>{{totalPrice}}</text>
					<u-image mode="scaleToFill" width="35rpx" height="35rpx" src="/static/ledou.png"></u-image>
				</view>
				<u-button size="mini" :custom-style="toOrderButton" type="error" @click="toOrder">立即下单</u-button>
			</view>
			<view v-else>
				<u-button size="mini" :custom-style="toOrderButton" type="error" @click="delGoods">删除</u-button>
			</view>
		</view>
		<!-- 弹框提示 -->
		<u-popup v-model="showMsg" border-radius="15" closeable mode="center" width="500rpx">
			<view style="padding: 40rpx;line-height: 40rpx;font-size: 28rpx;">
				<view style="text-align: center;font-size: 32rpx;margin-bottom: 20rpx;">提示</view>
				<view v-for="item in msgContent" :key="item.id">{{item.message}}</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {
		getCartList,
		deleteGoodsFormCart,
		updateGoodsBuyQty
	} from '@/api/shoppingCart.js'
	export default {
		data() {
			return {
				toOrderButton: {
					borderRadius:'100rpx',
					fontSize:'30rpx',
					width: '200rpx',
					height: '80rpx'
				},
				checkAll: false,// 全选
				isEdit: false, // 是否编辑模式
				cartList: [], // 商品列表
				loading: false,
				showMsg: false,
				msgContent: []
			};
		},
		computed: {
			// 用户信息
			userData(){
				return this.$store.state.vuex_userData
			},
			// 总数
			count() {
				let arr = this.cartList
				let count = 0
				arr.map(item=>{
					count = count + item.shoppingCartGoodsList.length
					if(!item.hasOwnProperty("checked")){
						item.checked = false
					}
					item.shoppingCartGoodsList.map(goods=>{
						if(!goods.hasOwnProperty("checked")){
							goods.checked = false
						}
					})
				})
				return count
			},
			// 总计
			totalPrice(){
				let arr = this.cartList
				let total = 0
				arr.map(item=>{
					let xj = 0
					item.shoppingCartGoodsList.map(a =>{
						if(a.checked){
							total = total + a.buyQty * a.goods.sellGold
							xj = xj + a.buyQty * a.goods.sellGold
						}
					})
					item.total = xj
				})
				return total
			},
		},
		onLoad() {
			// 获取购物车数据
			this.loading = true
			this.getCartList()
		},
		methods: {
			// 计算购物车数量
			getCarCount(){
				let arr = this.$store.state.vuex_cartList || []
				let count = 0
				arr.map(item=>{
					count = count + item.shoppingCartGoodsList.length
				})
				this.$u.vuex('vuex_cartNums', count)
			},
			// 查询购物车
			getCartList(){
				getCartList({}).then(res => {
					if(res.status == 200){
						this.$u.vuex('vuex_cartList', res.data)
						this.cartList = JSON.parse(JSON.stringify(res.data))
						this.getCarCount()
						// 默认全选
						if(!this.isEdit){
							this.checkAllChange()
						}
					}
					this.loading = false
					setTimeout(()=>{
						uni.hideLoading()
					},500)
				})
			},
			// 去选商品
			toBuy(){
				uni.switchTab({
					url:"/pages/goods/index"
				})
			},
			// 获取当前选择的商品, type: 0 删除，1 立即下单
			getCheckGoods(type){
				let arr = this.cartList
				let goods = []
				arr.map(item=>{
					item.shoppingCartGoodsList.map(a =>{
						if(a.checked){
							goods.push(type?a:a.id)
						}
					})
				})
				return goods
			},
			// 设置每个分类下的商品选中状态
			setClsGoodStatus(item,checked){
				item.shoppingCartGoodsList.map(good=>{
					// 已下架，已删除，已销完的不选
					if((good.goods.inventoryQty==0||good.goods.state == 0) && !this.isEdit){
						good.checked = false
					}else{
						good.checked = checked
					}
				})
			},
			// 全选 或 取消全选
			checkAllChange() {
				let arr = this.cartList
				arr.map(item=>{
					item.checked = !this.checkAll
					this.setClsGoodStatus(item,!this.checkAll)
				})
				this.checkAll = !this.checkAll
				arr.splice()
			},
			// 每个分类的全选
			goodsClasChange(index){
				let item = this.cartList[index]
				item.checked = !item.checked
				this.setClsGoodStatus(item,item.checked)
				// 判断是否全选
				this.hasCheckAll()
			},
			// 商品选择
			goodsChange(good,index,cindex){
				let goods = this.cartList[cindex] // 当前分类
				good.checked = !good.checked
				// 判断当前分类是否全选
				this.clasGoodsHasCheckAll(goods)
			},
			// 判断某个商品是否失效
			isSxGood(item){
				return !(item.goods.inventoryQty==0||item.goods.state == 0||item.goods.delFlage == 0) || this.isEdit
			},
			// 判断分类下商品是否都是已失效
			isSxGoodAll(row){
				return row.shoppingCartGoodsList.filter(item => {
					return this.isSxGood(item)
				})
			},
			// 判断某个分类是否全选
			clasGoodsHasCheckAll(row){
				let goods = this.isSxGoodAll(row)
				let len = goods.length
				let clen = 0
				if(len==0){
					return
				}
				goods.map(item=>{
					if(item.checked){
						clen = clen + 1
					}
				})
				row.checked = clen == len
				this.cartList.splice()
				// 判断是否全选
				this.hasCheckAll()
			},
			// 是否全选
			hasCheckAll(){
				let list = this.cartList
				let len = list.length
				let clen = 0
				list.map(item => {
					if(item.checked){
						clen = clen + 1
					}
				})
				this.checkAll = clen == len
				list.splice()
			},
			// 编辑购物车
			editCart(){
				this.isEdit = !this.isEdit
				this.checkAll = true
				this.checkAllChange()
			},
			// 判断当前分类下的商品总和是否满足规则
			hasZgjindu(){
				let result = []
				let list = this.cartList.filter(item=>item.total>0)
				for(let i=0;i<list.length;i++){
					let item = list[i]
					let ret = 0
					item.shoppingCartGoodsList.map(good=>{
						if(good.checked){
							ret = ret + good.goods.sellGold * good.buyQty
						}
					})
					result.push({id:item.goodsTypeNo,val:ret >= item.goldLimit,message:`[${item.name}]的商品合计满${item.goldLimit}乐豆才可购买`})
				}
				
				console.log(result.filter(item=>!item.val))
				return result.filter(item=>!item.val)
			},
			// 立即下单
			toOrder(){
				let goods = this.getCheckGoods(1)
				if(this.userData.currentGold >= this.totalPrice){
					if(goods.length){
						// 判断是否满足规则
						let a = this.hasZgjindu()
						if(a.length==0){
							this.$u.vuex("vuex_toOrderList",goods)
							uni.redirectTo({
								url:"/pages/toOrder/index?orderForm=SHOPPING_CAR"
							})
						}else{
							this.showMsg = true
							this.msgContent = a
						}
					}else{
						uni.showToast({
							title:"请选择商品",
							icon:"none"
						})
					}
				}else{
					uni.showToast({
						title:"你的乐豆余额不足",
						icon:"none"
					})
				}
			},
			// 删除购物车商品
			delGoodFormCart(ids){
				uni.showLoading({
					mask: true,
					title: "正在删除..."
				})
				deleteGoodsFormCart({idList:ids}).then(res => {
					if(res.status == 200){
						// 刷新购物车
						this.getCartList()
					}else{
						uni.hideLoading()
					}
				})
			},
			// 删除商品
			delGoods(){
				let ids = this.getCheckGoods(0)
				if(ids.length){
					this.delGoodFormCart(ids)
				}else{
					uni.showToast({
						title:"请选择要删除的商品",
						icon:"none"
					})
				}
			},
			// 更新商品数量
			updateGoodsBuyQty(item){
				uni.showLoading({
					mask: true,
					title: "更新数量中..."
				})
				updateGoodsBuyQty(item).then(res => {
					uni.hideLoading()
				})
			},
			// 更改商品数量
			goodsNumsChange(val,id){
				console.log(val,id)
				let cindex = id.split('-')[0]
				let index = id.split('-')[1]
				let item = this.cartList[cindex]
				let row = item.shoppingCartGoodsList[index]
				row.buyQty = val
				this.updateGoodsBuyQty({id:row.id,buyQty:row.buyQty})
			}
		},
	}
</script>

<style lang="scss">
page{
	height: 100%;
}
.cart-pages{
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	.noData{
		padding-top: 150upx;
	}
	.loading{
		display: flex;
		justify-content: center;
		padding: 150rpx 0;
	}
	.cart-bar{
		display: flex;
		justify-content: space-between;
		padding:20upx;
		.edit{
			color: #666;
		}
		.save{
			color: #00aaff;
		}
		.special-val{
			color: #FA3534;
			font-weight: bold;
			margin: 0 10rpx;
		}
	}
	.check-button{
		width: 40rpx;
		height: 40rpx;
	}
	.checked{
		background: url('/static/checked.png') no-repeat center center;
		background-size: 100% 100%;
	}
	.uncheck{
		background: url('/static/uncheck.png') no-repeat center center;
		background-size: 100% 100%;
	}
	.disabled{
		border:2rpx solid #EEEEEE;
		border-radius: 100rpx;
		background: #F8F8F8;
	}
	.goods-list{
		flex-grow: 1;
		overflow: auto;
		.goods-class-box{
			background: #FFFFFF;
			box-shadow: 1px 1px 3px #eee;
			margin-bottom: 20upx;
			.goods-class-head{
				display: flex;
				align-items: center;
				padding: 20upx;
				border-bottom: 1px solid #F8F8F8;
				justify-content: space-between;
				> view{
					&:first-child{
						display: flex;
						align-items: center;
					}
					.goodClsName{
						font-size: 30rpx;
						margin-left: 10rpx;
					}
				}
				.des{
					display: flex;
					align-items: center;
					font-size: 26upx;
					color: #999;
					text{
						color: #FA3534;
					}
				}
			}
		}
		
		.goods-item{
			padding: 20upx;
			display: flex;
			align-items: center;
			border-bottom: 1px solid #F8F8F8;
			&:last-child{
				border: 0;
			}
			.checkbox{
				width: 60rpx;
				overflow: hidden;
			}
			.goods-info{
				display: flex;
				align-items: center;
				flex-grow: 1;
				.goods-imgs{
					position: relative;
					border:1px solid #eee;
					border-radius: 10rpx;
					.goods-staus{
						width: 100%;
						height: 100%;
						position: absolute;
						z-index: 10000;
						border-radius: 15rpx;
						background: rgba($color: #000000, $alpha: 0.4);
						text-align: center;
						line-height: 140rpx;
						left: 0;
						top: 0;
						color: #eee;
						font-size: 24upx;
						font-weight: bold;
					}
				}
				.goods-text{
					padding-left: 20upx;
					flex-grow: 1;
					.good-name{
						font-weight: bold;
						word-break: break-all;
					}
				}
			}
			.goods-kucun{
				padding-top: 10rpx;
				font-size: 22rpx;
				text{
					color: #999;
				}
			}
			.goods-price{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-top: 10upx;
				>view{
					&:first-child{
						font-size: 22upx;
						display: flex;
						align-items: center;
						text{
							color: red;
							font-size: 32upx;
							margin-right: 6upx;
							font-weight: bold;
						}
					}
				}
			}
		}
		.goods-class-heji{
			padding: 20upx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			font-size: 24rpx;
			text{
				color: red;
			}
		}
	}
	.cart-submit{
		background: #FFFFFF;
		box-shadow: 1px 1px 3px #eee;
		border-top: 1px solid #eee;
		display: flex;
		align-items: center;
		justify-content: space-between;
		>view{
			display: flex;
			align-items: center;
			.checkAll{
				margin-left: 10rpx;
			}
			&:first-child{
				padding: 10upx 20upx;
			}
			&:last-child{
				padding: 10upx 20upx;
				font-size: 26upx;
				> view{
					padding-right: 30upx;
				}
				.heji{
					display: flex;
					align-items: center;
					font-weight: bold;
					text{
						color: red;
						font-size: 40upx;
					}
				}
			}
		}
	}
}
</style>
