<template>
	<view :class="[AppTheme]" class="all_box">
		<!-- 空白页 -->
		<view v-if="!cartList||cartList.length<=0" class="empty">
			<image :src="settingFile.root_img+'/static/app/emptyCart.jpg'" mode="aspectFit"></image>
			<view class="empty-tips">
				空空如也
				<navigator class="navigator" url="/pages/index/index" open-type="switchTab">随便逛逛>
				</navigator>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="item.id">
					<view class="cart-item" :class="{ 'b-b': index !== cartList.length - 1 }">
						<view class="image-wrapper">
							<image :src="item.pic" :class="[item.loaded]" mode="aspectFill" lazy-load
								@load="onImageLoad('cartList', index)" @error="onImageError('cartList', index)"></image>
							<view class="checkbox">
								<u-icon v-if="item.checked" @click="check('item', index)" size="25" :color="primary"
									name="checkmark-circle-fill"></u-icon>
								<u-icon v-if="!item.checked" @click="check('item', index)" size="25"
									name="checkmark-circle-fill"></u-icon>
							</view>
						</view>
						<view class="item-right">
							<u--text lines="2" lineHeight="20" :text="item.name"></u--text>
							<u--text color="$font-color-light" size="13" lineHeight="20" :text="item.skuattr"></u--text>
							<u--text mode="price" lineHeight="25" color="red" :text="item.price"></u--text>
							<u-number-box class="step" :name="index"
								:value="item.num * 1 > item.total * 1 ? item.total * 1 : item.num * 1" :min="1"
								:max="item.total * 1" @change="numberChange" :longPress="false"></u-number-box>
						</view>
						<text class="del-btn yticon icon-fork" @click="deleteCartItem(index)"></text>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<view v-if="allChecked" class="clear-btn" :class="{show: allChecked }">
						<u-icon top="-1" v-if="allChecked==true" @click="check('all')" size="28" :color="primary"
							name="checkmark-circle-fill"></u-icon>
						<view style="width: 70rpx;" @click="clearCart">清空</view>
					</view>
					<view v-else class="clear-btn2" :class="{ show: !allChecked }">
						<u-icon v-if="allChecked==false" @click="check('all')" size="28" name="checkmark-circle-fill">
						</u-icon>
					</view>
				</view>
				<view class="total-box">
					<text class="price text-neutral">¥{{ total }}</text>
					<text class="coupon">
						暂无优惠
					</text>
				</view>
				<button type="primary" class="no-border confirm-btn  bg-linear-gradient"
					@click="createOrder">去结算</button>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/cart/index.js';
	import mall from '@/api/mall/index.js';
	import tabbar from '@/components/tabbar/tabbar.vue';
	export default {
		components: {
			tabbar
		},
		data() {
			return {
				primary: this.$theme.primary,
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				settingFile: getApp().globalData.siteinfo,
				lasturlencode: '',
			};
		},
		onLoad() {
			this.loadData();
		},

		watch: {
			//显示空白页
			cartList(e) {
				let empty = e.length === 0 ? true : false;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			}
		},
		methods: {
			//请求数据
			loadData() {
				let list = [];
				let data = {
					sid: 0,
					lasturl: this.$store.state.lasturl
				};
				api.basket(data).then(res => {
					console.log(data, "data")
					if (res.status == 200) {
						this.lasturlencode = res.data.lasturlencode
						list = res.data.cache;
						if (res.data == '') {
							this.cartList = [];
							return
						}
						let cartList = list;
						if (list && list.length > 0) {
							cartList = list.map(item => {
								item.checked = true;
								return item;
							});
						}
						this.cartList = cartList;
						console.log(cartList);
						this.calcTotal(); //计算总价
					}
				});
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {

				this[key][index].image = this.settingFile.root_img + '/static/app/errorImage.jpg';
			},
			navToLogin() {
				uni.navigateTo({
					url: '/pages/user/user'
				});
			},
			//选中状态处理
			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, "data")
				this.cartList[data.name].num = data.value;
				this.calcTotal();
			},
			//删除
			deleteCartItem(index) {
				let list = this.cartList;
				let row = list[index];
				let id = row.id;
				console.log(id)
				api.delbasket({
					sid: 0,
					id
				}).then(res => {
					if (res.status == 200) {
						this.$api.msg('删除成功')
						this.cartList.splice(index, 1);
						this.calcTotal();
						uni.hideLoading();
					}
				})
			},
			//清空
			clearCart() {
				if (!this.allChecked) {
					return
				}
				uni.showModal({
					content: '清空购物车？',
					success: e => {
						if (e.confirm) {
							api.clearbasket({
								sid: 0
							}).then(res => {

								if (res.status == 200) {
									this.cartList = [];
									this.$api.msg('购物车已清空');
								} else {
									this.$api.msg(res.msg);
								}
							});
						}
					}
				});
			},
			//计算总价
			calcTotal() {
				let list = this.cartList;
				if (list.length === 0) {
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item => {
					if (item.checked === true) {
						total += item.price * item.num;

					} else if (checked === true) {
						checked = false;
					}
				});
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder() {
				let list = this.cartList;
				let goodsData = new Object();
				let goodslist = new Array();
				list.forEach(item => {
					if (item.checked) {
						/* 购物车列表每个商品的id  &&  对应每个商品的数量    以键值对的形式传递给后台*/
						goodsData["G" + item.id] = item.num;
						goodslist.push(item.goodsid)
					}
				});

				goodsData.sid = 0
				let id = uni.getStorageSync('userInfo').id;
				api.checkbasket(goodsData).then(res => {
					if (res.status == 200) {
						uni.showToast({
							icon: 'loading',
							title: '生成订单',
							duration: 2000
						});
						setTimeout(() => {
							this.$u.route('/pagesD/pages/order/createOrder', {
								id,
								sid: 0,
								goodids: goodslist.join(','),
								lasturl: this.lasturlencode,
							});
						}, 2000);
					} else {
						this.$u.toast(res.msg);
					}
				});
				return

				uni.navigateTo({
					url: `/pagesD/pages/order/createOrder?data=${JSON.stringify({
                    goodsData: goodsData
                })}`
				});
				this.$api.msg('跳转下一页 sendData');
			}
		}
	};
</script>

<style lang="scss">
	/deep/.u-icon__icon .uicon-checkmark-circle-fill
	{
		top:10rpx;
	}
	.all_box {
		.empty {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 100vh;
			padding-bottom: 100upx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			align-items: center;
			background: #fff;

			image {
				width: 240upx;
				height: 160upx;
				margin-bottom: 30upx;
			}

			.empty-tips {
				display: flex;
				font-size: $font-sm + 2upx;
				color: $font-color-disabled;

				.navigator {
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}

	/* 购物车列表项 */
	.cart-list {
		padding: 20rpx;

		.cart-item {
			display: flex;
			position: relative;
			background-color: #fff;
			padding: 15rpx;
			border-radius: 10rpx;

			.image-wrapper {
				width: 230upx;
				height: 230upx;
				flex-shrink: 0;
				position: relative;

				image {
					width: 230upx;
					height: 230upx;
					border-radius: 8upx;
				}

				.checkbox {
					position: absolute;
					left: -16rpx;
					top: -16rpx;
					z-index: 8;
					font-size: 44upx;
					line-height: 1;
					padding: 4upx;
					color: $font-color-disabled;
					background: #fff;
					border-radius: 50px;
				}
			}


			.item-right {
				display: flex;
				flex-direction: column;
				flex: 1;
				overflow: hidden;
				position: relative;
				padding-left: 30upx;

				.title,
				.price {
					font-size: $font-base + 2upx;
					height: 40upx;
					line-height: 40upx;
				}

				.attr {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					height: 50upx;
					line-height: 50upx;
				}

				.price {
					height: 50upx;
					line-height: 50upx;
				}

				.step {
					justify-content: flex-end;
				}
			}

			.del-btn {
				padding: 4upx 10upx;
				font-size: 34upx;
				height: 50upx;
				color: $font-color-light;
			}
		}
	}

	/* 底部栏 */
	.action-section {
		position: fixed;
		// left: 30upx;
		left: 20rpx;
		right: 20rpx;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 660upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255, 255, 255, 0.9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, 0.5);
		border-radius: 16upx;

		.checkbox {
			height: 52upx;
			position: relative;

			.image {
				width: 52upx;
				height: 100%;
				position: relative;
				z-index: 99;
				/* #ifdef H5 */
				margin-top: 0px;
				/* #endif */
				/* #ifdef APP-PLUS || MP-WEIXIN */
				margin-top: -1px;
				/* #endif */
			}
		}

		.clear-btn {
			position: absolute;
			left: 26upx;
			display: flex;
			justify-content: flex-start;
			flex-wrap: wrap;
			flex-direction: column;
			z-index: 4;
			height: 48rpx;
			line-height: 48rpx;
			font-size: $font-base;
			color: #fff;
			background: $font-color-disabled;
			border-radius: 50px;
			opacity: 0;
			transition: 0.2s;

			&.show {
				opacity: 1;
				width: 130upx;
			}
		}

		.clear-btn2 {
			position: absolute;
			left: 26upx;
			display: flex;
			justify-content: flex-start;
			flex-wrap: wrap;
			flex-direction: column;
			top: 0;
			z-index: 4;
			width: 0;
			height: 47rpx;
			line-height: 47rpx;
			font-size: $font-base;
			color: #fff;
			background: #fff;
			border-radius: 50px;
			opacity: 0;
			transition: 0.2s;

			&.show {
				opacity: 1;
				width: 130upx;
			}
		}

		.total-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			text-align: right;
			padding-right: 40upx;

			.price {
				font-size: $font-lg;
			}

			.coupon {
				font-size: $font-sm;
				color: $font-color-light;
				padding-top: 5rpx;

				text {
					color: $font-color-dark;
				}
			}
		}

		.confirm-btn {
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $font-base + 2upx;
		}
	}

	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked {
		color: $tab-color-1;
	}

</style>
