<template>
	<view class="container bg-drak" :class="{ 'margin-bottom-big': !empty }">
		<!-- <view class="top-bg">
			<view class="top-kuang">
				<view class="top-title">购物车</view>
			</view>
		</view> -->
		<!-- 00. 未授权登录 -->
		<!-- <use-empty v-if="!islogin" e-style="round" e-type="unauthorized" tip="当前未授权" btn-tip="去登录" height="70vh"
			:auto="false" @goto="tologin">11</use-empty> -->
		<!-- 00. 空白页 -->
		<use-empty v-if="empty" :auto="true" e-style="round" e-type="cart" tip="购物车数据为空" height="70vh"></use-empty>
		<!-- 00. 列表 -->
		<view v-else>
			<!-- 01. 购物车列表1 -->
			<view class="cart-list padding-sm">
				<block v-for="(item, index) in cartDatas" :key="index">
					<view class="cart-item bg-main margin-bottom-sm padding-lg pos-r dflex-s border-radius">
						<view class="image-wrapper pos-r" @click="togoods(item)">
							<!-- 商品图片 -->
							<image class="border-radius-xs wh-full" mode="aspectFill" :lazy-load="true"
								:src="item.goodsMasterImg">
							</image>
							<!-- 选中|未选中按钮 -->
							<view v-if="item.limitNum > 0 && item.limitNum >= item.goodsCount"
								class="iconfont checkbox pos-a bg-main border-radius-big"
								:class="{active: item.check, iconxuanzhongzhuangtai: item.check, iconweixuanzhongzhuangtai: !item.check}"
								@tap.stop="check('item', index)"></view>

							<view v-if="(item.limitNum < item.goodsCount)"
								class="disabled dflex-c dflex-flow-c pos-a pos-tl-c border-radius-c">
								<text>库存不足</text><text class="margin-left-xs fs-xs" v-if="item.limitNum > 0">剩余
									{{item.limitNum}}</text>
							</view>
						</view>
						<view class="item-right padding-left pos-r">
							<!-- 商品名称 -->
							<view class="clamp-2 title" @click="togoods(item)">{{item.goodsName}}
							</view>
							<view class="ft-dark fs-xs padding-top-xs">{{ item.goodAttr || '&nbsp;&nbsp;' }}</view>
							<view class="padding-tb-sm">
								<text class="price">{{ item.goodsActualPrice }}</text>
								<text class="m-price"
									v-if="item.marketPrice > 0">{{ item.marketPrice}}</text>
							</view>

							<!-- + - 购物车数量 -->
							<use-number-box :min="1" :max="item.limitNum || 1" :value="item.goodsCount"
								:is-max="item.goodsCount >= item.limitNum" :is-min="item.goodsCount === 1"
								:index="index" :disabled="item.goodsCount >= item.limitNum"
								@eventChange="numberChange">
							</use-number-box>
						</view>

						<!-- 删除 -->
						<view class="del-btn iconfont iconlajitong-01 pos-a border-radius-c dflex-c ft-dark fs-xl"
							@tap.stop="deleteCart(item.key)"></view>
					</view>
				</block>
			</view>

			<!-- 02. 底部操作栏 -->
			<view class="action-section dflex w-full bg-main pos-f padding-right">
				<view class="checkbox pos-r h-full dflex-c">
					<view class="padding-lr iconfont"
						:class="{active:allChecked,iconxuanzhongzhuangtai: allChecked, iconweixuanzhongzhuangtai: !allChecked}"
						@click="check('all')"></view>
					<view class="clear-btn pos-a tac ft-white" :class="{ show: allChecked }" @click="clearCart">清空
					</view>
				</view>
				<view class="total-box flex1 tar padding-right-lg">
					<text class="price">{{total || 0}}</text>
				</view>
				<button type="primary" class="payment no-border border-radius-lg fs" @click="createOrder()">去结算</button>
			</view>
		</view>

		<!-- 03. 猜你喜欢 -->
		<use-hot-goods :datas="goodsHotDatas" title-type="round" title="热门推荐"></use-hot-goods>
		<view style="width: 100%;height: 100px;"></view>
		<!-- <tabbar :current-page="2"></tabbar> -->
	</view>
</template>

<script>
	import {
		goodscart,
		cartcheck,
		cartcheckpiliang,
		changecart,
		deletecart,
		clearcart
	} from '../../utils/api_cart.js'
	import {
		goodslistlimit
	} from '../../utils/api_home.js'
	// import tabbar from '../tabbar.vue'
	import useHotGoods from '../../components/use-hot-goods/use-hot-goods.vue'
	import useNumberBox from '../../components/use-number-box/use-number-box.vue'
	import useEmpty from '../../components/use-empty/use-empty.vue'
	export default {
		components:{
			useNumberBox,
			useHotGoods,
			useEmpty,
			// tabbar
		},
		data() {
			return {
				// 空白页
				empty: false,//false
				// 购物车数据
				cartDatas: [
					// {goods:{name:'111'}}
				],
				// countType:'',//商品类型数量
				// 全选状态
				allChecked: false,
				// 总价格
				total: 0,
				// 热门推荐
				goodsHotDatas: [],
			};
		},
		watch: {
			//显示空白页
			cartDatas(e) {
				console.log(e,'e')
				let empty = e.length === 0;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			}
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {
			this.loadData();
			this.get_good_hot()
			var j=0
			for(var i=0;i<this.cartDatas.length;i++){
				if(this.cartDatas[index].check){
					j++
				}
			}
			if(j==this.cartDatas.length){
				this.allChecked=true
			}else{
				this.allChecked=false
			}
			
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.loadData(() => {
				uni.stopPullDownRefresh();
			});
		},

		methods: {
			//请求数据
			loadData(callback) {
				var _self = this;
				_self.cartDatas=[]
				var header={
					"Mall-Token": uni.getStorageSync('tokenId')
				}
				goodscart(header).then((res) => {
					if (res.success) {
						if(res.data.items==null){
						}else {
							let _cartDatas = [];
							res.data.items.forEach(data => {
								_self.cartDatas.push(data)
							})
							//计算总价
							_self.calcTotal();
							if (typeof callback === 'function') {
								// 数据加载完成回调函数
								callback();
							}
						}
					}
				})
				// // 更改为临时表方式查询
				// const goodsTemp = db.collection('usemall-goods').getTemp();
				// const goodsSkuTemp = db.collection('usemall-goods-sku').getTemp();
				
				// db.collection(_cart, goodsTemp, goodsSkuTemp)
				// 	.where('create_uid == $env.uid')
				// 	.field(
				// 		'_id, goodsCount, goods_sku.spec, goods.price, goods.market_price, limitNum, goods.name,goods.name_pw ,last_modify_time, goods._id as goods_id, goods.img, goods.state'
				// 	)
				// 	.orderBy('last_modify_time desc')
				// 	.get()
				// 	.then(res => {
				// 		if (res && res.result && res.result.errCode === 0) {
				// 			let _cartDatas = [];
				// 			res.result.data.forEach(x => {
				// 				x.goods = x.goods[0];
				// 				x.goods_id = x.goods_id[0];
				// 				x.goods_sku = x.goods_sku[0] || {};
								
				// 				if (x.goods && x.goods_id) _cartDatas.push(x);
				// 			});
				// 			// 购物车数据
				// 			this.cartDatas = _cartDatas;
				// 			console.log('购',this.cartDatas)
				// 			// 计算总价
				// 			this.calcTotal();

				// 			if (typeof callback === 'function') {
				// 				// 数据加载完成回调函数
				// 				callback();
				// 			}
				// 		}
				// 	})
				// return;
			},
			// 热门推荐
			get_good_hot(){
				let _self = this;
				_self.goodsHotDatas=[]
				var data='?hot=1'
				goodslistlimit(data).then((res) => {
					if (res.success) {
						var total=res.data.totalCount
						data='?hot=1&pageSize='+total
						goodslistlimit(data).then((res) => {
							if (res.success) {
								res.data.list.forEach(data => {
									_self.goodsHotDatas.push(data)
								})
							}else{
								_self.$message.warning('没有符合条件的数据！')
							}
						})
					}
				})
			},
			// 跳转登录页
			tologin() {
				this.$api.tologin();
			},
			// 跳转商品页
			togoods(item) {
				this.$api.togoods({
					id: item.goodsId
				});
			},

			// 选中状态处理
			check(type, index) {
				var _self=this
				if (type === 'item') {
					_self.cartDatas[index].check = !_self.cartDatas[index].check;
					if(_self.cartDatas[index].check){
						var check=1
					}else{
						var check=0
					}
					var j=0
					for(var i=0;i<_self.cartDatas.length;i++){
						if(_self.cartDatas[index].check){
							j++
						}
					}
					if(j==_self.cartDatas.length){
						_self.allChecked=true
					}else{
						_self.allChecked=false
					}
					//购物车选中或取消
					var header={
						"Mall-Token": uni.getStorageSync('tokenId')
					}
					console.log(_self.cartDatas[index].key,'check')
					var params=_self.cartDatas[index].key
					var data=check
					cartcheck(params,data,header).then((res) => {
						if (res.success) {
							_self.calcTotal();
						}
					})
				} else {
					const check = !_self.allChecked
					var keys=[]
					var k2=''
					_self.cartDatas.forEach(item => {
						item.check = check;
						_self.allChecked = check;
						keys.push(item.key)
					})
					_self.allChecked = check;
					if(_self.allChecked){
						var check2=1
					}else{
						var check2=0
					}
					k2=keys.toString()
					//购物车批量选中或取消
					var params='?check='+check2+'&keys='+k2
					var header={
						"Mall-Token": uni.getStorageSync('tokenId')
					}
					cartcheckpiliang(params,header).then((res) => {
						if (res.success) {
							_self.calcTotal();
						}
					})
				}

				_self.calcTotal();
			},
			// +- 数量
			numberChange(data) {
				var _self=this
				let cart = _self.cartDatas[data.index];
				var num=data.number-(_self.cartDatas[data.index].goodsCount)
				changecart
				//修改购物车接口
				var params='?num='+num+'&goodId='+cart.goodsId
				var header={
					"Mall-Token": uni.getStorageSync('tokenId')
				}
				changecart(params,header).then((res) => {
					if (res.success) {
						_self.loadData();
					}
					_self.$api.msg(res.msg);
				})

				// this.$db[_cart].update(cart._id, {
				// 	countType: data.number
				// }).then(res => {
				// 	if (res.code === 200) {
				// 		cart.countType = data.number;
				// 		this.calcTotal();
				// 		return;
				// 	}
				// 	this.$api.msg(res.msg);
				// });
			},
			// 删除
			deleteCart(id) {
				let _self = this
				uni.showModal({
					title: '提示',
					content: '删除购物车',
					success: function(res) {
						if (res.confirm) {
								var params=id
								var header={
									"Mall-Token": uni.getStorageSync('tokenId')
								}
								deletecart(params,header).then((res) => {
									if (res.success) {
										_self.loadData();
									}
									_self.$api.msg(res.msg);
								})
							// _self.$db[_cart].where('create_uid == $env.uid').remove(id)
							// 	.then(res => {
							// 		if (res.code === 200) {
							// 			_self.loadData();
							// 		}
							// 	})
						} else if (res.cancel) {
						}
					}
				});
			},
			// 清空
			clearCart() {
				let _self = this;
				uni.showModal({
					title: '提示',
					content: '清空购物车',
					success: function(res) {
						if (res.confirm) {
							var header={
								"Mall-Token": uni.getStorageSync('tokenId')
							}
							clearcart(header).then((res) => {
								if (res.success) {
									_self.loadData();
								}
								_self.$api.msg(res.msg);
							})
							// _self.$db[_cart].where('create_uid == $env.uid').remove()
							// 	.then(res => {
							// 		if (res.code === 200) {
							// 			_self.cartDatas = [];
							// 			return;
							// 		}
							// 		_self.$api.msg(res.msg)
							// 	})
						} else if (res.cancel) {
						}
					}
				});
			},
			// 计算总价
			calcTotal() {
				if (this.cartDatas.length === 0) {
					this.empty = true;
					return;
				}

				let total = 0,
					check = true;

				this.cartDatas.forEach(item => {
					if (item.check) {
						// 存在库存
						if (item.limitNum > 0 && item.limitNum >= item.goodsCount) {
							total += (item.goodsActualPrice) * item.goodsCount;
						}
					} else if (check) {
						check = false;
					}
				})

				this.allChecked = check;
				this.total = Number(total.toFixed(2));
			},
			// 创建订单
			createOrder() {
				let cart_ids = [];
				let skuId=[]
				this.cartDatas.forEach(item => {
					// 选中有库存购物车
					if (item.check && item.limitNum > 0 && item.limitNum > item.goodsCount) {
						cart_ids.push(item.goodsId)
						skuId.push(item.skuId)
					}
				})
				if (cart_ids.length <= 0) {
					this.$api.msg('请选择结算商品')
					return;
				}
				uni.navigateTo({
					url: `/packageShang/pages/order/create?cart_ids=${cart_ids.join(',')}&type=2&skuId=${skuId.join(',')}`
				})
			},
		},
	}
</script>

<style lang='scss'>
	@import url('/packageShang/components/iconfont/iconfont.css');
	@import url('/packageShang/common/common.scss');
	page {
		min-height: 100%;
	}
	/* 顶部背景 */
	.top-bg{
		width: 100%;
		height: 196rpx;
		background: rgba(255, 255, 255, 1);
		
		.top-kuang{
			width: 100%;
			height: 176rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 2rpx 0px rgba(236, 236, 236, 1);
			.top-title{
				padding: 106rpx 0 0 0rpx;
				text-align: center;
				font-size: 36rpx;
				font-weight: 500;
				line-height: 52rpx;
				color: rgba(0, 0, 0, 1);
			}
		}
	}

	/* 购物车列表项 */
	.cart-item {

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

		.image-wrapper {
			width: 230rpx;
			height: 230rpx;
			flex-shrink: 0;

			image {
				opacity: 1;
			}
		}

		.checkbox {
			top: -16rpx;
			left: -16rpx;
			color: $font-color-disabled;
			line-height: 1;
			font-size: 46rpx;
			padding: 5rpx;
			z-index: 8;
		}

		.disabled {
			color: #fff !important;
			width: 70%;
			height: 70%;
			background-color: rgba(51, 51, 51, 0.5);
		}

		.item-right {
			width: 140px;
			height: 260rpx;
			overflow: hidden;
		}

		.del-btn {
			bottom: 40rpx;
			right: 30rpx;
			width: 70rpx;
			height: 70rpx;
		}
	}

	/* 底部栏 */
	.action-section {
		z-index: 999;
		bottom: 0px;
		height: 100rpx;

		.checkbox {
			.iconfont {
				font-size: 46rpx;
				color: #2C405A;
			}
		}

		.clear-btn {
			left: 100rpx;
			background: #2C405A;
			border-radius: 0 50rpx 50rpx 0;
			padding: 12rpx 0;
			transition: all .2s;

			width: 0;
			opacity: 0;

			&.show {
				width: 120rpx;
				opacity: 1;
			}
		}

		.payment {
			padding: 0 40rpx;
			font-size: $font-base;
			background: $uni-color-primary;
		}
	}

	/* #ifdef H5 || MP-360 */
	.action-section {
		margin-bottom: 50px;
	}

	/* #endif */
</style>
