<template>
	<view class="pages">
		<div class="shop_info">
			<h3>门店确认</h3>
			<div class="address">
				<div class="address_1">{{ shopData.name }}</div>
				<div v-if="shopData.distance && shopData.distance!=-1" class="address_2">距您{{ shopData.distance }}，请确定门店后下单</div>
				<div v-else class="address_2">请确定门店后下单</div>
			</div>
			<div class="take_order"></div>
      <div>
        <div class="title">取单时间</div>
		<div class="time">现在下单，预计 <span class="min">{{ duration }}</span> 分钟后取餐</div>
      </div>
		</div>
		<div class="goods_info">
			<span class="goodInfoTitle">商品详细</span>
			<div class="goods" v-for="item in goods" :key="item.goodsId">
				<div class="goods_item">
					<image v-if="item.pics.thumbnailApplet" class="goods_img" :src="item.pics.thumbnailApplet"/>
					<image v-else class="goods_img" :src="item.pics.thumbnail" />

					<div class="goods_text">
						<div class="goods_name">
							<div class="name">{{ item.name }}</div>
							<div class="price">¥{{ Utils.isInteger(setPrice(item.sku.discount)) }}</div>
						</div>
						<div class="goods_psce">
							<div class="psce_name">
								<span v-for="(rule,index) in item.sku.rules" :key="rule.ruleId">
									{{ rule.ruleName }}
									<span v-if="index!=item.sku.rules.length-1">/</span>
								</span>
							</div>
							<div class="size">x {{ item.num }}</div>
						</div>
					</div>
				</div>
			</div>

			<div class="coupon" @click="goCouponSelect">
				<div class="title">HOOLOO券</div>
				<div :class="[ticketNum>0?'num-action':'num']">
					<span v-if="selectCoupon.couponAmount" class="price">-￥{{selectCoupon.couponAmount}}</span>
					<span v-else>{{ticketNum>0?ticketNum+'张可用':'暂无可用优惠'}}</span>
					<image v-if="!ticketNum>0" class="arrow-right-select" :src="'../../../static/imgs/jiantouhei.png'" />
					<image v-else class="arrow-right-select" :src="'../../../static/imgs/jiantoufen.jpg'" />
				</div>
			</div>

			<div class="total">
				<div class="size">共{{ totalNum }}件商品</div>
				<div class="priceBox">
					<span class="paid_in">实付</span>
					<span class="money">￥{{ Utils.isInteger(totalPrice) }}</span>
				</div>
			</div>
		</div>
		<div class="Payment_method">
			<div>支付方式</div>
			<div class="type">
				<image mode="aspectFit" src="../../../static/imgs/weixin-3.png" class="icon"></image>
				<span>微信支付</span>
			</div>
		</div>
		<div class="TermsOfAgreement" v-if="!TermsStatus">
			<div @click="clickAgreeTerms" :class="agreeTerms?'checked':'nochecked'"></div>
			<div class="content">
				已阅读并同意<span @click="goTerms(1)">《用户协议》</span>、<span @click="goTerms(2)">《隐私权政策》</span>、<span @click="goTerms(3)">《支付协议》</span>
			</div>
		</div>
		<div style="height:150rpx"></div>
		<div class="footer" :style="{'padding-bottom':BottomSafeHeight+'px'}">
			<div class="total">
				<div class="the_sum">
					<span class="name">实付</span>
					<span class="price">￥{{ Utils.isInteger(totalPrice) }}</span>
				</div>
				<!-- <div class="sun">
					<div class="price">总优惠￥{{ reduction }}</div>
				</div> -->
			</div>
			<view v-if="userms" class="payment" @click="messageAndSave">付款</view>
			<button v-if="!userms" class="payment" style="border-radius: 0;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">付款</button>
		</div>
		<show-toast ref="toast"/>
	</view>
</template>

<script>
import { $EventBus } from "@/utils/EventBus";
import Utils from '@/utils/utils'
import Menu from '@/request/menu'
import User from '@/request/user'
import Order from '@/request/order'
export default {
	onShow() {


		if (this.goods) {
			Order.getWaitTine({
				shopId: uni.getStorageSync('shopData').id,
				goods: this.goods
			}).then(({ data }) => {
				this.duration = data.data
			})
		}
		this.BottomSafeHeight = uni.getStorageSync('BottomSafeHeight')
		this.TermsStatus = uni.getStorageSync('TermsStatus') || false
	},
	onLoad(option) {
		console.log(123)

		// 清除优惠卷信息
		this.$store.commit("cleanInfo",{})


		if(!this.userms){
			User.wxLoginAndGetOpenid(true).then(loginInfo=>{
				this.loginInfo = loginInfo
			})
		}
		// 商品详情页点击立即支付进入
		if (option.goodsList) {
			const shopData = uni.getStorageSync('shopData');
			this.shopData = shopData
			this.buyType = 3;
			console.log(uni.getStorageSync('goodsList'));
			this.goods = uni.getStorageSync('goodsList') || [];
			this.payType = '2'
			this.saveGetTicket()
			return
		}

		// 微信扫码进入
		this.option = JSON.stringify(option)
		const { q } = option;
		// console.log(q);
		if (q) {
			User.getLocation((state, params) => {
				uni.removeStorageSync('shopCarInfo');
				$EventBus.$emit('updateCar');
				let id = decodeURIComponent(q).split('?')[1].split('=')[1];
				// let id = q;
				Menu.getScreenShopCar(id, params).then(res => {
					const data = JSON.parse(res.data.data);
					console.log(data);
					this.shopData = data.shop;
					this.buyType = data.screenNo;
					this.goods = data.goods.map(item => {
						const data = { ...item, skuId: item.sku.skuId, flag: true }
						Utils.getallNum(data, true) // 不校验数量
						return data
					})
				})
			})
			return
		}

		// 购物车点击进入
		const shopData = uni.getStorageSync('shopData');
		this.shopData = shopData
		this.buyType = 3;
		const shopCarInfo = uni.getStorageSync('shopCarInfo') || []
		this.goods = shopCarInfo.filter(item => item.flag);
		Order.getWaitTine({
			shopId: uni.getStorageSync('shopData').id,
			goods: this.goods
		}).then(({ data }) => {
			this.duration = data.data
		})
		this.saveGetTicket()

	},
	data() {
		return {
			goods: [],
			buyType: '',
			shopData: {},
			option: '',
			payType: '1',
			duration: '',
			loginInfo: '',
			BottomSafeHeight:0,
			Utils,
			agreeTerms:true,
			TermsStatus:true,
			ticketNum:0
		}
	},
	computed: {
		selectCoupon() {
			const data = this.$store.state.order.selectTicket
			return data
		},
		userms() {
			return this.$store.getters.Authorization;
		},
		totalNum() {
			let totalNum = 0;
			this.goods.map(item => {
				item.flag ? totalNum += item.num : totalNum += 0
			})
			return totalNum
		},
		reduction() {
			let price = 0;
			let discountNum = 0;
			this.goods.forEach(item => {
				const sku = item.sku;
				if (item.flag) {
					discountNum += item.num * sku.discount
					price += item.num * sku.price
				} else {
					discountNum += 0
					price += 0
				}
			})
			return (price - discountNum).toFixed(2)
		},
		amountOld() {
			let totalPrice = 0;

			this.goods.forEach(item => {
				const sku = item.sku;
				item.flag ? totalPrice += (item.num * sku.discount) : (totalPrice += 0)
			})

			return totalPrice.toFixed(2)
		},
		totalPrice() {
			let totalPrice = 0;

			this.goods.forEach(item => {
				const sku = item.sku;
				item.flag ? totalPrice += (item.num * sku.discount) : (totalPrice += 0)
			})

			totalPrice-=this.selectCoupon.couponAmount||0

			return totalPrice.toFixed(2)
		}
	},
	methods: {
		// 勾选隐私协议
		clickAgreeTerms(){
			this.agreeTerms = !this.agreeTerms
		},
		// 跳转隐私协议页面
		goTerms(type) {
			uni.navigateTo({url:'/orderSubPackage/pages/terms/index?type='+type})
		},

		itemReduction(discount, price, num) {
			return ((price - discount) * num).toFixed(2)
		},
		// 手机号授权登录
		getPhoneNumber(e) {
			if (e.detail.errMsg == 'getPhoneNumber:ok') {
				e.loginInfo = this.loginInfo
				User.getPhoneNumber(e);
			} else if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
				this.showToast({ title: '已拒绝手机号授权', icon: 'error' })
			}
		},
		messageAndSave() {
			if(!this.TermsStatus&&!this.agreeTerms){
				this.showToast({ title: "请同意下方协议条款" });
				return
			}else{
				if(this.agreeTerms)uni.setStorageSync('TermsStatus',true)
			}
			const tmpid = ['1uErx-15S-3vuopXSvvsxCeM_Jd-1iZC-nXzd2yW3QU', 'Q4HDwBEvpTXpwtZktqWm4SZOTEuQK1x48xjqjD2GqyM', 'Fu_CPIXa0cnJ4EDdVKqFQ3qqKJccMqt2oorI5mfNq74']
			const val = {}
			wx.requestSubscribeMessage({
				// 'Oq_zfRWRXijvXenRmfD2PARgpvdYlbkjR4laxKmBqb0' 
				tmplIds: tmpid,
				success: (res) => {
					const finalValue = Object.values(res).indexOf('reject')
					tmpid.forEach(item=>{
						val[item] = res[item]==='accept'?true:false
					})
					if(finalValue===-1){
						uni.setStorageSync('isMessage', 'true')
						User.setAllow(1)
						this.saveReserve(val)
					}else{
						User.setAllow(2)
						this.saveReserve(val)
					}
				},
				fail: (err) => {
					tmpid.forEach(item=>{
						val[item] = false
					})
					console.log(err);
					User.setAllow(2)
					this.saveReserve(val)
				}
			})
		},
		// 组装数据
		AssemblyOrder(){
			let list = [];
			if (this.payType == '1') {
				list = uni.getStorageSync('shopCarInfo').filter((v) => v.flag == true);
			} else {
				list = uni.getStorageSync('goodsList').filter((v) => v.flag == true);
			}
			return Utils.AssemblyOrder(this.shopData, this.totalPrice, this.totalNum, this.buyType, list);
		},
		// 结算组装数据获取优惠卷列表
		async  saveGetTicket() {
			// 组装购物车数据或者立即支付数据
			const res = this.AssemblyOrder()
			if(res){
				const {data:list}  = await Menu.requestTicketList(res);
				const {data:num}  = await Menu.requestTicketNum(res);
				if(list.code==200){
					const {data} = list
					this.ticketList = data
					this.$store.commit('setTickerList',this.ticketList)
				}
				if(num.code==200){
					const {data} = num
					this.ticketNum = data
				}
			}
		},
		//结算组装数据发起订单
		async saveReserve(val={}) {
			// 组装购物车数据或者立即支付数据
			let list = [];
			if (this.payType == '1') {
				list = uni.getStorageSync('shopCarInfo').filter((v) => v.flag == true);
			} else {
				list = uni.getStorageSync('goodsList').filter((v) => v.flag == true);
			}
			const shopInfo = uni.getStorageSync('shopData')
			const {lat,lng} = shopInfo
			// sendMsgFlag1：下单成功通知
			// sendMsgFlag2：订单状态变更通知
			// sendMsgFlag3：取餐提醒
			const sendMsgFlag1 = val['1uErx-15S-3vuopXSvvsxCeM_Jd-1iZC-nXzd2yW3QU']?1:0
			const sendMsgFlag2 = val['Q4HDwBEvpTXpwtZktqWm4SZOTEuQK1x48xjqjD2GqyM']?1:0
			const sendMsgFlag3 = val['Fu_CPIXa0cnJ4EDdVKqFQ3qqKJccMqt2oorI5mfNq74']?1:0

			let res = await Utils.AssemblyOrder(this.shopData, this.totalPrice, this.totalNum, this.buyType, list);
			if (res) {
				const {amount,...resule} = res
				const sendData = {
					...resule,
					amount:this.amountOld,
					paidAmount:amount,
					lat,
					lng,
					sendMsgFlag1,
					sendMsgFlag2,
					sendMsgFlag3
				}
				if(JSON.stringify(this.selectCoupon)!="{}"){
					sendData.couponId = this.selectCoupon.id||'',
					sendData.couponAmount = this.selectCoupon.couponAmount||0
				}
				let orderInfo = await Menu.saveReserve(sendData);
				if (orderInfo && orderInfo.data.code == 200) {
					await Menu.requestPayment(orderInfo.data.data, res, this.buyType);
				}
				
			}
		},
		goCouponSelect() {
			uni.navigateTo({ url: `/orderSubPackage/pages/coupon/index` })
		}
	}
}
</script>

<style lang="scss" scoped>
.pages {
	padding-top: 1rpx;
}

.shop_info {
	width: 686rpx;
	background: #FFFFFF;
	margin: 0 auto;
	margin-top: 32rpx;
	padding: 24rpx 32rpx;
	box-sizing: border-box;


	h3 {
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		font-weight: 500;
		color: #333333;
	}

	.address {
		margin-top: 17.81rpx;

		.address_1 {

			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #333333;
		}

		.address_2 {
			margin-top: 18rpx;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
		}
	}

	.take_order {
		margin-top: 25rpx;
		padding-top: 23.83rpx;
		border-top: 0.1px solid #F4F4F4;
		height: 2rpx;
	}
  	.title {
			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #333333;
		}

		.time {
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;

			.min {
				color: #0050F6;
				font-size: 32rpx;
				font-family: Futura-Medium, Futura;
				font-weight: normal;
				margin: 0 8rpx;
				display: inline-block;
			}
		}
}

.goods_info {
	width: 686rpx;
	background: #FFFFFF;
	margin: 0 auto;
	margin-top: 32rpx;
	padding: 26rpx 30rpx 24rpx 30rpx;
	box-sizing: border-box;


	.goodInfoTitle {
		height: 40rpx;
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #333333;
		line-height: 40rpx;
	}

	.goods {
		margin-top: 24rpx;
		border-bottom: 0.1px solid #F4F4F4;
		padding-bottom: 32rpx;

		.goods_item {
			display: flex;
			align-items: center;
		}

		.goods_img {
			height: 112rpx;
			width: 112rpx;
			background-color: #eee;
			margin-right: 32rpx;
		}

		.goods_text {
			flex: 1;

			.goods_psce,
			.goods_name {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.name {
					font-size: 28rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #666666;
				}

				.price {
					font-size: 28rpx;
					font-family: Futura-Medium, Futura;
					font-weight: 500;
					color: #333333;
				}

				.psce_name {
					font-size: 24rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #999999;
				}

				.size {
					font-size: 24rpx;
					font-family: ArialMT;
					color: #666666;
				}
			}

			.goods_psce {
				margin-top: 18.65rpx;
			}
		}
	}

	.discount {
		margin-top: 25rpx;

		.discount_1 {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 600;
			color: #333333;

			.price {
				font-family: Arial-BoldMT, Arial;
				font-weight: normal;
				color: #EB5F17;
			}
		}

		.concessional_rate {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;
			margin-top: 18rpx;

			.price {

				font-family: Arial-BoldMT, Arial;
				font-weight: 700;
				color: #000;
			}
		}
	}

	.coupon {
		display: flex;
		align-items: center;
		display: flex;
		justify-content: space-between;
		margin-top: 24.38rpx;
		margin-bottom: 23.57rpx;

		.title {
			font-size: 28rpx;
			font-family: ArialMT;
			color: #333333;
			height: 40rpx;
			line-height: 40rpx;
		}
		.num {
			font-size: 28rpx;
			height: 40rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			display: flex;
			align-items: center;
			color: #999999;
			height: 40rpx;
			line-height: 40rpx;
			.price {
				font-family: Futura-Medium, Futura;
			}
			.arrow-right-select{
				width: 15.27rpx;
				height: 19.68rpx;
				margin-left: 8rpx;
			}
		}
		.num-action {
			font-size: 28rpx;
			height: 40rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			display: flex;
			align-items: center;
			color: #FF63BA;
			height: 40rpx;
			line-height: 40rpx;
			.price{ 
				font-family: Futura-Medium, Futura;
			}
			.arrow-right-select{
				width: 15.27rpx;
				height: 19.68rpx;
				margin-left: 8rpx;
			}
		}

	}

	.total {
		display: flex;
		align-items: center;
		display: flex;
		justify-content: space-between;
		padding-top: 24.16rpx;
		border-top: 0.1px solid #F4F4F4;

		.size {
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;
		}

		.the_sum{
     	display: flex;
			align-items: flex-end;
			.paid_in {
				font-size: 28rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}

			.money {
				font-weight: 500;
				font-size: 36rpx;
        font-family: Futura-Medium, Futura;
				color: #333333;
				// vertical-align: middle;
        line-height: 40rpx;
			} 
    }
    .priceBox{
			display: flex;
			align-items: center;
			.paid_in {
				font-size: 28rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}

			.money {
				font-weight: 500;
				font-size: 36rpx;
        font-family: Futura-Medium, Futura;
				color: #333333;
				// vertical-align: middle;
        line-height: 40rpx;
			}
		}

	}
}

.Payment_method {
	width: 686rpx;
	margin: 32rpx auto 0;
	padding: 26rpx 30rpx;
	background: #FFFFFF;
	font-size: 28rpx;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #333333;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;

	.type {
		display: flex;
		align-items: center;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;

		.icon {
			width: 32rpx;
			height: 32rpx;
			margin-right: 8rpx;
		}
	}
}

.TermsOfAgreement {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	margin-top: 31rpx;
	margin-left: 32rpx;

	.content {
		font-size: 24rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #666666;
		line-height: 34rpx;
		span {
			color: #0050F6;
		}
	}
	.checked {
        width: 24rpx;
        height: 24rpx;
        background: url('../../../static/imgs/duigouxuanzhong.png') center center no-repeat;
		background-size:100% 100%;
        margin-right: 8rpx;
    }
    .nochecked {
        width: 24rpx;
        height: 24rpx;
        background: url('../../../static/imgs/weixuanzhong.png') center center no-repeat;
		background-size:100% 100%;
        margin-right: 8rpx;
    }
}

.footer {
	height: 100rpx;
	background: #fff;
	position: fixed;
	bottom: 0;
	display: flex;
	align-items: center;
	width: 100%;

	.total {
		flex: 1;
		padding-left: 30rpx;

		.the_sum {
			display: flex;
			align-items: center;
			.name {
				font-size: 28rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}

			.price {
				margin-left: 13.36rpx;
				font-size: 36rpx;
				font-family: Futura-Medium, Futura;
				font-weight: 500;
				color: #333333;
        		line-height: 40rpx;
			}
		}

		.sun {
			font-size: 20rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FF0E00;
			margin-top: 10rpx;
		}
	}

	.payment {
		width: 200rpx;
		height: 100%;
		background: #0050F6;
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 100rpx;
		text-align: center;
	}
}
</style>