<template>
	<view class="container order clearfix" :style="{paddingBottom :isIphoneX ? '170rpx' : '134rpx'}">
		<!-- 地址选择 v-if="isAddress" -->
		<choice-address ref="choiceAddress" :addressData="addressData"></choice-address>
		<!-- 商品 -->
		<goodsList ref='goods' v-if="isRequest" :goodsData="goodsData" @handleGoodList="handChangeInputGoodsList"></goodsList>
		<!-- 运费 -->
		<seller-freight ref="freight" 
						v-if="isRequest" 
						:freightDatas="freightData">
		</seller-freight>
		<!-- 底部 -->
		<view class="footer" :style="{paddingBottom :isIphoneX ? '68rpx' : '0rpx'}">
			<view class="footer-le">
				<view class="footer-count">
					<text>共{{allCount}}件商品</text>
				</view>
				<view class="footer-price">
					<view class="sum" :class="totalFullReduction == 0 ? 'none' : ''">总价:<text class="price">￥{{payAllPrice | NumFormat}}</text></view>
				</view>
			</view>
			<view class="footer-submit" @click.stop="orderSubmitMit">
				<view class="btn" :class="isSubLoading ? 'disabled' : ''">提交订单</view>
			</view>
		</view>
	</view>
</template>

<script> 
	import authorize from '@/common/config/authorize.js'
	import choiceAddress from '@/components/cm-module/creatOrder/address'  
	import goodsList from '@/components/cm-module/creatOrder/goodsList'
	import sellerFreight from '@/components/cm-module/creatOrder/sellerFreight'
	export default {
		components:{
			choiceAddress,
			goodsList,
			sellerFreight
		},
		data() {
			return {
				isSubLoading:false,
				productIds:'',			  //获取上一级页面商品信息
				productCount:'',		  //获取上一级页面商品数量
				allCount:1,				  //订单提交总数量
				totalOriginalPrice:0,	  //订单总原价(划线部分)
				totalFullReduction:0,	  //满减金额
				payAllPrice:0.00,		  //订单提交总金额
				allPrice:0.00,			  //订单总金额
				townId:'',				  //区ID
				isRequest:false,		  //是否加载完成渲染子组件
				isFreight:false,		  //是否加载完成渲染子组件
				isAddress:false,		  //是否加载完成地址
				ischecked:false,	      //是否勾选余额
				addressData:{},//初始化地址信息
				goodsData:[],//初始化商品信息
				freightData:{},			  //邮费数据
				isIphoneX:this.$store.state.isIphoneX,
				productsList:[],
				params:{
					userId:0
				},
				subParams:{
					userId:0,
					orderInfo:[],//提交的商品信息
					addressId:0,
					cartType:0,
					payInfo:{
						orderShouldPayFee:0
					}
				},
				orderInfo:''
			}
		},
		onLoad(option){//商品数据
			let data = JSON.parse(option.data);
			this.allCount = data.data.allCount;
			console.log(data);
			if(option.type =='prodcut'){
				this.subParams.cartType = 2
				this.params.productCount = data.data.productCount
				this.params.productId = data.data.productId
				this.params.heUserId = data.data.heUserId ? data.data.heUserId : 0
			}else{
				this.subParams.cartType = 1 
				this.params.cartIds = data.data.cartIds
			}
			this.$api.getStorage().then((resolve) =>{
				this.params.userId = this.subParams.userId =  resolve.userId ? resolve.userId : 0
				this.getInitCrearOrder(this.params);
			})
		},
		filters:{
			NumFormat(value) {//处理金额
				return Number(value).toFixed(2);
			},
		},
		methods: {
			getInitCrearOrder(params){//确认订单初始化信息 
				this.OrderService.QueryOrderConfirm(params)
					.then(response =>{
						let data = response.data
						let productIds = []
						this.isRequest = true
						this.goodsData = data.shopList
						console.log(this.goodsData);
						// this.totalFullReduction = data.totalFullReduction
						// this.totalOriginalPrice = data.totalFullReduction + data.totalPrice
						this.allPrice = this.payAllPrice = data.totalPrice
						this.subParams.payInfo.orderShouldPayFee = this.payAllPrice.toFixed(2)
						console.log('this.subParams.payInfo.orderShouldPayFee',this.subParams.payInfo.orderShouldPayFee)
					})
					.catch(error =>{
						this.$util.msg(error.msg,2000)
					})
			},
			getAddressData(){//获取地址信息
				this.$api.getStorage().then((resolve) => {
					this.UserService.QueryAddressList({pageNum:1,pageSize:1,userId:resolve.userId})
					.then(response =>{
						this.isAddress = true
						this.addressData = {}
						if(response.data.list != ''){
							this.subParams.addressId = response.data.list[0].addressId;
							this.townId = response.data.list[0].townId;
							this.addressData = response.data.list[0];
						}else{
							this.addressData = this.addressData;
						}
					})
				})
			},
			handChangeInputGoodsList(data){//对应供应商的留言信息
				this.goodsData = data;
			},
			orderSubmitMit(){//提交订单
				if(this.isSubLoading){ return; }
				if(this.subParams.addressId == ''){
					this.$util.msg('请先添加收货地址～',2000)
					return
				}
				// 处理商品信息及留言
				this.subParams.orderInfo = this.goodsData.map(el => {
					let productInfo = [];
					el.productList.forEach(pros => {
						productInfo.push({
							productId:pros.productId,
							productNum:pros.productCount,
							heUserId:pros.heUserId
						})
					})				
					return {shopId:el.shopId, note:el.note ? el.note:'' , productInfo:productInfo}
				})
				console.log(this.subParams)
				this.isSubLoading = true;	
				this.OrderService.CreatedOrderSubmit(this.subParams).then(response =>{
					const data = response.data;
					this.orderInfo = response.data;
					setTimeout(()=>{
						this.isSubLoading = false;
					},2000)
					this.MiniWxPayFor(data)
				}).catch(error =>{
					this.$util.msg(error.msg,2000);
				})
			},
			MiniWxPayFor(data){
				this.PayService.PayOrderOnLineSwitch().then(response =>{
					if(response.data === 1 ){
						this.WeChatMiniWxPay(data)
					}else{
						this.$api.navigateTo(`/pages/user/order/order-payment?money=${data.payableAmount}`)
					}
				})
			},
			async WeChatMiniWxPay(data){
				const wechatCode = await authorize.getCode('weixin')
				this.PayService.WeChatMiniWxPay(
					{
						payAmount:data.payableAmount*100,
						payWay:"WEIXIN",
						code:wechatCode,
						orderId:data.orderId
					}
				)
				.then(response =>{
					let PayInfo = JSON.parse(response.data.data.payInfo);
					this.WxRequestPayment(PayInfo)
				})
				.catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			WxRequestPayment(data){
				let self = this
				wx.requestPayment(
					{
						'timeStamp': data.timeStamp,
						'nonceStr': data.nonceStr,
						'package': data.package,
						'signType': data.signType,
						'paySign': data.paySign,
						'success':function(res){
							wx.reLaunch({url: '/pages/tabBar/index/index'});
						},
						'fail':function(res){
							console.log(res)
							console.log('ORDERID',self.orderInfo)
							self.$api.redirectTo(`/pages/user/order/success?data=${JSON.stringify({data:self.orderInfo})}`)
						},
						'complete':function(res){
			
						}
					}
				)
			},
		},
		onShow() {
			let pages = getCurrentPages();
			let currPage = pages[pages.length-1];
			if(currPage.data.select =='select'){
				this.isAddress = true
				let SelectData = uni.getStorageSync('selectAddress');
				this.subParams.addressId = SelectData.addressId;
				this.addressData = SelectData
			}else{
				this.getAddressData()
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: auto;
		background:#F7F7F7;
	}
	.btn-hover{
		background: #FFFFFF;
	}
	.animation{
		/* transition: transform 0.3s ease;*/
		transition-property: transform;
		transition-duration: 0.3s;
		transition-timing-function: ease;
	}
	.invoice-freight{
		width: 702rpx;
		padding: 0 24rpx;
		height: 86rpx;
		line-height: 86rpx;
		font-size: $font-size-28;
		color: $text-color;
		background: #FFFFFF;
		float: left;
		font-weight: bold;
		.freight-left{
			float: left;
			.icon-yunfeishuoming{
				height: 100%;
				padding: 0 15rpx;
				color: $color-system;
				font-weight: normal;
			}
		}
		.freight-right{
			float: right;
			color: #2A81FF;
		}
	}
	.invoice-balance{
		width: 702rpx;
		height: auto;
		padding:0 24rpx;
		background: #FFFFFF;
		float: left;
		margin-top: 24rpx;
		margin-bottom: 24rpx;
		.balabce-t{
			width: 100%;
			height: 86rpx;
			line-height: 86rpx;
			font-size: $font-size-28;
			color: $text-color;
			float: left;
			.balabce-t-le{
				float: left;
				font-weight: bold;
			}
			.balabce-t-ri{
				float: right;
				display: flex;
				align-items: center;
				.money{
					display: flex;
					float: left;
				}
				.checkbox-box{
					display: flex;
					width: 60rpx;
					float: left;
					height: 100%;
					font-size: $font-size-24;
					.checkbox{
						width: 40rpx;
						text-align: right;
						box-sizing: border-box;
						text-align: center;
						text-decoration: none;
						border-radius: 0;
						-webkit-tap-highlight-color: transparent;
						overflow: hidden;
						color: $color-system;
						padding: 5rpx;
					}
				}	
			}
		}
		.balabce-b{
			width: 100%;	
			float: left;
			overflow: hidden;
			.balabce-b-text{
				width: 100%;
				line-height: 58rpx;
				font-size: $font-size-24;
				color: #FF2A2A;
				text-align: right;
				float: right;
			}
			&.balabce-b--hide {
				padding: 0 0;
				height: 0px;
				line-height: 0px;
			}	
		}
	}
	.footer{
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 995;
		display: flex;
		align-items: center;
		width: 100%;
		height: 110rpx;
		line-height: 110rpx;
		justify-content: space-between;
		font-size: $font-size-28;
		background-color: #FFFFFF;
		z-index: 998;
		color: $text-color;
		.footer-le{
			width:570rpx;
			height:100%;
			float: left;
		}
		.footer-count{
			float: left;
			padding-left: 24rpx;
			width:170rpx;
			box-sizing: border-box;
			font-size: $font-size-26;
		}
		.footer-price{
			float: right;
			text-align: right;
			color: $text-color;
			padding-right:20rpx;
			box-sizing: border-box;
			width: 370rpx;
			.sum{
				width: 100%;
				height: 110rpx;
				line-height: 110rpx;
				float: left;
				.price{
					font-size: $font-size-32;
					color: $color-system;
				}
			}
			
		}
		.footer-submit{
			display:flex;
			align-items:center;
			justify-content: center;
			width: 210rpx;
			height: 100%;
			box-sizing: border-box;
			padding: 15rpx 5rpx;
			.btn{
				width: 100%;
				height: 100%;
				color: #FFFFFF;
				background:$btn-confirm;
				font-size: $font-size-26;
				text-align: center;
				line-height: 80rpx;
				border-radius: 40rpx;
				&.disabled{
					background: #e4e8eb;
					color: #999999;
				}
			}
		}
	}
	.Rebate{
		width: 702rpx;
		height: auto;
		padding: 0 24rpx;
		background: #FFFFFF;
		float: left;
		margin-bottom: 24rpx;
		margin-bottom: 24rpx;
		line-height: 86rpx;
		.rebate-title{
			float: left;
			font-weight: bold;
			color: #333333;
			font-size: $font-size-28;
		}
		.iconfont{
			float: right;
			color: #b2b2b2;
			font-size: 40rpx;
			&.icon-yixuanze{
				color: $color-system;
			}
		}
	}
	
</style>
