<template>
	<block>
		<!-- z-paging插件：具体使用文档请看https://z-paging.zxlee.cn/ -->
		<z-paging
			:auto="false"
			:refresher-enabled="false"
			auto-show-back-to-top
			back-to-top-bottom="300rpx"
			:paging-style="{ paddingBottom: 'constant(safe-area-inset-bottom)', paddingBottom: 'env(safe-area-inset-bottom)' }"
			ref="paging"
			v-model="dataList"
		>
			<template #top>
				<view v-if="!showEmptyCart" class="l-boxShadow c-bg-f l-flex-between o-plr-24 o-ptb-10">
					<view></view>
					<view class="c-text-16" @click="isEdit = !isEdit">{{ isEdit ? '完成' : '编辑' }}</view>
				</view>
			</template>
			<view class="o-plr-24 o-pt-20 chgUNumBox">
				<u-checkbox-group size="30" v-model="single_checkbox" placement="column" @change="single_checkboxChg">
					<view @click.self="isCheckChg(item)" class="l-flex-between l-boxShadow o-mb-20 c-bg-f o-plr-10 o-ptb-10 c-radius-10" v-for="item in dataList" style="border: 1px solid #eee;">
						<view class="l-flex-RC">
							<view class="l-flex-1"><u-checkbox :checked="item.isCheck" shape="circle" :name="item.imgId"></u-checkbox></view>
							<view class="l-flex-3">
								<u--image width="250rpx" height="250rpx" mode="aspectFit" :lazy-load="true" :fade="true" duration="450" :src="item.imgUrl">
									<view slot="error" style="font-size: 24rpx;">加载失败</view>
								</u--image>
							</view>
						</view>
						<view class="l-flex-6">
							<view class="c-text-r c-color-8" @click.stop="discountClk(item)">
								<u--text align="right" suffixIcon="arrow-right" color="#888" iconStyle="font-size: 18px;color:#888;" text="优惠码"></u--text>
							</view>
							<view class="u-line-2 o-mtb-30 c-color-8">{{ item.imgName }}</view>
							<view class="l-flex-between o-mb-20">
								<view class="">
									<text class="c-text-16 c-color-MR">￥{{ item.totalPrice }}</text>
								</view>
								<!-- 如果优惠券总金额大于0，则显示预估到手价 -->
								<view v-if="GETT_home_totalCoupon > 0" class="estiPriceCon c-text-12 c-color-f l-flex-RC">
									<view class="estiPriceTxt c-text-12 o-ptb-10 o-plr-14">预估到手</view>
									<view class="estiPrice c-text-12 o-ptb-10 o-plr-14">￥{{ compEstiPrice(item.totalPrice) }}</view>
								</view>
							</view>
							<u-number-box
								@overlimit="
									e => {
										numsOverlimit(e, item);
									}
								"
								v-model="item.nums"
								@change="
									e => {
										numsChg(e, item);
									}
								"
								disabledInput
								@minus="
									e => {
										goodMinus(e, item);
									}
								"
								@plus="
									e => {
										goodPlus(e, item);
									}
								"
							></u-number-box>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<template #bottom>
				<view v-show="!showEmptyCart" class="l-boxShadow c-bg-f l-flex-between o-plr-24 o-ptb-20" style="width: 100%;">
					<view style="flex: 0 0 70px;">
						<u-checkbox-group size="30" v-model="all_checkbox" placement="column" @change="all_checkboxChg">
							<u-checkbox shape="circle" label="全选" name="全选"></u-checkbox>
						</u-checkbox-group>
					</view>
					<!-- 支付 -->
					<view class="l-flex-between o-w" v-if="!isEdit">
						<view>
							<view class="c-color-1 c-text-14">
								合计：
								<text class="c-text-14 c-color-MR">￥{{ priceList.totalPrice }}</text>
							</view>
							<view class="l-f">
								<view class="c-color-1 c-text-14 o-mr-14">
									已优惠：
									<text class="c-text-14 c-color-MR">￥{{ priceList.discountPrices }}</text>
								</view>
								<u--text @click="amountClk" size="14" type="primary" text="查看明细"></u--text>
							</view>
						</view>
						<view>
							<u-button
								:disabled="totalNums === 0"
								v-if="GETT_loginInfos.phone"
								@click="toPayPop"
								throttleTime="2000"
								type="primary"
								shape="circle"
								size="normal"
								:text="`去支付(${totalNums})`"
							></u-button>
							<u-button
								:disabled="totalNums === 0"
								v-else
								open-type="getPhoneNumber"
								@getphonenumber="getPhone"
								type="primary"
								shape="circle"
								size="normal"
								:text="`去支付(${totalNums})`"
							></u-button>
						</view>
					</view>
					<!-- 清除 -->
					<view class="" v-else><u-button @click="deleteSelClk" :disabled="totalNums === 0" type="error" shape="circle" :text="`删除(${totalNums})`"></u-button></view>
				</view>
				<!-- 底部导航栏-占位符解决上拉刷新没显示加载更多的问题 -->
				<k-tabbar :fixed="false" :placeholder="false" :safeAreaInsetBottom="false" />
			</template>
			<!-- 空数据页面显示 -->
			<template #empty>
				<u-empty :show="showEmptyCart" mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png">
					<u-button @click="toHomeIdx" throttleTime="2000" size="small" type="primary" :customStyle="{ marginTop: '10px' }" min="1" text="查看更多商品"></u-button>
				</u-empty>
			</template>
		</z-paging>
		<u-modal @confirm="uModalConfirm" @cancel="uModalShow = false" showCancelButton :show="uModalShow" title="提示">
			<view class="slot-content"><view class="c-text-c">确定需要删除该商品吗？</view></view>
		</u-modal>
		<!-- 金额明细弹窗 -->
		<k-amountPop ref="kAmountPopRef"></k-amountPop>
		<!-- 优惠码弹窗 -->
		<k-discountPop ref="kDiscountPopRef"></k-discountPop>
		<!-- 支付弹窗 -->
		<k-payPop ref="kPayPopRef"></k-payPop>
		<!-- 支付提示弹窗 -->
		<u-modal @confirm="payShow = false" :show="payShow" title="提示" :content="payContent"></u-modal>
		<!-- 优惠券弹窗 -->
		<k-coupon ref="kCouponRef"></k-coupon>
	</block>
</template>

<script>
// 导入优惠券弹窗
import kCoupon from '@/components/common/k-coupon/index.vue';
// 导入接口
import { API_getPhone,API_setDingYue } from '@/common/api.js';
// 引入辅助函数
import { mapGetters } from 'vuex';
// 导入金额明细弹窗
import kAmountPop from '@/components/common/k-amountPop/index.vue';
// 导入优惠码弹窗
import kDiscountPop from '@/components/common/k-discountPop/index.vue';
// 导入支付弹窗
import kPayPop from '@/components/common/k-payPop/index.vue';
// 引入底部导航栏
import kTabbar from '@/components/common/k-tabbar/k-tabbar.vue';
export default {
	components: {
		kTabbar,
		kPayPop,
		kDiscountPop,
		kAmountPop,
		kCoupon
	},
	data() {
		return {
			// 是否编辑模式
			isEdit: false,
			// 支付提示弹窗
			payShow: false,
			payContent: false,
			// 控制模态框的显示
			uModalShow: false,
			// z-paging插件的主数据，用作列表渲染
			dataList: [],
			// 全选checkbox的值
			all_checkbox: [],
			// 单选checkbox的值
			single_checkbox: [],
			// 用来存储要删除的商品
			deleteShops: {}
		};
	},
	computed: {
		// 使用辅助函数
		...mapGetters(['GETT_loginInfos', 'GETT_clientId', 'GETT_home_couponList', 'GETT_home_totalCoupon']),
		// 整合购物车数据
		$S_tabbar_shopCarts() {
			let shopCarts = this.$M_GS('common', '$S_tabbar_shopCarts');
			if (!this.$M_IsEmpty(shopCarts)) {
				let cartList = [];
				for (let key in shopCarts) {
					cartList.push(shopCarts[key]);
				}
				return cartList;
			} else {
				return [];
			}
		},
		// 购物车数据是否为空
		showEmptyCart() {
			if (this.$M_IsEmpty(this.$S_tabbar_shopCarts)) return true;
			return false;
		},
		// 单选的选中值
		singleCheckbox() {
			let single_checkbox = [];
			if (this.$S_tabbar_shopCarts.length > 0) {
				single_checkbox = this.$S_tabbar_shopCarts.map(item => {
					if (item.isCheck) {
						return item.imgId;
					}
				});
			}
			return single_checkbox;
		},
		// 全选的选中值
		allCheckbox() {
			let all_checkbox = [];
			if (this.$S_tabbar_shopCarts.length > 0) {
				all_checkbox = this.$S_tabbar_shopCarts.map(item => {
					if (item.isCheck) {
						return item.imgId;
					}
				});
			}
			all_checkbox = this.arrTrimSpace(all_checkbox);
			if (all_checkbox.length === this.$S_tabbar_shopCarts.length) return ['全选'];
			return [];
		},
		// 选中的总数量
		totalNums() {
			let totalNums = 0;
			if (this.$S_tabbar_shopCarts.length > 0) {
				this.$S_tabbar_shopCarts.forEach(item => {
					if (item.isCheck) {
						totalNums = this.$M_Big(totalNums).add(item.nums);
					}
				});
			}
			return totalNums;
		},
		// 选中的总金额
		priceList() {
			let totalPrice = 0;
			let discountPrices = 0;
			if (this.$S_tabbar_shopCarts.length > 0) {
				this.$S_tabbar_shopCarts.forEach(item => {
					if (item.isCheck) {
						let discountPrice = 0;
						// 计算出每件商品的总优惠
						if (item.discountList && item.discountList.length > 0) {
							discountPrice = item.discountList.reduce((prev, cur) => {
								return this.$M_Big(prev)
									.add(cur)
									.toNumber();
							}, 0);
						}
						// 减去总优惠
						totalPrice = this.$M_Big(totalPrice)
							.add(item.totalPrice)
							.sub(discountPrice)
							.toNumber();
						// 总优惠是
						discountPrices = this.$M_Big(discountPrices)
							.add(discountPrice)
							.toNumber();
					}
				});
			}
			return {
				totalPrice,
				discountPrices
			};
		},
		// 计算预估到手价
		compEstiPrice() {
			return function(totalPrice) {
				const estiPrice = this.$M_Big(totalPrice)
					.sub(this.GETT_home_totalCoupon)
					.toNumber();
				if (estiPrice <= 0) return 0.01;
				return estiPrice;
			};
		}
	},
	mounted() {
		// 首次进入需要调用方法加载
		this.$refs.paging.complete(this.$S_tabbar_shopCarts);
	},
	updated() {
		// 当vuex数据更新时重新赋值给购物车
		this.dataList = this.$S_tabbar_shopCarts;
		this.single_checkbox = this.singleCheckbox;
		this.all_checkbox = this.allCheckbox;
	},
	methods: {
		// 点击改变选中状态
		isCheckChg(row) {
			row.isCheck = !row.isCheck;
		},
		// 点击删除按钮
		deleteSelClk() {
			// 如果没有机器编码就提示联系管理员
			uni.showModal({
				title: '提示',
				confirmText: '确定',
				confirmColor: '#3c9cff',
				content: `确定需要删除选定的商品吗？`,
				success: modelRes => {
					if (modelRes.confirm) {
						let cartList = this.$S_tabbar_shopCarts;
						let list = [];
						// 筛选出选中的商品
						if (cartList.length > 0) {
							cartList.forEach((item, index) => {
								if (item.isCheck) {
									delete cartList[index];
								} else {
									list.push(item);
								}
							});
						}
						// 把数组转成对象
						let shopCarts = this.arrAttrToOBj(list, 'imgId');
						this.$M_Dp('ACTI_SHOPCARTS', shopCarts);
						this.isEdit = false;
					}
				}
			});
		},
		// 点击查看明细
		amountClk() {
			this.$refs.kAmountPopRef.popOpen(this.$S_tabbar_shopCarts, this.priceList);
		},
		// 点击优惠码
		discountClk(row) {
			this.$refs.kDiscountPopRef.popOpen(row, 1);
		},
		// 获取手机号
		async getPhone(e) {
			const { code } = e.detail;
			// 如果用户点击允许获取手机号
			if (!!code) {
				let param = {
					code,
					id: this.GETT_loginInfos.id
				};
				// 调用获取手机号的接口
				let res = await API_getPhone(param);
				// 把手机号信息存到vuex里面
				await this.$M_Cm('MUTA_GETOPENID', res);
				console.log('GETT_loginInfos', this.GETT_loginInfos);
			}
			this.toPayPop();
		},
		// 点击支付按钮
		toPayPop() {
			// 规定支付的商品数量不能超过5
			if (this.totalNums > 3) {
				this.payContent = '支付商品的数量不能超过3件，请到购物车页面减少数量后，重新支付！！！';
				this.payShow = true;
				return;
			}
			//询问是否订阅取餐通知
			this.dingyue();
			let list = [];
			// 筛选出选中的商品
			if (this.$S_tabbar_shopCarts.length > 0) {
				this.$S_tabbar_shopCarts.forEach(item => {
					if (item.isCheck) {
						list.push(item);
					}
				});
			}
			// 把数组转成对象
			let shopCarts = this.arrAttrToOBj(list, 'imgId');
			// 组合要支付的参数
			const payParam = {
				shopCarts,
				clientId: this.GETT_clientId,
				id: this.GETT_loginInfos.id
			};
			// 如果有优惠券要提醒用户去选择优惠券
			if (this.GETT_home_couponList.length > 0) {
				uni.showModal({
					title: '提示',
					confirmText: '去使用',
					cancelText: '不使用',
					confirmColor: '#3c9cff',
					content: `当前可使用优惠券${this.GETT_home_couponList.length}张。`,
					success: modelRes => {
						if (modelRes.confirm) {
							// 打开优惠券弹窗
							this.$refs.kCouponRef.popOpen(this.GETT_home_couponList, payParam, 2, this.priceList.totalPrice);
						} else {
							// 显示支付弹窗
							this.$refs.kPayPopRef.popOpen(payParam, 2);
						}
					}
				});
			} else {
				// 显示支付弹窗
				this.$refs.kPayPopRef.popOpen(payParam, 2);
			}
		},
		//询问是否订阅取餐通知
		dingyue(){
			var that = this;
			wx.requestSubscribeMessage({
				tmplIds: ['NVmdaK4MwygT63ME830pwM6wZt4eufxhBr6jlQ2XXJ4'],
			      success(res) {
					var status = res.NVmdaK4MwygT63ME830pwM6wZt4eufxhBr6jlQ2XXJ4;
					if(status=='accept'){
						//通知后台该用户订阅了消息
						var id = that.GETT_loginInfos.id;
						API_setDingYue( {id:id} ).then(res => {
							console.log('res', res);
						});
					}
			        console.log('授权成功');
				}
			})
		},
		// 当数量超出范围，比如最小范围1触发
		numsOverlimit(e, row) {
			if (e === 'minus') {
				this.deleteShops = row;
				this.uModalShow = true;
			}
		},
		// 点击删除弹窗的确定按钮
		uModalConfirm() {
			let shopCarts = this.$S_tabbar_shopCarts;
			let list = [];
			if (shopCarts.length > 0) {
				// 根据id筛选出不是删除的那个商品
				list = shopCarts.filter(item => {
					if (item.imgId !== this.deleteShops.imgId) {
						return item;
					} else {
						// 要把优惠码和优惠价清空
						item.codeList = [];
						item.discountList = [];
					}
				});
			}
			// 把数组转成对象储存到vuex中
			let cartList = this.arrAttrToOBj(list, 'imgId');
			this.$M_Dp('ACTI_SHOPCARTS', cartList);
			this.uModalShow = false;
		},
		// 点击商品+
		goodPlus(e, row) {
			this.handleCar(e, row, 1);
		},
		// 点击商品-
		goodMinus(e, row) {
			this.handleCar(e, row, 2);
		},
		// 点击数量的+-
		numsChg(e, row) {
			// 增加用户体验
			uni.showLoading({
				title: '请稍等'
			});
			setTimeout(() => {
				uni.hideLoading();
			}, 200);
			this.handleCar(e, row, 3);
		},
		// 处理购物车数据
		handleCar(e, row, idx) {
			let shopCarts = this.$S_tabbar_shopCarts;
			if (shopCarts.length > 0) {
				shopCarts.forEach(item => {
					if (item.imgId === row.imgId) {
						switch (idx) {
							// 给优惠码和优惠价的列表添加一个0值
							case 1:
								item.codeList.push(0);
								item.discountList.push(0);
								break;
							// 去掉优惠码和优惠价的列表的最后一个
							case 2:
								item.codeList.pop();
								item.discountList.pop();
								break;
							// 找到购物车数据对应商品的，重新计算总价格
							case 3:
								item.nums = e.value;
								item.totalPrice = this.$M_Big(item.goodsPrice)
									.mul(item.nums)
									.toNumber();
								break;
						}
					}
				});
			}
			// 把数组转成对象储存到vuex中
			let cartList = this.arrAttrToOBj(shopCarts, 'imgId');
			this.$M_Dp('ACTI_SHOPCARTS', cartList);
		},
		// 根据数组的某个属性转成对象
		arrAttrToOBj(arr, attr, obj = {}) {
			if (arr.length > 0) {
				arr.forEach(item => {
					obj[item[attr]] = item;
				});
				return obj;
			} else {
				return {};
			}
		},
		// 去掉数组的空格，null，undefeated类型
		arrTrimSpace(array) {
			let list = [];
			array.forEach(item => {
				if (item == '' || item == null || typeof item == 'undefined') {
				} else {
					list.push(item);
				}
			});
			return list;
		},
		// 点击单选按钮
		single_checkboxChg(e) {
			let shopCarts = this.$S_tabbar_shopCarts;
			let singleList = this.arrTrimSpace(e);
			// 如果存在单选
			if (singleList.length > 0) {
				if (shopCarts.length > 0) {
					shopCarts.forEach(item => {
						item.isCheck = false;
						singleList.forEach(item1 => {
							if (item.imgId === item1) {
								item.isCheck = true;
							}
						});
					});
				}
			} else {
				if (shopCarts.length > 0) {
					// 取消全选，具体是遍历数组，把全选的isCheck改为false
					shopCarts.forEach(item => {
						item.isCheck = false;
					});
				}
			}
			// 把数组转成对象储存到vuex中
			let cartList = this.arrAttrToOBj(shopCarts, 'imgId');
			this.$M_Dp('ACTI_SHOPCARTS', cartList);
		},
		// 点击全选按钮
		all_checkboxChg(e) {
			let shopCarts = this.$S_tabbar_shopCarts;
			let all_checkbox = [];
			// 全选的长度大于0
			if (e.length > 0) {
				if (shopCarts.length > 0) {
					// 全选，具体是遍历数组，把全选的isCheck改为true，并且把控制全选的checkbox赋值
					shopCarts.forEach(item => {
						item.isCheck = true;
						all_checkbox.push(item.imgId);
					});
				}
			} else {
				// 取消全选，具体是遍历数组，把全选的isCheck改为false
				if (shopCarts.length > 0) {
					shopCarts.forEach(item => {
						item.isCheck = false;
					});
				}
			}
			// 全选的值
			this.all_checkbox = all_checkbox;
			// 把数组转成对象储存到vuex中
			let cartList = this.arrAttrToOBj(shopCarts, 'imgId');
			this.$M_Dp('ACTI_SHOPCARTS', cartList);
		},
		// 点击去首页
		toHomeIdx() {
			// 改变vuex的数据
			this.$M_Dp('ACTI_TABIDX', 0);
		}
	}
};
</script>

<style lang="scss" scoped>
.estiPriceCon {
	.estiPriceTxt {
		position: relative;
		color: #ff9900;
		background-color: #fff5f4;
		border-right: 1px solid #fff;
	}

	.estiPrice {
		background-color: #f15c34;
		border-top-right-radius: 10rpx;
		border-bottom-right-radius: 10rpx;
	}
}
</style>
