<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!hasLogin" class="empty">
			<image src="/static/error/emptyCart.png" class="emptyImg" mode="aspectFit"></image>
			<view class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登陆></view>
			</view>
		</view>
		<view v-if="hasLogin">
			<!-- 列表 -->
			<view class="coupon flex" @click="Getcoupon" v-if="showCart == true">
				<view class="tip red">优惠券</view>
				<view class="tip">优惠券详情见活动页面</view>
				<view class="tip green flex">
					<view>更多优惠</view>
					<view class="iconfont iconenter"></view>
				</view>
			</view>
			<view class="emptyCart" v-if="showCart == false">
				<view class="empty-img"><image src="/static/error/emptyCart.png"></image></view>
				<view class="empty-text">
					空空如也，
					<text @click="ToCategory">随便逛逛</text>
				</view>
			</view>
			<view class="cart-list">
				<view v-for="(item, index) in cartList" :key="index" class="cart-item" :class="{ 'b-b': index !== cartList.length - 1 }">
					<view class="image-wrapper">
						<image
							:src="item.productInfo.image"
							:class="[item.loaded]"
							mode="aspectFill"
							lazy-load
							@load="onImageLoad('cartList', index)"
							@error="onImageError('cartList', index)"
						></image>
						<view class="iconfont iconroundcheckfill checkbox" :class="{ checked: item.checked }" @click="check('item', index)"></view>
					</view>
					<view class="item-right">
						<view class="flex">
							<text class="clamp title">{{ item.productInfo.store_name }}</text>
							<text class="del-btn iconfont iconclose" @click="deleteCartItem(item, 1)"></text>
						</view>
						<text class="attr">{{ item.attr_val }}</text>
						<view class="flex">
							<view class="price">¥{{ item.productInfo.price }}</view>
							<uni-number-box
								class="step"
								:min="1"
								:max="item.productInfo.stock"
								:value="item.cart_num > item.productInfo.stock ? item.productInfo.stock : item.cart_num"
								:isMax="item.cart_num >= item.productInfo.stock ? true : false"
								:isMin="item.cart_num === 1"
								:index="index"
								:key="item.id"
								:disabled="true"
								@eventChange="numberChange"
							></uni-number-box>
						</view>
					</view>
				</view>
			</view>
			<view class="guess-name" v-if="invalList.length > 0">
				<view class="img"><image src="../../static/image/img13.png"></image></view>
				<view class="name">失效商品</view>
			</view>
			<view class="cart-list">
				<view v-for="(item, ind) in invalList" :key="item.id" class="cart-item" :class="{ 'b-b': ind !== invalList.length - 1 }">
					<view class="image-wrapper"><image :src="item.productInfo.image" mode="aspectFill"></image></view>
					<view class="meng">已失效</view>
					<view class="item-right">
						<view class="flex">
							<text class="clamp title">{{ item.productInfo.store_name }}</text>
							<text class="del-btn iconfont iconclose" @click="deleteCartItem(item, 2)"></text>
						</view>
						<text class="attr">{{ item.attr_val }}</text>
						<view class="flex">
							<view class="price">¥{{ item.productInfo.price }}</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="Guesslist.length > 0">
				<view class="guess-name">
					<view class="img"><image src="../../static/image/img13.png"></image></view>
					<view class="name">猜你喜欢</view>
				</view>
				<view id="list-box" class="list-box" :style="{ height: swiperHeight + 'px' }">
					<view class="guess-section">
						<view v-for="(item, index) in Guesslist" :key="index" class="guess-item" @click="ToDetail(item)">
							<view class="imagewrapper"><image :src="item.image"></image></view>
							<view class="guess-list">
								<text class="title clamp margin-c-20">{{ item.store_name }}</text>
								<view class="info clamp margin-c-20">{{ item.store_info }}</view>
								<view class="tipBox margin-c-20">
									<view class="tipsl" v-if="item.keyword != ''">
										<text v-for="lss in item.keyword">{{ lss }}</text>
									</view>
								</view>
							</view>
							<view class="price margin-c-20 flex">
								<view class="price_list">
									<view class="price-red">
										￥{{ item.price }}
										<text>/份</text>
									</view>
									<view class="price-green">
										￥{{ item.ot_price }}
										<text>市场价</text>
									</view>
								</view>
								<view class="img position-relative" @click.stop="Addcar(item)">
									<image src="/static/img/img21.png"></image>
									<view class="corner" v-if="item.cart_num > 0">
										<text>{{ item.cart_num }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section" v-show="showCart">
				<view class="checkbox">
					<view class="iconfont iconroundcheckfill icon-checked-box" @click="check('all')" :class="{ 'icon-checked': allChecked }"></view>
					<view class="clear-btn" @click="allChecked ? clearCart() : ''" :class="{ show: allChecked }"><text>清空</text></view>
				</view>
				<view class="total-box">
					<text class="price">合计：¥{{ total }}</text>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">结算</button>
			</view>
		</view>
	</view>
</template>
<script>
import { getCartList, getCartNum, cartDel } from '@/api/user.js';
import { getProducts,cartAdd } from '@/api/product.js';
import { mapState } from 'vuex';
import { saveUrl, interceptor } from '@/utils/loginUtils.js';
export default {
	data() {
		return {
			total: 0, //总价格
			allChecked: false, //全选状态  true|false
			showCart: false, //隐藏购物车数据
			empty: false, //空白页现实  true|false
			cartList: [], //购物车商品
			swiperHeight: 0,
			Guesslist: '', //猜你喜欢
			invalList: '' //失效商品
		};
	},
	onShow() {
		// 只有登录时才加载数据
		if (this.hasLogin) {
			this.loadData();
			this.Guess();
		}
	},
	onLoad(option){
		if (option.spread) {
			uni.setStorageSync('spread', option.spread);
		}
		saveUrl();
	},
	watch: {
		//显示空白页
		cartList(e) {
			let empty = e.length === 0 ? true : false;
			if (this.empty !== empty) {
				this.empty = empty;
			}
			if (e.length > 0) {
				this.showCart = true;
			}
			if (e.length == 0) {
				this.showCart = false;
			}
		},
		// 初次加载页面高度时修改页面高度
		Guesslist(newValue, oldValue) {
			let obj = this;
			let bHeight = Math.ceil(newValue.length / 2);
			obj.$nextTick(function() {
				uni.createSelectorQuery()
					.select('#list-box')
					.fields(
						{
							size: true
						},
						function(data) {
							obj.pageProportion = data.width / 750;
							obj.swiperHeight = Math.ceil(obj.pageProportion * 620 * bHeight);
						}
					)
					.exec();
			});
		}
	},
	computed: {
		...mapState('user', ['hasLogin'])
	},
	//下拉刷新
	onPullDownRefresh() {
		let obj = this;
		//监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
		setTimeout(function() {
			obj.loadData();
			uni.stopPullDownRefresh(); //停止下拉刷新动画
		}, 1000);
	},
	methods: {
		//请求数据
		async loadData() {
			let obj = this;
			getCartList({})
				.then(function(e) {
					obj.invalList = e.data.invalid;
					// 获取当前购物车物品增加数量
					let nub = obj.cartList.length;
					// 获取之前对象数组
					let aArray = obj.cartList.reverse();
					// 获取返回数据对象数组
					let bArray = e.data.valid.reverse();
					// 处理数据缓存
					let arr = bArray
						.map((item, ind) => {
							// 设置返回数据默认为勾选状态
							item.checked = true;
							// 获取相同数组之前对象的数据
							let carlist = aArray[ind];
							// 判断之前是否已经加载完毕
							if (carlist && carlist.loaded == 'loaded') {
								item.loaded = 'loaded';
							}
							return item;
						})
						.reverse();

					obj.$set(obj, 'cartList', []);
					obj.$nextTick(e => {
						obj.$set(obj, 'cartList', arr);
						obj.calcTotal(); //计算总价
					});
				})
				.catch(function(e) {
					console.log(e);
				});
		},
		// #ifdef MP
		onShareAppMessage: function(res) {
			let userInfo = uni.getStorageSync('userInfo');
			let GetInfo = uni.getStorageSync('GetInfo');
			// 来自页面内分享按钮
			let pages = getCurrentPages();
			// 获取当前页面
			let page = pages[pages.length - 1];
			let path = '/pages/index/index?';
			// 保存邀请人
			path += 'spread=' + userInfo.uid;
			let data = {
				path: path,
				imageUrl: GetInfo.img,
				title: GetInfo.title
			};
			console.log(data)
			return data;
		},
		// #endif
		// 猜你喜欢
		Guess() {
			let obj = this;
			getProducts({
				page: 1,
				limit: 10,
				type: 1,
				sid: 97 //分类id
			})
				.then(({ data }) => {
					obj.Guesslist = data;
				})
				.catch(err => {
					console.log(err);
				});
		},
		//加入购物车
		Addcar(item) {
			let obj = this;
			cartAdd({
				cartNum: '1', //商品数量
				uniqueId: '', //商品标签
				new: 0, //商品是否新增加到购物车1为不加入0为加入
				mer_id: '',
				productId: item.id //商品编号
			})
				.then(function(e) {
					uni.showToast({
						title: '成功加入购物车',
						type: 'top',
						duration: 500,
						icon: 'none'
					});
					obj.Guess();
					obj.loadData();
				})
				.catch(e => {});
		},
		// 商品详情页
		ToDetail(item) {
			if (item.stock < 1) {
				this.$api.msg('该商品已售罄');
			} else {
				uni.navigateTo({
					url: `/pages/product/product?id=` + item.id
				});
			}
		},
		ToCategory() {
			uni.switchTab({
				url: `/pages/category/category`
			});
		},
		//领取优惠券
		Getcoupon() {
			uni.navigateTo({
				url: '/pages/coupon/getcoupon'
			});
		},
		//监听image加载完成
		onImageLoad(key, index) {
			// 修改载入完成后图片class样式
			this.$set(this[key][index], 'loaded', 'loaded');
		},
		//监听image加载失败
		onImageError(key, index) {
			this[key][index].image = '/static/error/errorImage.jpg';
		},
		// 跳转到登录页
		navToLogin() {
			// 保存地址
			saveUrl();
			// 登录拦截
			interceptor();
		},
		//选中状态处理
		check(type, index) {
			if (type === 'item') {
				this.cartList[index].checked = !this.cartList[index].checked;
			} else {
				const checked = !this.allChecked;
				const list = this.cartList;
				list.forEach(item => {
					item.checked = checked;
				});
				this.allChecked = checked;
			}
			this.calcTotal(type);
		},
		//数量
		numberChange(data) {
			console.log(data);
			let arr = this.cartList[data.index];
			arr.cart_num = data.number;
			getCartNum({ id: arr.id, number: data.number })
				.then(e => {})
				.catch(function(e) {
					console.log(e);
				});
			this.calcTotal();
			this.Guess();
		},
		//删除
		deleteCartItem(index, type) {
			uni.showLoading({
				title: '加载中'
			});
			let id = index.id;
			let obj = this;
			// if(type == 1){
			// 	let list = this.cartList;
			// 	let row = list[index];
			// 	id = row.id;
			// }else{
			// 	let list = this.invalList;
			// 	let row = list[index];
			// 	id = row.id;
			// }
			// if(type == 1){
			// 	this.cartList.splice(index, 1);
			// 	this.calcTotal();
			// }else{
			// 	this.invalList.splice(index, 1);
			// }
			cartDel({
				ids: id
			})
				.then(function(e) {
					uni.hideLoading();
					obj.loadData();
					obj.calcTotal();
					obj.Guess();
				})
				.catch(e => {
					uni.hideLoading();
					console.log(e.message);
				});
		},
		//清空
		clearCart() {
			uni.showModal({
				content: '清空购物车？',
				success: e => {
					if (e.confirm) {
						let st = this.cartList.map(e => {
							return e.id;
						});
						cartDel({
							ids: st.join(',')
						}).then(e => {
							console.log(e);
						});
						this.cartList = [];
						this.Guess();
					}
				}
			});
		},
		//计算总价
		calcTotal() {
			let list = this.cartList;
			console.log(list, 7);
			if (list.length === 0) {
				this.empty = true;
				return;
			}
			let total = 0;
			let checked = true;
			list.forEach(item => {
				if (item.checked === true) {
					total += item.productInfo.price * item.cart_num;
				} else if (checked === true) {
					checked = false;
				}
			});
			this.allChecked = checked;
			this.total = Number(total.toFixed(2));
		},
		//创建订单
		createOrder() {
			let list = this.cartList;
			let goodsData = [];
			list.forEach(item => {
				if (item.checked) {
					goodsData.push(item.id);
				}
			});

			uni.navigateTo({
				url: '/pages/order/createOrder?id=' + goodsData.join(',')
			});
		},
		//随便逛逛
		Toindex() {
			uni.switchTab({
				url: '/pages/category/category'
			});
		}
	}
};
</script>

<style lang="scss">
.container {
	padding-bottom: 134rpx;
	background-color: $page-color-base;
	.emptyCart {
		position: relative;
		width: 100%;
		padding-top: 150rpx;
		.empty-img {
			width: 385rpx;
			height: 300rpx;
			margin: 0rpx auto;
			image {
				width: 100%;
				height: 100%;
			}
		}
		.empty-text {
			text-align: center;
			font-size: $font-sm + 2rpx;
			color: $font-color-disabled;
			margin-bottom: 100rpx;
			text {
				color: $uni-color-primary;
			}
		}
	}
	/* 空白页 */
	.empty {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100vh;
		padding-bottom: 100rpx;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		background: #fff;
		.emptyImg {
			width: 300rpx;
			height: 250rpx;
			margin-bottom: 30rpx;
		}
		.empty-tips {
			display: flex;
			font-size: $font-sm + 2rpx;
			color: $font-color-disabled;
			.navigator {
				color: $uni-color-primary;
				margin-left: 16rpx;
			}
		}
		.empty {
			width: 100%;
			height: 500rpx;
		}
	}
}
/* 购物车列表项 */
.coupon {
	width: 92%;
	margin: 25rpx auto;
	border-radius: 25rpx;
	background: #ffffff;
	font-size: 20rpx !important;
	padding: 25rpx 15rpx;
	.red {
		background-color: #fe1212;
		color: #ffffff;
		line-height: 35rpx;
		padding: 0rpx 20rpx;
		border-radius: 25rpx;
	}
	.green {
		color: #2dbd59;
	}
	.tip.green {
		height: 30rpx;
	}
}
.cart-list {
	background: #ffffff;
	width: 92%;
	margin: 25rpx auto;
	border-radius: 25rpx;
	.cart-item {
		display: flex;
		position: relative;
		padding: 30rpx 40rpx;
		.image-wrapper {
			width: 160rpx;
			height: 160rpx;
			flex-shrink: 0;
			position: relative;
			image {
				border-radius: 8rpx;
			}
		}
		.meng {
			width: 160rpx;
			height: 160rpx;
			position: absolute;
			background-color: rgba(0, 0, 0, 0.6);
			color: #ffffff;
			font-size: 22rpx;
			line-height: 160rpx;
			text-align: center;
		}
		.checkbox {
			position: absolute;
			left: -16rpx;
			top: -16rpx;
			z-index: 8;
			font-size: 44rpx;
			line-height: 1;
			padding: 4rpx;
			color: $font-color-disabled;
			background: #fff;
			border-radius: 50px;
		}
		.item-right {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position: relative;
			padding-left: 30rpx;
			.title {
				font-size: $font-base + 2rpx;
				color: $font-color-dark;
				height: 40rpx;
				line-height: 40rpx;
			}
			.price {
				font-size: $font-base + 2rpx;
				color: #ff1a27;
				font-weight: bold;
				height: 40rpx;
				line-height: 40rpx;
			}
			.attr {
				font-size: $font-sm + 2rpx;
				color: $font-color-light;
				height: 50rpx;
				line-height: 50rpx;
			}
			.price {
				height: 50rpx;
				line-height: 50rpx;
			}
		}
		.del-btn {
			padding: 4rpx 10rpx;
			font-size: 34rpx;
			height: 50rpx;
			color: $font-color-light;
		}
	}
}
.guess-name {
	padding: 25rpx 25rpx;
	font-size: 32rpx;
	text-align: center;
	.img {
		width: 80%;
		margin: 0rpx auto;
		height: 4rpx;
		image {
			width: 100%;
			height: 100%;
		}
	}
}
/* 猜你喜欢 */
.guess-section {
	display: flex;
	flex-wrap: wrap;
	padding: 0 20rpx;
	.guess-item {
		// height: 558rpx;
		position: relative;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		border: 2rpx solid #eeeeee;
		width: 343rpx;
		margin-bottom: 4%;
		border-radius: $border-radius-sm;
		background-color: white;
		padding-bottom: 30rpx;
		&:nth-child(2n + 1) {
			margin-right: 24rpx;
		}
	}
	.imagewrapper {
		width: 100%;
		height: 330rpx;
		border-radius: 3px;
		margin-bottom: 15rpx;
		image {
			width: 100%;
			height: 100%;
			// opacity: 1;
		}
	}
	.guess-list {
		height: 130rpx;
		.title {
			font-size: 28rpx;
			color: $font-color-dark;
		}
		.info {
			color: #999999;
			font-size: 24rpx;
		}
		.tipBox {
			// padding-bottom: 8rpx;
			.tipsl {
				text {
					border: 2rpx solid #ff1a27;
					color: #ff1a27;
					border-radius: 5rpx;
					font-size: 18rpx;
					padding: 2rpx 5rpx;
					margin-right: 15rpx;
				}
			}
		}
	}
	.price {
		font-size: 28rpx;
		width: 303rpx;
		// padding-top: 25rpx;
		position: relative;
		.price_list {
			.price-red {
				font-weight: bold;
				font-size: 32rpx !important;
				color: #ff1a27;
				text {
					color: #9699a0;
					font-size: 24rpx !important;
					font-weight: normal;
					padding: 0rpx 10rpx;
				}
			}
			.price-green {
				color: #2dbd59;
				font-size: 24rpx !important;
				text {
					background: #2dbd59;
					color: #ffffff;
					padding: 0rpx 8 rpx;
					border-radius: 7rpx;
					font-size: 20rpx !important;
					margin-left: 8rpx;
				}
			}
		}
		.img {
			position: absolute;
			bottom: 0;
			right: 0;
			width: 50rpx;
			height: 50rpx;
			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	.icon {
		@extend %icon;
	}

	.detail {
		line-height: 1;
	}
	.tip {
		color: white;
		background-color: $color-yellow;
		line-height: 1.5;
		font-size: $font-sm;
		padding-left: 20rpx;
	}
}
/*公用边框样式*/
%icon {
	margin-right: 10rpx;
	display: inline-block;
	padding: 2rpx 10rpx;
	border: 1rpx solid $color-yellow;
	color: $color-yellow;
	line-height: 1;
	font-size: $font-base;
	border-radius: 10rpx;
}
/* 底部栏 */
.action-section {
	/* #ifdef H5 */
	margin-bottom: 100rpx;
	/* #endif */
	position: fixed;
	// left: 30rpx;
	bottom: 0rpx;
	z-index: 95;
	display: flex;
	align-items: center;
	width: 100%;
	height: 120rpx;
	padding: 0 30rpx;
	background: #ffffff;
	// box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.5);
	.checkbox {
		height: 52rpx;
		position: relative;
		.icon-checked-box {
			border-radius: 50rpx;
			background-color: #ffffff;
			width: 52rpx;
			height: 100%;
			position: relative;
			z-index: 5;
			font-size: 53rpx;
			line-height: 1;
			color: $font-color-light;
		}
		.icon-checked {
			color: $base-color;
		}
	}
	.clear-btn {
		position: absolute;
		left: 26rpx;
		top: 0;
		z-index: 4;
		width: 0;
		height: 52rpx;
		line-height: 52rpx;
		padding-left: 38rpx;
		font-size: $font-base;
		color: #fff;
		background: $font-color-disabled;
		border-radius: 0 50px 50px 0;
		opacity: 0;
		transition: 0.2s;
		&.show {
			opacity: 1;
			width: 120rpx;
		}
	}
	.total-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		text-align: right;
		padding-right: 40rpx;
		.price {
			font-size: $font-lg;
			color: #ff383e;
		}
		.coupon {
			font-size: $font-sm;
			color: $font-color-light;
			text {
				color: $font-color-dark;
			}
		}
	}
	.confirm-btn {
		padding: 0 45rpx;
		margin: 0;
		border-radius: 100px;
		height: 70rpx;
		line-height: 70rpx;
		font-size: $font-base + 2rpx;
		background: #ff1a27;
	}
}
/* 复选框选中状态 */
.action-section .checkbox.checked,
.cart-item .checkbox.checked {
	color: $base-color;
}
</style>
