<template>
	<view class="container order clearfix" :style="{paddingBottom :isIphoneX ? '170rpx' : '134rpx'}">
		<!-- 透明模态层 -->
		<modal-layer v-if='modallayer'></modal-layer>
		<!-- 地址选择 -->
		<choice-address ref="choiceAddress" v-if="isAddress" :addressData="addressData"></choice-address>
		<!-- 商品 -->
		<goods-list ref='goods' v-if="isRequest" :goodsData="goodsData" @handleGoodList="handChangeInputGoodsList"></goods-list>
		<!-- 发票信息 -->
		<invoice-tent ref="invoice"
					  v-if="isRequest"
					  :invoiceDatas="invoiceData"
					  @handleChoiceaInvoice="handleChoiceaInvoiceData">
		</invoice-tent>
		<!-- 运费 -->
		<freight ref="freight"
				 v-if="isFreight"
				 :freightData="freightData"
				 @confirmFreight="hanldFreightFn">
		</freight>
		<freight-alert v-if="isfreightTip" ref="csPhone"></freight-alert>
		<!-- 余额抵扣 -->
		<view class="invoice-balance" v-show="!rechargeGoods">
			<view class="balabce-t">
				<view class="balabce-t-le">余额抵扣</view>
				<view class="balabce-t-ri">
					<view class="money">
						<text>可用余额：</text>
						<text>￥{{userMoney | NumFormat}}</text>
					</view>
					<view class="checkbox-box">
						<button class="checkbox iconfont"
								hover-class="btn-hover"
								v-if="userMoney!=0"
								@click.stop="checkedBalabce"
								:class="[ischecked ?'icon-gouxuanl':'icon-weigouxuan']"
						>
						</button>
					</view>
				</view>
			</view>
			<view class="balabce-b" :class="{'balabce-b--hide':!ischecked}">
				<view class="balabce-b-text animation" :style="{'transform':ischecked?'translateY(0)':'translateY(-50%)','-webkit-transform':ischecked?'translateY(0)':'translateY(-50%)'}">
					<text>当前使用：￥{{deductMoney | NumFormat}}，剩余：￥{{surplusMoney | NumFormat}}</text>
				</view>
			</view>
		</view>
		<!-- 底部 -->
		<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-none" v-if="reducedPrice>0">
						<text class="money-sign">￥</text>
						<text class="money">{{ totalOriginalPrice | NumFormat }}</text>
						<text class="money-reduced">减<text>￥{{ reducedPrice | NumFormat}}</text></text>
					</view>
					<view class="sum" :class="reducedPrice == 0 ? 'none' : ''">总价:<text class="price">￥{{payAllPrice | NumFormat}}</text></view>
				</view>
			</view>
			<view class="footer-submit" @click.stop="orderSubmitMit">提交订单</view>
		</view>
	</view>
</template>

<script>
	import choiceAddress from '@/components/cm-module/creatOrder/choiceAddress'
	import goodsList from '@/components/cm-module/creatOrder/goodsList'
	import invoiceTent from '@/components/cm-module/creatOrder/invoiceTent'
	import freight from '@/components/cm-module/creatOrder/freight'
	import freightAlert from '@/components/cm-module/modelAlert/freightAlert'
	import modalLayer from "@/components/modal-layer"

	export default {
		components:{
			choiceAddress,
			goodsList,
			invoiceTent,
			freight,
			freightAlert,
			modalLayer
		},
		data() {
			return {
				modallayer:false,
				orderID:0,
				productIds:'',			  //获取上一级页面商品信息
				productCount:'',		  //获取上一级页面商品数量
				classifyIDS:'',			  //获取上一级页面商品分类
				userID:'',				  //用户ID
				cartType:'',			  //购买类型（1购物车提交，2直接购买提交）
				submitState:'',  		  //提交状态
				balanceDeductionFlag:2,   //勾选余额的状态(1使用，2不使用)
				allCount:1,				  //订单提交总数量
				totalOriginalPrice:0,	  //订单总原价(划线部分)
				reducedPrice:0,			  //满减金额
				payAllPrice:0.00,		  //订单提交总金额
				allPrice:0.00,			  //订单总金额
				surplusMoney:0.00,		  //显示勾选后的剩余抵扣
				userMoney:0.00,			  //显示可使用余额
				deductMoney:0.00,		  //显示已使用的余额
				addressID:'',			  //地址ID
				townID:'',				  //区ID
				isRequest:false,		  //是否加载完成渲染子组件
				isFreight:false,		  //是否加载完成渲染子组件
				isAddress:false,		  //是否加载完成地址
				isfreightTip:false,		  //控制邮费弹窗
				ischecked:false,	      //是否勾选余额
				hanldFreePostFlag:'',	  //邮费状态
				hanldFreight:'',		  //邮费
				addressData:{},			  //初始化地址信息
				goodsData:[],			  //初始化商品信息
				invoiceData:{type:0},	  //初始化发票信息
				freightData:{},			  //邮费数据
				orderInfo:[],			  //提交的商品信息
				payInfo:{},				  //订单信息
				rechargeGoods:null,		  //判断订单里有定金商品或者充值商品时，余额抵扣部分不显示
				isIphoneX:this.$store.state.isIphoneX
			}
		},
		onLoad(option){//商品数据
			let data = JSON.parse(option.data);
			if(option.type =='prodcut'){
				this.cartType = 2
				this.productCount = data.data.productCount
				this.productIds = data.data.productID
			}else{
				this.cartType = 1
				this.productCount = data.data.productCount
				this.productIds = data.data.productID
			}
			this.$api.getStorage().then((resolve) =>{
				this.userID = resolve.userID
				this.getInitCrearOrder(option);
			})
		},
		filters:{
			NumFormat(value) {//处理金额
				return Number(value).toFixed(2);
			},
		},	
		methods: {
			getInitCrearOrder(option){//获取订单商品信息
				let params ={userId:this.userID,count:this.productCount,productIds:this.productIds}
				this.OrderService.CreateOrderInfo(params).then(response =>{
					let resData = response.data
					this.isRequest = true
					this.goodsData = resData.list
					this.userMoney = resData.userMoney
					this.reducedPrice = resData.reducedPrice
					this.allPrice = this.payAllPrice = resData.totalPrice
					this.totalOriginalPrice = resData.totalOriginalPrice
					this.rechargeGoods = resData.rechargeGoods
				}).catch(error =>{
					this.$util.msg(error.msg,2000)
				})
			},
			getFreightData(){//获取邮费信息
				let params ={
						userId:this.userID,
						productIds:this.productIds,
						totalPrice:this.allPrice,
						townId:this.addressData.townID
					}
				this.OrderService.GetOrderPostage(params).then(response =>{
					this.isFreight = true
					this.freightData = response.data
					this.hanldFreePostFlag = response.data.freePostFlag
					this.hanldFreight = response.data.freight
					if(this.hanldFreePostFlag == 1){
						this.payAllPrice = this.allPrice + response.data.freight
						this.attributePallPrice()
					}else{
						this.payAllPrice = this.allPrice
						this.attributePallPrice()
					}
				})
			},
			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.results != ''){
							this.addressID = response.data.results[0].addressID;
							this.townID = response.data.results[0].townID;
							this.addressData = response.data.results[0];
							this.getFreightData()
						}else{
							this.addressData = this.addressData;
						}
					})
				})
			},
			handChangeInputGoodsList(data){//对应供应商的留言信息
				this.goodsData = data;
			},
			handleChoiceaInvoiceData(data){//获取发票信息
				this.invoiceData = data
			},
			hanldFreightFn(data){//显示邮费弹窗
				switch(data){
					case 1:
						this.hanldFreight = this.freightData.freight
						this.hanldFreePostFlag = data
						this.payAllPrice =this.allPrice + this.hanldFreight
						this.attributePallPrice()
						break
					case -1:
						this.hanldFreight = 0
						this.hanldFreePostFlag = data
						this.payAllPrice = this.allPrice
						this.attributePallPrice()
						break
				}
			},
			checkedBalabce(){//勾选使用余额
				if(this.userMoney > 0){
					this.ischecked = !this.ischecked
					if(this.ischecked){
						this.balanceDeductionFlag =1
						this.attributePallPrice()
					}else{
						if(this.hanldFreePostFlag == 1 || this.hanldFreePostFlag == '1'){
							this.payAllPrice = this.allPrice+parseInt(this.freightData.freight)
						}else{
							this.payAllPrice = this.allPrice
						}
						this.balanceDeductionFlag = 2
					}
				}else{
					return
				}
			},
			attributePallPrice(){//计算价格
				if(this.hanldFreePostFlag == 1 || this.hanldFreePostFlag == '1'){
					this.attributeHashfreight(this.freightData.freight)
				}else{
					this.attributeNofreight()
				}
			},
			attributeNofreight(){//计算没有邮费的支付价格
				if(this.ischecked){
					if(this.userMoney>this.payAllPrice){
						this.payAllPrice = 0.00
						this.deductMoney = this.allPrice							//勾选后使用抵余额
						this.surplusMoney = this.userMoney - this.deductMoney	    //勾选后的剩余抵扣
					}else{
						this.payAllPrice = this.allPrice - this.userMoney       	//勾选后的总价
						this.deductMoney = this.userMoney				            //勾选后使用抵余额
						this.surplusMoney = this.userMoney - this.deductMoney	    //勾选后的剩余抵扣
					}
				}else{
					this.payAllPrice = this.allPrice;
					this.deductMoney = 0.00;
					this.surplusMoney = this.userMoney;
				}
			},
			attributeHashfreight(freight){//计算需要邮费的支付价格
				this.payAllPrice = this.allPrice+parseInt(freight)//计算不包邮的价格 总价等于商品价格+邮费
				if(this.ischecked){
					if(this.userMoney>this.payAllPrice){							//余额大于支付金额
						this.payAllPrice =0.00
						this.deductMoney = this.allPrice+parseInt(freight)			//勾选后使用抵余额
						this.surplusMoney = this.userMoney - this.deductMoney	    //勾选后的剩余抵扣
					}else{
						this.payAllPrice = this.allPrice+parseInt(freight) - this.userMoney       	//勾选后的总价
						this.deductMoney = this.userMoney				            //勾选后使用抵余额
						this.surplusMoney = this.userMoney - this.deductMoney	    //勾选后的剩余抵扣
					}
				}else{
					this.payAllPrice = this.allPrice+parseInt(freight)
					this.deductMoney = 0.00
					this.surplusMoney = this.userMoney
				}
			},
			orderSubmitMit(){//提交订单
				if(this.addressID == ''){
					this.$util.msg('请先添加收货地址～',2000)
					return
				}
				this.orderInfo = this.goodsData.map(el => {
					let productInfo = [];
					el.cartList.forEach(item => {
						productInfo.push({
							productId:item.productId,
							productNum:item.number,
							presentNum:0,
							productType:item.productType
						})
					})
					return {shopId:el.id,note:el.note?el.note:'',productInfo:productInfo}
				})
				//订单信息
				this.payInfo = {
						clauseId:0,//条款（暂时保留）
						orderShouldPayFee:this.payAllPrice.toFixed(2),//提交的总价
						balancePayFlag:this.balanceDeductionFlag,//余额抵扣的状态
						freight:parseInt(this.hanldFreight).toFixed(2),//邮费
						freePostFlag:parseInt(this.hanldFreePostFlag)//运费形式
					}
				let param = {
						orderSource:6,
						clubUserId:this.userID,
						cartType:this.cartType,
						addressId:this.addressID,
						orderInfo:this.orderInfo,
						payInfo:this.payInfo,	//订单信息
						orderInvoice:this.invoiceData
					}
					// console.log(param)
				this.modalLayer = true;
				this.OrderService.CreatedOrderSubmit({'params':JSON.stringify(param)}).then(response =>{
					const data = response.data;
					if(data.code === '1'){
						this.submitState ='success'
						let data = {orderID:response.data.orderID}
						this.$api.navigateTo(`/pages/user/order/success?data=${JSON.stringify({data:data})}`)
					}else{
						this.submitState ='confirm'
						this.$util.msg('订单提交成功',3000,true,'success')
						setTimeout(()=>{
							this.$api.redirectTo(`/pages/user/order/order-payment?type=${this.submitState}&orderID=${response.data.orderID}`)
						},3000)
					}
				}).catch(error =>{
					this.$util.msg(error.msg,3000);
				})
			},
			handFreightAlertShow(){//显示邮费弹窗
				this.isfreightTip = true;
			},
			hideFreight(){//关闭邮费弹窗
				this.isfreightTip = false;
			},
		},
		onShow() {
			// this.addressID = ''
			let pages = getCurrentPages();
			let currPage = pages[pages.length-1];
			if(currPage.data.select =='select'){
				this.isAddress = true
				let SelectData = uni.getStorageSync('selectAddress');
				this.addressID = SelectData.addressID;
				this.addressData = SelectData
				this.getFreightData()
			}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;
	}
	.order{
		padding-bottom: 134rpx;
	}
	.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;
					}
				}
			}
		}
		.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:180rpx;
			box-sizing: border-box;
		}
		.footer-price{
			width:370rpx;
			float: right;
			text-align: right;
			color: $text-color;
			padding: 10rpx 20rpx 10rpx 0;
			box-sizing: border-box;
			.sum-none{
				width: 100%;
				height: 45rpx;
				line-height: 45rpx;
				color: $text-color;
				float: left;
				text-align: right;
				.money{
					font-size: $font-size-26;
					color: #999999;
					text-decoration: line-through;
				}
				.money-sign{
					font-size: $font-size-26;
					color: #999999;
					text-decoration: line-through;
				}
				.money-reduced{
					margin-left: 10rpx;
					font-size: $font-size-26;
					color:$color-system;
				}
			}
			.sum{
				width: 100%;
				height: 45rpx;
				line-height: 45rpx;
				float: left;
				&.none{
					height: 90rpx;
					line-height: 90rpx;
				}
				.price{
					font-size: $font-size-32;
					color: #FF2A2A;
				}
			}
			
		}
		.footer-submit{
			display:flex;
			align-items:center;
			justify-content: center;
			width: 180rpx;
			height: 100%;
			color: #FFFFFF;
			background:linear-gradient(135deg,rgba(242,143,49,1) 0%,rgba(225,86,22,1) 100%);
		}
	}

</style>
