<template>
	<view class="pad-x150" v-if="isLoading">
		<status-nav :ifReturn="true" navBarTitle="确认订单" :marginBottom="0"></status-nav>
		<!-- 收件人信息 -->
		<view class="settlement-content pad-zy20 border-box">
			<view class="section background-white radius30 mar-x40 pad-all25 border-box font30">
				<view class="title">收件人信息</view>
				<view class="addressee-info mar-s20 flex" @tap="toAddress">
					<view class="txt" v-if="default_address">
						<view class="font30 mar-x10">{{default_address.name}}<text>{{default_address.phone}}</text></view>
						<text class="font24 color-8c">{{default_address.province_str}}{{default_address.city_str}}{{default_address.county_str}}{{default_address.address}}</text>
					</view>
					<view class="txt" v-else>
						<view class="font30 color-8c" style="line-height: 2;">请选择地址</view>
					</view>
					<image src="/static/icon/icon-more.png" mode="widthFix"></image>
				</view>
			</view>
			<!-- 订单信息 -->
			<view class="section background-white radius30 mar-x40 pad-all25 border-box font30">
				<view class="title">订单信息</view>
				<view class="shop-slide-list">
					<view class="shop-slide-item">
						<view class="item border-box background-white flex" v-for="(item,index) in orderShopList" :key="index">
							<view class="shop-img radius30">
								<image :src="item.spu_cover" mode="widthFix"></image> 
							</view>
							<view class="shop-txt">
								<view class="shop-txt-top">
									<view class="title font30 clips1">{{item.goods_name}}</view>
									<view class="specs font24 color-66 mar-sx10 clips2">规格：{{item.sku_name}}</view>
								</view>
								<view class="shop-txt-bottom flex">
									<!-- 商品价格 -->
									<view class="price font30 color-red">￥{{item.price}}<text class="font24 color-66">x{{item.num}}</text></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 优惠选择 -->
			<view class="section background-white radius30 mar-x40 pad-all25 border-box font30" v-if="orderInfo.is_distributor==0">
				<view class="title">优惠选择</view>
				<view class="section-list font30">
					<view class="item flex" v-if="orderInfo.vip_level>0">
						<label class="radio" @tap="chooseEv('vip')"><radio :checked="vipCheck" color="#febf00"/><text>会员折扣</text></label>
						<view class="txt flex">
							<view>{{orderInfo.membership_discount}}折</view>
							<view class="btn"></view>
						</view>
					</view>
					<view class="item flex" @tap.stop="toCoupon">
						<label class="radio" @tap.stop="chooseEv('coupon')">
							<radio :checked="couponCheck" color="#febf00" :disabled="couponList.length?false:true"/>
							<text>优惠券</text>
						</label>
						<view class="txt flex">
							<view class="color-red" v-if="couponList.length">{{'-'+ couponList[couponIndex].amount}}</view>
							<view class="btn">
								<image src="/static/icon/icon-join.png" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 积分抵扣 -->
			<view class="section background-white radius30 mar-x40 pad-all25 border-box font30">
				<view class="title">积分抵扣</view>
				<view class="section-list font30">
					<view class="item flex">
						<label class="radio" @tap="chooseEv('score')">
							<radio :checked="scoreCheck" color="#febf00" :disabled="!checkedYes"/>
							<text>可用积分</text>
						</label>
						<view class="txt flex">
							<view class="color-66">{{orderInfo.available_score}}</view>
							<view class="btn"></view>
						</view>
					</view>
				</view>
			</view>
			<!-- 支付方式 -->
			<view class="section background-white radius30 mar-x40 pad-all25 border-box font30">
				<view class="title">支付方式</view>
				<view class="section-list font30">
					<view class="item flex">
						<label class="radio"><radio :checked="wechatCheck" @tap="wechatCheck=!wechatCheck" color="#febf00"/>微信支付</label>
					</view>
					<view class="item flex">
						<label class="radio" @tap="priceCheck=!priceCheck">
							<radio :checked="priceCheck" color="#febf00" :disabled="orderInfo.available_balance>0?false:true"/>
							<text>余额支付</text>
						</label>
						<view class="txt flex">
							<view class="color-66">{{parseFloat(orderInfo.available_balance)>0?orderInfo.available_balance:0}}</view>
							<view class="btn"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 尾部 -->
		<view class="pull-footer-bg background-white pad-all20 radius30 border-box">
			<view class="pull-footer background-grey radius30 pad-all20 border-box flex">
				<view class="price color-ff" style="margin-left: 24rpx;">
					<view class="font36 flex">合计：<text v-if="totalPrice>0">￥</text>{{totalPrice}}</view>
					<text class="font26" v-if="discountPrice>0">总优惠：￥{{discountPrice}}</text>
				</view>
				<view class="btn font36 color-48 background-orange radius30 flex" @tap="submitEv">立即支付</view>
			</view>
		</view>
		<!-- 优惠券弹窗 -->
		<view class="pull-bg" style="background-color: rgba(0,0,0,.3);" v-show="isCoupon"></view>
		<view class="coupon-box border-box background-white" v-show="isCoupon">
			<view class="title font36 background-white pad-sx25">优惠券选择</view>
			<scroll-view scroll-y="true" class="coupon-scoll">
				<view class="coupon-list pad-zy20 border-box">
					<view class="coupon-item radius30 mar-s40 flex" v-for="(item,index) in couponList" :key="index" @tap="changeCoupon(index)">
						<view class="price color-ff border-box"><text class="font30">￥</text>{{item.amount.split(".")[0]}}<text class="font30">{{'.'+item.amount.split(".")[1]}}</text></view>
						<view class="txt">
							<view class="font36">{{item.name}}</view>
							<view class="font24 color-8c mar-s10">满{{parseInt(item.condition)}}减{{parseInt(item.amount)}}</view>
							<view class="font24 color-8c mar-s10">{{item.begin_at}}至{{item.end_at}}</view>
						</view>
						<view class="btn mar-zy20 color-ff font24" v-if="index == couponIndex">已选择</view>
					</view>
				</view>
			</scroll-view>
			<view class="coupon-btns border-box pad-zy20 color-48 mar-sx30 flex">
				<view class="btn font36 radius30 background-orange" @tap="useCoupon">确认使用</view>
				<view class="btn font36 radius30" style="background-color: #e9e9e9;" @tap="closeCoupon">取消选择</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderInfo:{}, //订单信息
				default_address:{}, //地址信息
				orderShopList:[], // 商品信息
				couponList:[], //优惠券列表
				couponIndex:0, //优惠券选择
				vipCheck: false, //会员折扣
				couponCheck:false, // 优惠选择
				scoreCheck:false, //积分抵扣
				wechatCheck:true, //微信支付
				priceCheck:false, //余额支付
				isCoupon:false, //优惠券弹窗
				flag:true,
				preferential_options:'coupon',//优惠选择
				totalPrice:'',//总价
				discountPrice:'', //优惠价格
				discountNum:0, //优惠价格数字
				isLoading:false,
				score_rule: 1, //多少积分抵扣
				checkedYes:true,
			}
		},
		onShow() {
			// 获取信息
			this.getOrderInfo();
		},
		methods: {
			// 选择地址
			toAddress(){
				uni.navigateTo({
					url:`/pagesA/address/address?type=change`
				})
			},
			
			// 计算价格
			computePrice(){
				// 原需支付
				let totalNum = this.orderInfo.total_price;
				totalNum = parseFloat(this.$toolAll.tools.addXiaoShu(totalNum));
				let totalPrice  = this.$toolAll.tools.addXiaoShu(totalNum);
				// 会员折扣
				let vipNum = this.orderInfo.vip_level>0?this.orderInfo.total_price*(1 - this.$toolAll.tools.addXiaoShu(this.orderInfo.membership_discount)/10):0;
				vipNum = parseFloat(this.$toolAll.tools.addXiaoShu(vipNum));
				let vipPrice = this.$toolAll.tools.addXiaoShu(vipNum);
				// 优惠券折扣
				let couponNum = this.couponList.length>0?this.couponList[this.couponIndex].amount:0;
				couponNum = parseFloat(this.$toolAll.tools.addXiaoShu(couponNum));
				let couponPrice = this.$toolAll.tools.addXiaoShu(couponNum);
				// 积分可抵扣额度
				let scoreNum = this.orderInfo.available_score*this.score_rule;
				scoreNum = parseInt(this.$toolAll.tools.addXiaoShu(scoreNum));
				let scorePrice = this.$toolAll.tools.addXiaoShu(scoreNum);
				
				// 只有会员则扣
				if(this.vipCheck && !this.scoreCheck){
					this.discountNum = vipNum;
					this.discountPrice = vipPrice;
				}
				// 只有优惠券
				if(this.couponCheck && !this.scoreCheck){
					this.discountNum = couponNum;
					this.discountPrice = couponPrice;
				}
				// 只有积分
				if(!this.vipCheck && !this.couponCheck && this.scoreCheck){
					if(scoreNum >= totalNum){
						this.discountNum = totalNum;
						this.discountPrice = totalPrice;
					}else{
						this.discountNum = scoreNum;
						this.discountPrice = scorePrice;
					}
				}
				// 会员折扣+积分
				if(this.vipCheck && this.scoreCheck){
					if(scoreNum + vipNum >= totalNum){
						this.discountNum = totalNum;
						this.discountPrice = totalPrice;
					}else{
						this.discountNum = scoreNum + vipNum;
						this.discountPrice = this.$toolAll.tools.addXiaoShu(scoreNum + vipNum);
					}
				}
				// 优惠券+积分
				if(this.couponCheck && this.scoreCheck){
					if(scoreNum + couponNum >= totalNum){
						this.discountNum = totalNum;
						this.discountPrice = totalPrice;
					}else{
						this.discountNum = scoreNum + couponNum;
						this.discountPrice = this.$toolAll.tools.addXiaoShu(scoreNum + couponNum);
					}
				}
				// 都不选择
				if(!this.vipCheck && !this.couponCheck && !this.scoreCheck){
					this.discountNum = 0;
					this.discountPrice = 0;
				}
				// 计算支付价格
				this.totalPrice = this.$toolAll.tools.addXiaoShu(totalNum - this.discountNum);
			},
			
			// 获取订单准备信息
			getOrderInfo(){
				uni.showLoading({
					title:'加载中'
				})
				let params = {
					sku_list: uni.getStorageSync('buyList'),
				}
				this.$requst.post('/api/order/prepare-info',params).then(res=>{
					if(res.code == 0){
						console.log(res,'订单准备信息');
						// 其他信息
						this.orderInfo = res.data;
						
						// 优惠券信息
						let baseArr = res.data.available_coupon_list;
						let couponArr = baseArr.sort(function (a, b) {
						  return b.amount - a.amount;
						});
						this.couponList = couponArr;
						if(this.couponList.length==0){
							this.couponCheck = false;
						}
						
						// 商品信息
						this.orderShopList = res.data.list;
						
						// 积分抵扣规则
						let score_num = res.data.integral_rule.deduction_points_score;
						let score_value = res.data.integral_rule.deduction_points_score_value;
						this.score_rule = parseFloat(score_value)/parseFloat(score_num);
						
						// 积分是否可选
						let scoreA = this.orderInfo.available_score*this.score_rule;
						let scoreB = parseFloat(this.$toolAll.tools.addXiaoShu(scoreA));
						if(scoreB<1){
							this.checkedYes = false;
						}
						
						// 地址信息
						let addr_id = uni.getStorageSync('addr_id');
						if(addr_id){
							// 获取地址
							this.getAddrDetail(addr_id);
						}else{
							this.default_address = res.data.default_address;
						}
						
						// 价格
						this.discountPrice = 0;
						this.totalPrice = this.$toolAll.tools.addXiaoShu(this.orderInfo.total_price);
						
						// 计算价格
						if(this.vipCheck||this.couponCheck||this.scoreCheck){
							// 计算价格
							this.computePrice();
						}
					}
					uni.hideLoading();
					this.isLoading = true;
				})
			},
			
			// 获取地址
			getAddrDetail(id){
				this.$requst.post('/api/user/address-info',{id:id}).then(res=>{
					if(res.code == 0){
						console.log(res,'地址详情');
						this.default_address = res.data;
					}
				})
			},
			
			// 打开优惠券弹窗
			toCoupon(){
				if(this.couponList.length){
					this.isCoupon =true;
				}else{
					this.$toolAll.tools.showToast('暂无可用的优惠券');
				}
			},
			
			// 选择优惠券
			changeCoupon(index){
				if(index!==this.couponIndex){
					this.couponIndex = index;
				}
			},
			
			//确认选择
			useCoupon(){
				this.isCoupon = false;
				this.vipCheck = false;
				this.couponCheck = true;
				// 计算价格
				this.computePrice();
			},
			
			//取消选择
			closeCoupon(){
				this.isCoupon = false;
				this.couponIndex = 0;
			},
			
			// 选择按钮
			chooseEv(type){
				if(type == 'vip' && this.orderInfo.vip_level>0){
					if(this.vipCheck){
						this.vipCheck = false;
					}else{
						this.vipCheck = true;
						this.couponCheck = false;
					}
					this.computePrice();
				}
				if(type == 'coupon' && this.couponList.length){
					if(this.couponCheck){
						this.couponCheck = false;
					}else{
						this.couponCheck = true;
						this.vipCheck = false;
					}
					this.computePrice();
				}
				if(type == 'score' && this.orderInfo.available_score>0){
					if(this.checkedYes){
						if(this.scoreCheck){
							this.scoreCheck = false;
						}else{
							this.scoreCheck = true;
						}
						this.computePrice();
					}else{
						this.$toolAll.tools.showToast('当前积分无法抵扣');
					}
				}
			},
			
			// 提交
			submitEv(){
				this.flag = false;
				if(this.vipCheck){
					this.preferential_options = 'membership_discount';
				}
				if(this.couponCheck){
					this.preferential_options = 'coupon';
				}
				if(!this.couponCheck && !this.vipCheck){
					this.preferential_options = '';
				}
				if(this.default_address == null) {
					this.$toolAll.tools.showToast('请填写地址信息');
				}else{
					if(this.wechatCheck || this.priceCheck){
						let params = {
							sku_list: uni.getStorageSync('buyList'),
							preferential_options:this.preferential_options,
							coupon_id: this.couponCheck?this.couponList[this.couponIndex].id:'',
							deduction_points:this.scoreCheck?1:0,
							is_balance:this.priceCheck?1:0,
							is_wechat:this.wechatCheck?1:0,
							address_id:this.default_address.id
						}
						this.$requst.post('/api/order/create',params).then(res=>{
							if(res.code==0) {
								console.log(res,'支付返回')
								if(res.data.need_wechat_pay == 1){
									// 调用微信支付
									this.callPayMent(res.data.payment_params,res.data.id,res.data.coding);
								}else{
									// 成功状态
									this.successEv(res.data.coding);
									// 清除缓存
									uni.removeStorageSync('addr_id');
									// 页面跳转
									uni.navigateTo({
										url:`/pages/cart/finish?id=${res.data.id}`
									})
								}
							}else{
								console.log(res.msg,'提示信息')
								this.$toolAll.tools.showToast(res.msg);
								this.flag = true;
							}
						})
					}else{
						this.$toolAll.tools.showToast('请选择支付方式');
					}
				}
			},
			
			// 调用微信支付
			callPayMent(data,id,coding){
				//调起支付
				wx.requestPayment({ 
					'timeStamp': data.timeStamp,
					'nonceStr': data.nonceStr,
					'package': data.package,
					"signType": data.signType,
					'paySign': data.sign,
					'success': (res)=> { // 接口调用成功的回调函数
						console.log('支付成功:',res);
						// 成功状态
						this.successEv(coding);
						// 清除缓存
						uni.removeStorageSync('addr_id');
						// 页面跳转
						uni.navigateTo({
							url:`/pages/cart/finish?id=${id}`
						})
					},
					'fail': (res)=> { // 接口调用失败的回调函数
						this.$toolAll.tools.showToast('您已取消支付');
						setTimeout(()=>{
							// 页面跳转
							uni.navigateTo({
								url:`/pagesA/order/order?index=1&backTag=backmy`
							})
						},1000)
					}
				  })
			},
			
			// 成功状态
			successEv(coding){
				this.$requst.post('/api/order/paid',{order_coding:coding}).then(res=>{
					if(res.code==0) {
						console.log(res,'成功状态')
					}else{
						this.$toolAll.tools.showToast(res.msg);
					}
				})
			}
		}
	}
</script>

<style>
	
</style>
