<template>
	<view
		class="o-h c-bg-f o-plr-30 singleByeIdx"
	>
		<view class="o-h l-f l-flex-d l-flex-j-b ">
			<view class="l-flex-center o-mt-50 l-flex-3">
				<u--image
					:width="GETT_miniProduct.includes(GETT_singleBye_shopCarts.imgId) ? '500rpx' : '450rpx'"
					:height="GETT_miniProduct.includes(GETT_singleBye_shopCarts.imgId) ? '500rpx' : '450rpx'"
					mode="aspectFit"
					:lazy-load="true"
					:fade="true"
					duration="450"
					:src="GETT_singleBye_shopCarts.imgUrl"
				>
					<view slot="error" style="font-size: 24rpx;">加载失败</view>
				</u--image>
			</view>
			<view class="l-f l-flex-d l-flex-center l-flex-1 chgUNumBox">
				<u-number-box
					button-size="48"
					v-model="GETT_singleBye_shopCarts.nums"
					@change="
						e => {
							numsChg(e, GETT_singleBye_shopCarts);
						}
					"
					disabledInput
					@minus="
						e => {
							goodMinus(e, GETT_singleBye_shopCarts);
						}
					"
					@plus="
						e => {
							goodPlus(e, GETT_singleBye_shopCarts);
						}
					"
				></u-number-box>
				<u-button :customStyle="{marginTop:'20px'}" @click="discountClk" type="primary" shape="circle" text="添加优惠码"></u-button>
			</view>
			<view class="l-flex-1 l-f l-flex-d l-flex-j-e">
				<view class="o-mt-30 l-flex-between">
					<u-button @click="toIndex" plain shape="circle" type="primary" text="购买更多"></u-button>
					<view style="flex:0 0 120px;">
						<view class="c-color-1 c-text-14">
							合计：
							<text class="c-text-14 c-color-MR">￥{{ priceList.totalPrice }}</text>
						</view>
						<view class="c-color-1 c-text-14 o-mr-14">
							已优惠：
							<text class="c-text-14 c-color-MR">￥{{ priceList.discountPrices }}</text>
						</view>
							<!-- 如果优惠券总金额大于0，则显示预估到手价 -->
							<view v-if="GETT_home_totalCoupon > 0" class="c-text-12 c-color-f l-flex-RC" style="color:#ff9900;">
								<view class="c-text-14">预估到手：</view>
								<view class="c-text-14" style="color:#f45632;">
									￥{{ compEstiPrice(priceList.totalPrice) }}
								</view>
							</view>
						<view class=""><u--text @click="amountClk" size="14" type="primary" text="查看明细"></u--text></view>
					</view>
					<u-button v-if="GETT_loginInfos.phone" @click="toPayPop" throttleTime="2000" type="primary" shape="circle" text="去支付"></u-button>
					<!-- :text="`去支付(￥${GETT_singleBye_shopCarts.totalPrice})`" -->
					<u-button v-else open-type="getPhoneNumber" @getphonenumber="getPhone" type="primary" shape="circle" text="去支付"></u-button>
				</view>
			</view>
		</view>
		<!-- 金额明细弹窗 -->
		<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>
	</view>
</template>

<script>
// 导入优惠券弹窗
import kCoupon from '@/components/common/k-coupon/index.vue';
// 导入金额明细弹窗
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 { API_getPhone,API_setDingYue } from '@/common/api.js';
// 引入辅助函数
import { mapGetters } from 'vuex';
export default {
	components: {
		kPayPop,
		kDiscountPop,
		kAmountPop,
		kCoupon
	},
	data() {
		return {
			// 支付提示弹窗
			payShow: false,
			payContent: false
		};
	},
	computed: {
		// 获取vuex中购物车的数据
		$S_tabbar_shopCarts() {
			return this.$M_GS('common', '$S_tabbar_shopCarts');
		},
		// 使用辅助函数
		...mapGetters(['GETT_miniProduct', 'GETT_loginInfos', 'GETT_clientId', 'GETT_singleBye_shopCarts','GETT_home_couponList', 'GETT_home_totalCoupon']),

		// 选中的总金额
		priceList() {
			const item = this.GETT_singleBye_shopCarts;
			// 总价格
			let totalPrice = 0;
			// 总优惠
			let discountPrices = 0;
			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;
			};
		}
	},
	onLoad() {
		uni.setNavigationBarTitle({
			title: this.GETT_singleBye_shopCarts.imgName
		});
	},
	methods: {
		// 点击商品+
		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) {
			switch (idx) {
				// 给优惠码和优惠价的列表添加一个0值
				case 1:
					row.codeList.push(0);
					row.discountList.push(0);
					break;
				// 去掉优惠码和优惠价的列表的最后一个
				case 2:
					row.codeList.pop();
					row.discountList.pop();
					break;
				// 找到购物车数据对应商品的，重新计算总价格
				case 3:
					row.nums = e.value;
					row.totalPrice = this.$M_Big(row.goodsPrice)
						.mul(row.nums)
						.toNumber();
					break;
			}
			this.$M_Cm('MUTA_SINGSHOPCARTS', row);
		},
		// 点击查看明细
		amountClk() {
			console.log(this.GETT_singleBye_shopCarts, 'this.GETT_singleBye_shopCarts');
			this.$refs.kAmountPopRef.popOpen({}, this.priceList);
		},
		// 点击优惠码
		discountClk() {
			this.$refs.kDiscountPopRef.popOpen(this.GETT_singleBye_shopCarts, 2);
		},
		// 获取手机号
		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);
			}
			this.toPayPop();
		},
		// 点击支付按钮
		toPayPop() {
			//询问是否订阅取餐通知
			this.dingyue();
			console.log('单个商品', this.GETT_singleBye_shopCarts);
			// 如果是一件商品，那么要给优惠码加个0
			if(this.GETT_singleBye_shopCarts.nums === 1){
				// 如果没有优惠码
				if(this.GETT_singleBye_shopCarts.codeList.length===0){
					this.GETT_singleBye_shopCarts.codeList = [0];
				}
			}
			// 规定支付的商品数量不能超过5
			if (this.GETT_singleBye_shopCarts.nums > 5) {
				this.payContent = '支付商品的数量不能超过5件，请减少数量后，重新支付！！！';
				this.payShow = true;
				return;
			}
			let shopCarts = {};
			shopCarts[this.GETT_singleBye_shopCarts['imgId']] = this.GETT_singleBye_shopCarts;
			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, 3, this.priceList.totalPrice);
						} else {
							// 显示支付弹窗
							this.$refs.kPayPopRef.popOpen(payParam, 3);
						}
					}
				});
			}else{
				// 显示支付弹窗
				this.$refs.kPayPopRef.popOpen(payParam, 3);
			}
		},
		//询问是否订阅取餐通知
		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('授权成功');
				}
			})
		},
		// 加入购物车
		addCart() {
			let row = this.GETT_singleBye_shopCarts;
			// 加入购物车初始状态都是选中状态
			row['isCheck'] = true;
			// 获取vuxe购物车数据
			let shopCarts = this.$S_tabbar_shopCarts;
			// 如果不存在imgId这个属性，则创建
			if (!shopCarts[row['imgId']]) {
				// $M_Big用来计算总数量的方法（具体用法请看common）
				row['totalPrice'] = this.$M_Big(row['goodsPrice'])
					.mul(row['nums'])
					.toNumber();
				// 用$M_Extend继承row创建新对象并赋值给shopCarts的属性
				shopCarts[row['imgId']] = this.$M_Extend(row, {
					nums: row['nums']
				});
			} else {
				shopCarts[row['imgId']]['codeList'] = shopCarts[row['imgId']]['codeList'].concat(row.codeList);
				shopCarts[row['imgId']]['discountList'] = shopCarts[row['imgId']]['discountList'].concat(row.discountList);

				// 如果存在imgId这个属性，则数量+1，总数totalPrice=价格goodsPrice*数量nums
				let nums = shopCarts[row['imgId']]['nums'] + row['nums'];
				// $M_Big用来计算总数量的方法（具体用法请看common）
				row['totalPrice'] = this.$M_Big(row['goodsPrice'])
					.mul(nums)
					.toNumber();
				shopCarts[row['imgId']] = this.$M_Extend(row, {
					nums
				});
			}
			console.log('shopCarts', shopCarts);
			// 修改vuex购物车数据
			this.$M_Dp('ACTI_SHOPCARTS', shopCarts);
			// 处理优惠码集合
			this.handleDiscList();
		},
		handleDiscList() {
			// 获取购物车数据
			let shopCarts = this.GETT_singleBye_shopCarts;
			let codes = [];
			// 重新组合优惠码
			codes = [...new Set(codes.concat(shopCarts['codeList']))];
			// 储存优惠码，用来校验重复问题
			this.$M_Cm('MUTA_DISCOUNTCODE', codes);
		},
		// 去首页
		toIndex() {
			this.addCart();
			this.$M_Back();
		}
	}
};
</script>

<style lang="scss" scoped>
	.singleByeIdx {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>
