<template>
	<view :class="['qn-page-' + theme]">
		<view class="container">
			<Aempty text="您购物车暂无商品，快去加购吧～" src="https://onlineimg.qianniao.vip/car.png" v-if="!isLogin || (invalidData.length === 0 && goodsData.length === 0)"></Aempty>
			<view v-else>
				<!-- 列表 goodsData -->
				<view class="card" v-for="(item, index) in goodsData" :key="index">
					<view class="box clearfix">
						<text
							@click="checkShop(item.checkedShop, item.shopId, 2, item)"
							class="ibonfont"
							:class="[item.checkedShop ? 'ibonxuanze_xuanzhong primary-color' : 'ibonxuanze']"
						></text>
						<text class="title">{{ item.shopName }}</text>
					</view>
					<view class="cart-list">
						<u-swipe-action
							class="uniSwipe"
							:options="options"
							v-for="(goods, goodsindex) in item.shopGoodsData"
							:key="goodsindex"
							:show="goods.isShow"
							:index="goodsindex"
							@open="openItem(index, goodsindex)"
							@click="deleteCartItem([goods.cartId], goods)"
						>
							<view class="cart-item clearfix">
								<!-- 是否选中 -->
								<text
									@click="checkShop(goods.selection === 5, goods.cartId, 1, goods, item)"
									class="ibonfont float_left"
									:class="[goods.selection === 5 ? 'ibonxuanze_xuanzhong primary-color' : 'ibonxuanze']"
								></text>
								<view class="image-wrapper float_left" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)">
									<!-- 图片 -->
									<image :src="goods.goodsImages" mode="aspectFill" />
								</view>
								<!-- 标题 -->
								<view class="item-right float_left">
									<text class="title" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)">{{ goods.goodsName }}</text>
									<view class="attr" @click="goPage(`/pagesT/product/product?id=${goods.goodsId}`)">
										<block v-if="goods.specGroup && goods.specGroup.length">
											<text>规格：</text>
											<text v-for="(sku, skui) in goods.specGroup" :key="skui" style="padding-right: 4upx;">{{ sku.specValueName }};</text>
										</block>
									</view>
									<view class="BotStyle clearfix">
										<view class="price float_left primary-color">
											<text class="icon-rmb">¥</text>
											<view style="display: inline-block;"><rich-text :nodes="$_utils.splitPrice(goods.price)"></rich-text></view>
											<text style="font-size: 20rpx;">/{{ goods.unitName }}</text>
										</view>
										<view v-if="goods.isActivity === 5" class="activity-tag float_left primary-bg">活动价</view>
										<view class="float_right clearfix number-box">
											<block v-if="goods.isDistribution === 5">
												<!-- 开启预售不验证最大值 -->
												<u-number-box
													:bg-color="primaryColor"
													color="#fff"
													:value="goods.buyNum"
													:input-height="44"
													:min="goods.setNum"
													@blur="numberChange($event, goods)"
													@plus="clacAdd($event, goods)"
													@minus="clacSusubtract($event, goods)"
												></u-number-box>
											</block>
											<block v-else>
												<!-- 未开启预售最大值为库存数 -->
												<u-number-box
													:bg-color="primaryColor"
													color="#fff"
													:value="goods.buyNum"
													:input-height="44"
													:max="Number(goods.inventoryNum)"
													:min="goods.setNum"
													@blur="numberChange($event, goods)"
													@plus="clacAdd($event, goods)"
													@minus="clacSusubtract($event, goods)"
												></u-number-box>
											</block>
										</view>
									</view>
								</view>
							</view>
						</u-swipe-action>
					</view>
				</view>
				<view class="card invalid-card" v-if="invalidData.length">
					<view class="clearfix invalid-view">
						<text class="float_left invalid-tit">失效商品（{{ invalidData.length }}）</text>
						<text class="float_right invalid-btn primary-color" @click="clearInvalid">清空失效商品</text>
					</view>
					<view class="cart-list" v-for="(goods, goodsindex) in invalidData" :key="goodsindex">
						<view class="cart-item clearfix">
							<!-- 是否选中 -->
							<view class="image-wrapper float_left">
								<view class="invalid-tag"><text>已失效</text></view>
								<!-- 图片 -->
								<image :src="goods.goodsImages" mode="aspectFill" />
							</view>
							<!-- 标题 -->
							<view class="item-right float_left">
								<view class="title ellipsis">{{ goods.goodsName }}</view>
								<view class="invalid-msg">{{ goods.invalidMsg }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 优惠券面板 -->
		</view>
		<!-- 底部菜单栏 -->
		<view class="action-section" v-if="isLogin" :style="{ bottom: isBang ? '170rpx' : '100rpx' }">
			<view class="action-section-main">
				<view class="checkbox clearfix">
					<text @click="checkShop(allChecked, '', 3)" class="ibonfont float_left" :class="[allChecked ? 'ibonxuanze_xuanzhong primary-color' : 'ibonxuanze']"></text>
					<view class="all-btn float_right" :class="{ show: allChecked }">
						<text @click="checkShop(allChecked, '', 3)">全选</text>
						<!-- #ifdef MP -->
						<text style="margin-left: 24upx;" @click="is_edit = !is_edit">{{ is_edit ? '完成' : '编辑' }}</text>
						<!-- #endif -->
					</view>
				</view>
				<view class="total-box" v-if="!is_edit">
					<view>
						<text class="total-text">合计：</text>
						<text class="price primary-color">¥{{ $_utils.formatNub(goodsDataAll.payMoney) || 0 }}</text>
					</view>
					<!-- 说明 -->
					<view class="freeExpressPrice" v-if="!goodsDataAll.totalMoney && startDeliveryPrice" @click="goPage('/pages/classification/cate', 'switchTab')">
						<text>满{{ startDeliveryPrice }}元起送，先去逛逛</text>
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
					<view
						class="freeExpressPrice"
						v-else-if="startDeliveryPrice && goodsDataAll.totalMoney < startDeliveryPrice"
						@click="goPage('/pages/classification/cate', 'switchTab')"
					>
						<text>还差{{ $NP.minus(startDeliveryPrice, goodsDataAll.totalMoney) }}元起送，再去逛逛</text>
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>

					<view class="freeExpressPrice" v-else-if="freeExpressPrice > 0" @click="goPage('/pages/classification/cate', 'switchTab')">
						还差{{ freeExpressPrice.toFixed(2) }}元免运费，去凑单
						<u-icon name="arrow-right" size="20"></u-icon>
					</view>
					<!--  v-else-if="goodsDataAll.preferential > 0"  -->
					<view class="freeExpressPrice" v-else @click="goPage('/pages/classification/cate', 'switchTab')">
						总额：¥{{ goodsDataAll.totalMoney || 0 }} 活动优惠：-¥{{ goodsDataAll.preferential || 0 }}
					</view>
				</view>
				<view v-if="!is_edit" @click="createOrder" class="confirm-btn primary-bg">
					<text v-if="!goodsDataAll.totalMoney">随便逛逛</text>
					<text v-else-if="goodsDataAll.totalMoney < startDeliveryPrice">去凑单</text>
					<text v-else>去结算</text>
					<!--  ({{ goodsDataAll.checkNum || 0 }}) -->
				</view>
				<text v-if="is_edit" class="del-goods-btn" @click="delSelect">删除</text>
			</view>
		</view>
		<!-- 底部tabbar -->
		<Tabbar v-model="tab_current"></Tabbar>
	</view>
</template>
<script>
import Login from '@/components/Login.vue';
export default {
	components: {
		Login
	},
	data() {
		return {
			tab_current: 2,
			is_edit: false,
			totalMoney: 0, //总价格
			buyNum: 1, //更新购物数字
			checkedShop: false, //商铺选择
			allChecked: false, //全选状态  true|false
			empty: false, //空白页现实  true|false
			goodsData: [], //店铺列表
			invalidData: [], //失效商品
			shopGoodsData: [], //商品列表
			options: [
				{
					text: '删除',
					style: {
						backgroundColor: 'rgb(255,58,49)'
					}
				}
			],
			goodsDataAll: {
				activityMoney: '0.00',
				cartNum: 0,
				checkNum: 0,
				expressMoney: 0,
				goodsData: [],
				goodsNum: 0,
				invalidData: [],
				payMoney: '0.00',
				preferential: '0.00',
				totalMoney: '0.00',
				vipDiscount: 0,
				vipDoubleDiscount: 0
			}
		};
	},
	// #ifdef APP-PLUS || H5
	onNavigationBarButtonTap(obj) {
		var currentWebview = this.$mp.page.$getAppWebview();
		var tn = currentWebview.getStyle().titleNView;
		// 修改buttons
		// index: 按钮索引, style {WebviewTitleNViewButtonStyles }
		if (!this.is_edit) {
			this.is_edit = true;
			tn.buttons[0].text = '完成'; //[0] 按钮的下标
			currentWebview.setStyle({
				titleNView: tn
			});
		} else if (this.is_edit) {
			// console.log(132312);
			this.is_edit = false;
			tn.buttons[0].text = '编辑'; //[0] 按钮的下标
			currentWebview.setStyle({
				titleNView: tn
			});
		}
	},
	// #endif

	watch: {
		'$store.state.locationObj'(val) {
			if (JSON.stringify(val) === '{}') {
				this.getAuthorizeInfo();
				return;
			}
			if (this.isLogin) {
				this.getCartByUserCenterId();
			}
		},
		isLogin(val) {
			if (val) {
				this.getCartByUserCenterId();
			}
		}
	},
	computed: {
		// 判断市场常见的几种刘海屏机型 true为刘海机型
		isBang() {
			return this.$_utils.modelmes();
		},
		isLogin() {
			return this.$store.state.hasLogin;
		},
		startDeliveryPrice() {
			return this.$store.state.baseSet.startDeliveryPrice || 0;
		},
		freeExpressPrice() {
			const freeExpressPrice = this.$store.state.baseSet.freeExpressPrice || 0;
			return this.$NP.minus(freeExpressPrice, this.goodsDataAll.totalMoney);
		}
	},
	onLoad() {
		if (JSON.stringify(this.$store.state.locationObj) === '{}') {
			this.getAuthorizeInfo();
		}
		// #ifdef MP-WEIXIN
		// 小程序的原生菜单中显示分享按钮
		uni.showShareMenu({
			withShareTicket: false,
			menus: ['shareAppMessage', 'shareTimeline']
		});
		// #endif
	},

	onShow() {
		if (this.$store.state.hasLogin) {
			this.getCartByUserCenterId();
		}
	},
	onPullDownRefresh() {
		if (this.isLogin) {
			this.getCartByUserCenterId();
		} else {
			uni.stopPullDownRefresh();
		}
	},
	methods: {
		// 点击添加clacAdd
		clacAdd(e, goods) {
			if (goods.selection === 5) {
				this.goodsDataAll.totalMoney = this.$NP.plus(Number(this.goodsDataAll.totalMoney), Number(goods.price));
			}

			this.updateBuyNum(goods.cartId, e.value);
		},
		// 点击减少数量
		clacSusubtract(e, goods) {
			// if (goods.buyNum === 1) {
			// 	this.$api.msg('商品数量不可以再减少了哦');
			// 	return;
			// }
			if (goods.selection === 5) {
				this.goodsDataAll.totalMoney = this.$NP.minus(Number(this.goodsDataAll.totalMoney), Number(goods.price));
			}

			this.updateBuyNum(goods.cartId, e.value);
		},
		// 手动输入
		numberChange(e, goods) {
			if (e.value <= 0) {
				this.$api.msg('请输入正确的数量');
				return;
			}
			this.updateBuyNum(goods.cartId, e.value);
		},
		// 更新购物车数量 updateBuyNum
		updateBuyNum(id, buyNum) {
			this.$u.api
				.updateBuyNum(id, {
					buyNum: buyNum
				})
				.then(res => {
					this.getCartByUserCenterId();
				})
				.catch(() => {
					this.getCartByUserCenterId();
				});
		},
		//请求数据 获取商品列表
		getCartByUserCenterId() {
			this.$u.api.getCartByUserCenterId().then(({ data }) => {
				uni.stopPullDownRefresh();
				if (Array.isArray(data)) {
					this.goodsDataAll = {
						activityMoney: '0.00',
						cartNum: 0,
						checkNum: 0,
						expressMoney: 0,
						goodsData: [],
						goodsNum: 0,
						invalidData: [],
						payMoney: '0.00',
						preferential: '0.00',
						totalMoney: '0.00',
						vipDiscount: 0,
						vipDoubleDiscount: 0
					};
					this.goodsData = [];
					this.invalidData = [];
					this.$store.commit('commit_cartNum', 0);
					this.$store.commit('commit_cartPrice', 0);
					return;
				}
				this.goodsDataAll = data;
				this.invalidData = data.invalidData || [];
				if (data.goodsData && data.goodsData.length) {
					data.goodsData.forEach(item => {
						item.checkedShop = item.shopGoodsData.every(itemG => itemG.selection === 5);
						item.shopGoodsData.forEach(goods => {
							goods.isShow = false;
						});
					});
					this.goodsData = data.goodsData;
					this.allChecked = this.goodsData.every(item => item.checkedShop);
				} else {
					this.goodsData = [];
				}
				this.$store.commit('commit_cartNum', data.goodsNum);
				this.$store.commit('commit_cartPrice', data.totalMoney);
			});
		},
		//  打开swipeAction
		openItem(i, gi) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			let target = this.$u.deepClone(this.goodsData);
			target[i].shopGoodsData[gi].isShow = true;
			this.goodsData = target;
		},
		// 选中切换
		// type 1 单商品；2 店铺切换；3 全选切换
		async checkShop(checked, id, type, row, PRow) {
			const selection = checked ? 4 : 5;
			const params = {
				selection: selection,
				type: type
			};
			if (type === 1) {
				params.cartId = id;
				// 前端手动把选择标示进行切换，优化操作体验
				row.selection = selection;
				PRow.checkedShop = PRow.shopGoodsData.every(itemG => itemG.selection === 5);
				this.allChecked = this.goodsData.every(item => item.checkedShop);
			} else if (type === 2) {
				params.shopId = id;
				// 前端手动把选择标示进行切换，优化操作体验
				row.checkedShop = !checked;
				row.shopGoodsData.forEach(item => {
					item.selection = selection;
				});
				this.allChecked = this.goodsData.every(item => item.checkedShop);
			} else {
				// 前端手动把选择标示进行切换，优化操作体验
				this.allChecked = !checked;
				this.goodsData.forEach(item => {
					item.checkedShop = !checked;
					item.shopGoodsData.forEach(goods => {
						goods.selection = selection;
					});
				});
			}
			this.$u.api
				.updateSelection({
					...params
				})
				.then(res => {
					this.getCartByUserCenterId();
				});
		},
		// 移出商品
		delSelect() {
			let chooseGoods = [];
			this.goodsData.forEach(item => {
				item.shopGoodsData.forEach(itemC => {
					if (itemC.selection === 5) {
						chooseGoods.push(itemC.cartId);
					}
				});
			});
			this.deleteCartItem(chooseGoods);
		},
		// 清空失效
		clearInvalid() {
			let chooseGoods = this.invalidData.map(item => {
				return item.cartId;
			});
			this.deleteCartItem(chooseGoods);
		},
		// deleteCartItem 删除
		deleteCartItem(cartId, row, index, gIndex) {
			if (cartId.length === 0) {
				this.$api.msg('请选择要删除的商品');
				return;
			}
			uni.showModal({
				title: '提示',
				content: '你确定将此产品移除购物车',
				success: res => {
					if (res.confirm) {
						this.$u.api
							.delCart({
								cartId: cartId
							})
							.then(res => {
								this.getCartByUserCenterId();
							});
					}
				}
			});
		},
		//创建订单
		createOrder() {
			// if (this.$store.state.baseSet.personnelReview === 5) {
			// 验证账户状态
			this.userAudit();
			if (!this.isUserAudit) {
				return;
			}
			// }
			if (!this.goodsDataAll.totalMoney) {
				this.goPage('/pages/classification/cate', 'switchTab');
				return;
			}
			if (this.startDeliveryPrice && this.goodsDataAll.totalMoney < this.startDeliveryPrice) {
				// this.$api.msg('请选择要结算的商品');
				this.goPage('/pages/classification/cate', 'switchTab');
				return;
			}
			if (!this.goodsDataAll.checkNum) {
				this.$api.msg('请选择要结算的商品');
				return;
			}
			let isSub = true;
			for (let i in this.goodsData) {
				let item = this.goodsData[i];
				for (let g in item.shopGoodsData) {
					let goods = item.shopGoodsData[g];
					if (goods.selection === 5 && goods.isInvalid === 4) {
						isSub = false;
						break;
					}
				}
			}
			if (!isSub) {
				this.$api.msg('抱歉，您要结算的商品中包含失效商品，请取消后再次进行提交');
				return;
			}
			uni.navigateTo({
				url: `/pagesT/order/createOrder`
			});
		}
	},
	onShareAppMessage(options) {
		return {
			title: this.$store.state.baseSet.shop,
			path: '/pages/index/index?businessmanId=' + (this.$store.state.userStatus.id||''),
			success: res => {
				console.log(res);
			}
		};
	},
	// #ifdef MP-WEIXIN
	// 分享到朋友圈
	onShareTimeline(obj) {},
	// 收藏小程序
	onAddToFavorites() {}
	// #endif
};
</script>

<style lang="scss">
.box {
	border-bottom: 1px solid #eeeeee;
	.title {
		font-size: 28upx;
		font-weight: 510;
		padding-left: 24upx;
		line-height: 94rpx;
		color: #3c3c3c;
	}
	.ibonfont {
		display: inline-block;
		color: #cccccc;
		font-size: 36rpx;
	}
}
.container {
	padding-bottom: 100upx;
}

/* 购物车列表项 */
.card {
	background: #ffffff;
	padding: 0 48upx 32rpx;
	margin-bottom: 20rpx;
}
.total-view {
	text-align: right;
	font-size: 32upx;
	color: #999;
	padding: 24upx 0;

	.price {
		color: $price-color;
		font-size: 30upx;
		font-weight: 510;
	}
}

.uniSwipe:last-child {
	.cart-item {
		border-bottom: 0 none;
	}
}
.cart-item {
	padding-top: 24upx;
	.ibonfont {
		transform: translateY(60upx);
		color: #cccccc;
		font-size: 36rpx;
		display: inline-block;
		width: 34rpx;
		height: 34rpx;
		margin-right: 16upx;
	}
	.image-wrapper {
		width: 152upx;
		height: 152upx;

		background-color: #eef3f4;
		border-radius: 12upx;
		image {
			width: 100%;
			height: 100%;
			border-radius: 12upx;
		}
	}
	.item-right {
		margin-left: 16upx;
		width: 430rpx;
		position: relative;
		.del-btn {
			padding: 4upx 10upx;
			font-size: 30upx;
			height: 50upx;
			color: $font-color-light;
			position: absolute;
			top: 0;
			right: 20upx;
		}
		.title {
			color: #3c3c3c;
			font-size: 28upx;
			height: 40upx;
			line-height: 40upx;
			text-overflow: -o-ellipsis-lastline;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 1;
			line-clamp: 2;
			-webkit-box-orient: vertical;
			font-weight: 510;
		}
		.attr {
			font-size: 24upx;
			font-weight: 400;
			color: #9b9b9b;
			height: 32rpx;
			margin: 8rpx 0;
			line-height: 32rpx;
		}
		.price {
			color: $price-color;
			font-size: 40upx;
			font-weight: 510;
			font-family: DIN-Medium;
		}
		.activity-tag {
			width: 76rpx;
			font-size: 20rpx;
			color: #ffffff;
			height: 32rpx;
			line-height: 32rpx;
			text-align: center;
			border-radius: 6rpx;
			margin-left: 10rpx;
			margin-top: 16rpx;
		}
	}
}
/* 底部栏 */
.action-section {
	position: fixed;
	left: 0upx;
	bottom: 100upx;
	z-index: 95;
	width: 100%;
	height: 100rpx;
	background-color: #ffffff;
	.delivery-tip {
		font-size: 22upx;
		background-color: #fdf6ec;
		color: #d48d24;
		text-align: center;
		line-height: 42upx;
	}
	.action-section-main {
		padding: 0 0 0 32upx;
		height: 100upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.checkbox {
			height: 52upx;
			image {
				width: 30upx;
				height: 100%;
				z-index: 5;
			}
			.ibonfont {
				font-size: 36rpx;
				display: inline-block;
				width: 34rpx;
				height: 34rpx;
				color: #cccccc;
				transform: translateY(10rpx);
			}
		}
		.all-btn {
			color: #6c6c6c;
			font-size: 24upx;
			line-height: 60upx;
			padding-left: 12upx;
			font-weight: 400;
		}
		.total-box {
			flex: 1;
			text-align: right;
			.total-text {
				color: #3c3c3c;
				font-size: 24upx;
				font-weight: 400;
			}
			.price {
				font-size: 36upx;
				color: $price-color;
				font-weight: 600;
			}
			.freeExpressPrice {
				font-size: 20rpx;
				color: #9c9c9c;
			}
		}
		.confirm-btn {
			height: 52upx;
			line-height: 52upx;
			color: #ffffff;
			background-color: #f63434;
			text-align: center;
			border-radius: 52upx;
			padding: 0 30rpx;
			margin: 0 24rpx;
			font-size: 28rpx;
		}
		.diff-price {
			font-size: 24upx;
			color: #666;
			line-height: 90upx;
			padding-right: 10upx;
		}

		.del-goods-btn {
			width: 140upx;
			height: 60upx;
			line-height: 60upx;
			border: 1px solid #fd463e;
			color: #fd463e;
			font-size: 26upx;
			text-align: center;
			border-radius: 6upx;
			margin-right: 24upx;
		}
	}
}

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

.invalid-card {
	background: #ffffff;
	border-radius: 12upx;
	margin: 0 auto 24upx;
	padding: 0 24rpx 24rpx;
	width: 702rpx;
	.invalid-view {
		line-height: 94rpx;
		border-bottom: 1px solid #eeeeee;
		.invalid-tit {
			font-size: 28upx;
			font-weight: 510;
			color: #3c3c3c;
		}

		.invalid-btn {
			font-size: 24upx;
			color: $uni-color-error;
		}
	}
	.cart-list {
		.cart-item {
			.image-wrapper {
				position: relative;
				.invalid-tag {
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);
					width: 100rpx;
					height: 100rpx;
					background-color: rgba($color: #000000, $alpha: 0.5);
					font-size: 20rpx;
					color: #eeeeee;
					font-weight: 300;
					border-radius: 100%;
					text {
						position: absolute;
						left: 50%;
						top: 50%;
						transform: translate(-50%, -50%);
						text-align: center;
						display: block;
						width: 88rpx;
						height: 88rpx;
						line-height: 90rpx;
						border-radius: 100%;
						border: 2rpx solid #cccccc;
					}
				}
			}
			.item-right {
				position: relative;
				height: 152rpx;
				.title {
					height: 66rpx;
					font-size: 24rpx;
					font-weight: 400;
					color: #9b9b9b;
					line-height: 33rpx;
				}
				.invalid-msg {
					position: absolute;
					left: 0;
					bottom: 0;
					font-size: 24rpx;
					font-weight: 400;
					color: #3c3c3c;
				}
			}
		}
	}
}
</style>
