<template>
	<view class="pd-main backcor9 settleAccounts">
		<!-- 地址 -->
		<view class="select-address backcolorfff paading10  border-8r  border-bt mart10 " @click="goAddress">
			<view v-if="haveAddress" class="address-left flex-1 font16">
				<view class="text-ov ">
					{{addressDetail.regionName+" "+addressDetail.address}}
				</view>
				<view class="color999 mart3">
					<text class="address-name">{{addressDetail.consignee}}</text>
					<text class="address-phone margle10">{{addressDetail.phone}}</text>
				</view>
			</view>
			<view v-else class="address-left flex-1 font16">
				<view class="color999 ">
					请选择地址
				</view>
			</view>
			<view class="icon-ymt to-right font14"></view>
		</view>

		<!-- 选购的商品信息 -->
		<view class=" backcolorfff paading10  border-8r  border-bt mart10 ">
			<!-- 及时达 -->
			<!-- <view class="container-price select-address">
				<view class="beizhu font16 ">
					即时达:
				</view>
				<view class="beizhu font16 ">
					<text class="fcorred">尽快送达,预计11:58送达</text><text class="icon-ymt to-right font14"></text>
				</view>
			</view> -->


			<!-- 当有多个商品时 -->
			<view class="po-ra" v-if="isMoreThanOne" @click="showPopup('goods')">
				<view class="po-ra">
					<scroll-view class="settle-goods" scroll-x="true">
						<view class="settle-con">
							<view class="settle-img" v-for="(item,index) in goodsList" :key="index">
								<image class="st-img" v-if="item.img" :src="imageUrl+item.img" mode="aspectFill">
								</image>
							</view>

						</view>

					</scroll-view>
					<view class="fix-soon fcor666">
						共{{getNumberAll}}件<text class="icon-ymt to-right font14 fcor666"></text>
					</view>
				</view>
			</view>


			<!-- 当只有一个商品时 -->
			<view v-if="!isMoreThanOne">

				<view class="settle-con">
					<view class="settle-img">
						<image class="st-img" v-if="goodsList[0].img" :src="imageUrl+goodsList[0].img"
							mode="aspectFill"></image>
					</view>
					<view class="settle-msg">
						<view class="settle-title marb5">
							<text class="flex-1">{{goodsList[0].title}}</text>
							<view class="font14 fcor666">共{{getNumberAll}}件</view>
						</view>
						<view v-if="yhqId == 0" class="settle-title">
							<text >¥{{goodsList[0].price}}</text>
							<text class="font14 fcor666">×{{goodsList[0].num}}</text>
						</view>
						<view v-else class="settle-title">
							<text>¥{{goodsList[0].originalPrice}}</text>
							<text class="font14 fcor666">×{{goodsList[0].num}}</text>
						</view>
						
					</view>

				</view>


			</view>

		</view>


		<!-- 金额费用 -->
		<view class=" backcolorfff paading10  border-8r  border-bt mart10 ">
			<!-- 商品金额 -->
			<view class="container-price select-address border-bt">
				<view class="address-left ">
					商品金额
				</view>
				<view class="to-right fontwig6 dis-flex">
					<view class="" v-if="yhqId == 0">
						¥{{priceAll}}
					</view>
					<view :class="'margle10'+(yhqId == 0?' text-lt fcor666 ':'  ')">
						¥{{priceOrigin}}
					</view>
				</view>
			</view>
			<!-- 运费 -->
			<view class="container-price select-address border-bt">
				<view class="address-left ">
					运费<text class="icon-ymt question font16 paddleft5 fcor666" @click="showPopup('freight')"></text>
				</view>
				<view class="to-right fontwig6">
					¥{{postPriceAll}}
				</view>
			</view>
			<!-- 优惠券 -->
			<view class="container-price select-address border-bt" @click="showPopup('coupon')">
				<view class="address-left  ">
					<text> 优惠券</text>
					<view :class="' mart3 font14 '+(yhqUse>0?' fcorred ':' fcor666 ') ">
						{{yhqUse}}张优惠券可用
					</view>
				</view>
				<view class="dis-flex font14">
					<view class=" fcorred">
						- ¥ {{yhqPrice}}
					</view>
					<view class="icon-ymt to-right "></view>
				</view>



			</view>
			<!-- 积分抵现 -->
			<view class="container-price select-address border-bt" v-if="isShowjf">
				<view class="address-left ">
					<text @click="showPopup('integral')">积分抵现
						<text class="icon-ymt question font16 paddleft5 fcor666"></text>
					</text>
					<!-- <view class="font14 fcor666" >当前积分{{availIntegal}}</view> -->
				</view>
				<view class="dis-flex">
					<view class=" font14 fcor666" v-if="availIntegal == 0">
						暂无积分可用
					</view>
					<view class="dis-flex font12 fcor666" v-else>
						<text class="fcorred">可用{{availIntegalUse}}积分抵扣{{parseFloat(availIntegalUse/percentage)}}元</text>
						<radio @click="cilikRadio" :checked="isSelectJf" style="transform:scale(0.7)" color="#FF1A34" />
					</view>
					<!-- <view  class="icon-ymt to-right font14">
					
					</view> -->
				</view>
			</view>

			<!-- 总结算 -->
			<view class="container-price select-address ">
				<view class="address-left ">

				</view>
				<view class=" font14">
					小计:<text class="fontwig6 font22 paddleft5">¥{{priceSettle | numFormat}}</text>
				</view>
			</view>
		</view>
		<!-- 备注 -->
		<view class=" backcolorfff paading10  border-8r  border-bt mart10 ">
			<view class="container-price select-address">
				<view class="beizhu font16">
					备注:
				</view>
				<view class="beizhu font14 fcor666">
					{{noteValue.length}}/40
				</view>
			</view>
			<view class="width100">
				<textarea :cursor-spacing="50" class="border-8r backcor9 paading10 note"  :focus="false"
					:disable-default-padding="false" v-model="noteValue" maxlength="40"
					placeholder="请输入备注信息"></textarea>

			</view>

		</view>


		<!-- 底部结算按钮 -->
		<view class="tool-contain">
			<view v-if="addressDetail" class="adressConfirm">
				送至: {{addressDetail.regionName+" "+addressDetail.address}}
			</view>
			<view class="tool-right  backcolorfff">
				<view class="tool-jiesuan marRight10 dis-flex ">
					合计:<text class="fcorred font22 paddleft5">¥{{priceSettle | numFormat}}</text>
				</view>
				<view class="jiesuan-btn fcorfff" @click.stop="settleAccount">
					去支付
				</view>
			</view>
		</view>


		<detailPopup ref="detailPopup" @selectYhq="selectYhq"></detailPopup>
		<ssPaymentPassword ref="paymentPassword" :mode="1" @submit="submitHandle" />
	</view>
</template>

<script>
	import detailPopup from '@/physical-merchants/settleAccounts/detail-popup/detail-popup.vue'
	import ssPaymentPassword from '@/components/sanshui-payment-password/index.vue'
	import {
		getRegionFreight,
		getAddressPrice,
		getUserExclusiveDiscount,
		createOrder,
		findUser,
		findDeliveryAddressById
	} from '@/Utils/physicalObject.js'
	import {
		getThirdPartyByDetail
	} from '@/Utils/Api.js'
	const app = getApp();
	export default {
		data() {
			return {
				useScope: 9, //实物商品
				imageUrl: app.globalData.imgUrl, //图片地址
				noteValue: '',

				isMoreThanOne: false, //是否超过一个商品
				goodsList: [], //商品列表
				haveAddress: false, //默认没有地址
				isFirstSearchAddress:true,
				addressDetail: null, //地址信息
				postPrice: null, //运费信息

				discountList: [], //优惠券信息
				yhqId: 0, //优惠券id,
				yhqPrice: 0, //优惠券抵的价格


				jifenPrice: 0, //积分抵的价格
				userInfo: null,
				availIntegal: 0, //积分数量
				availIntegalUse:0,//可使用的积分数量
				percentage:100,//100积分兑换1块钱
				isSelectJf: false, //是否选择积分抵扣
				isShowjf:true,//是否显示积分
				PaymentPassword: 0,
				
				 noClick:true,//去支付的点击防抖判断
			}
		},
		components: {
			detailPopup,
			ssPaymentPassword
		},
		computed: {
			getNumberAll() {
				if (this.goodsList.length > 0) {
					let num = 0;
					this.goodsList.map(item => {
						num += Number(item.num);
					})

					return num;
				} else {
					return 0
				}

			},
			//商品金额
			priceAll() {
				var str = 0;
				this.goodsList.map(item=>{
					str =parseFloat((str + (item.num*item.price)).toFixed(2))
				})
				return str;
			},
			//商品原价金额
			priceOrigin() {
				var str = 0;
				this.goodsList.map(item=>{
					str =parseFloat((str + (item.num*item.originalPrice)).toFixed(2))
				})
				return str;
			},
			
			//计算运费
			postPriceAll() {
				if (this.postPrice) {
					if (this.yhqId != 0) { //使用优惠券
						if (this.priceOrigin >= this.postPrice.freePostPrice) {
							return 0
						} else {
							return this.postPrice.freightPrice;
						}
					
					}else{
						if (this.priceAll >= this.postPrice.freePostPrice) {
							return 0
						} else {
							return this.postPrice.freightPrice;
						}
					}
					
					
				} else {
					return 0;
				}
			},
			//小计金额,不含积分
			priceSettle() {
				let priceAll = Number(this.priceAll); //商品金额
				let priceOrigin = Number(this.priceOrigin); //商品原价
				let freightPrice = Number(this.postPriceAll); //运费
				let yhqPrice = Number(this.yhqPrice); //优惠券	
				if (this.yhqId != 0) { //使用优惠券
					priceAll = priceOrigin;
				}else{
					priceAll = priceAll;
				}
				// console.log("商品金额:"+priceAll)
				if (yhqPrice >= priceAll) {
					priceAll = 0;
				} else {
					priceAll =parseFloat((priceAll - yhqPrice).toFixed(2)) ;
				}
				// console.log("商品金额-优惠券:"+priceAll)
			
				//优惠券不能抵运费
				priceAll =parseFloat((priceAll + freightPrice).toFixed(2)) ;
				// console.log("商品金额-优惠券+运费:"+priceAll)
				if(priceAll == 0){
					this.isShowjf = false;
				}else{
					this.isShowjf = true;
				}

				//percentage 100,100积分兑换1块钱
				let price = parseFloat((this.availIntegal / this.percentage).toFixed(2));
				//总积分扣得钱超出了小计金额
				if(price >= priceAll){
					this.availIntegalUse =parseFloat((priceAll*this.percentage).toFixed(2)) ;
				}else {
					//总积分扣得钱没有超过小计今额	
					this.availIntegalUse = this.availIntegal;
				}
				
				// console.log("全部积分:"+this.availIntegal,"可用积分:"+this.availIntegalUse)
				
				let jifenPrice = 0;
				if(this.isSelectJf){
					
					jifenPrice = parseFloat((this.availIntegalUse / this.percentage).toFixed(2));
				}else{
					jifenPrice = 0;
				}
				
				this.jifenPrice = jifenPrice;
				// console.log("jifenPrice:"+jifenPrice)
				if (jifenPrice >= priceAll) {
					priceAll = 0;
				} else {
					priceAll =parseFloat((priceAll - jifenPrice).toFixed(2)) ;
				}
				// console.log("商品金额-优惠券+运费-积分:"+priceAll)
				return priceAll
			},
			
			// 可以使用的优惠券张数
			yhqUse() {
				if (this.discountList.length == 0) {

					return 0;
				} else {
					let num = 0;
					this.discountList.map(item => {
						if (item.discountType == 1) {
							if (this.priceAll >= item.discountCondition) {
								num += 1;
							}
						} else if (item.discountType == 2 || item.discountType == 3) { //3:折扣券,2:直抵20元
							num += 1;
						}
					})

					return num;


				}
			},	
		},
		
		onLoad(options) {
			this.goodsList = JSON.parse(options.goodsList);
			// console.log(this.goodsList,"this.goodsList")
			if (this.goodsList.length > 1) {
				this.isMoreThanOne = true;
			}
			
			// 监听事件  
			    uni.$on('address',(addressDetail)=>{  
			        this.addressDetail = addressDetail;
					this.getRegiFreight(addressDetail);
					  console.log(addressDetail,"监听")
			    })  
			
		},
		onUnload() {  
		    // 移除监听事件  
		        uni.$off('address');  
		    },
		 onShow() {
		
			this.getUserDiscount() //查询优惠券
			this.findUser() //查询用户相关内容						
			this.getAddrPrice() //查询收货地址包邮金额和运费金额
			
			if(this.addressDetail&&!this.isFirstSearchAddress){
				// console.log(this.addressDetail,"123456")
				let params = {
					id:this.addressDetail.id
				}
				findDeliveryAddressById(params).then(res=>{
					// console.log(res)
					if (res.return_code == '000000') {
						this.addressDetail = res.return_data
					}else{ //之前选择的地址失效了
						this.isFirstSearchAddress=true;
						this.haveAddress = false;
						this.addressDetail = null;
						this.getAddrPrice();
					}
				})
				
			}
			
		},
		
		methods: {
			
			//根据区域查询包邮,运费价格
			async getRegiFreight(addressDetail) {
				// console.log(addressDetail,"addressDetail")
				this.addressDetail = addressDetail;
				this.haveAddress = true;
				let params = {
					regionId: addressDetail.regionId
				}
				this.postPrice = 0;
				getRegionFreight(params).then(res => {
					if (res.return_code == '000000') {
						this.postPrice = res.return_data
					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}

				})
			},
			//初始化查询地址
			getAddrPrice() {
				
				if(!this.isFirstSearchAddress&&this.addressDetail){		
					return
				}
				
				uni.showLoading({
					title: '加载中',
					mask: true,
				});
				this.postPrice = 0;
				getAddressPrice().then(res => {
					uni.hideLoading();
					this.isFirstSearchAddress = false;
					if (res.return_code == '000000') {
						if (res.return_data) {
							this.getRegiFreight(res.return_data.deliveryAddress)
						}
					} else {
						this.haveAddress = false;
						// uni.showToast({
						// 	title: res.return_msg,
						// 	icon: 'none',
						// 	duration: 2000
						// })
					}


				})
			},
			goAddress() {
				uni.navigateTo({
					url: "/physical-merchants/address/address?status=" + 1
				})
			},
			// 查询优惠券
			getUserDiscount() {
				let _this = this;
				let params = {
					useScope: _this.useScope
				};
				getUserExclusiveDiscount(params).then(res => {
					if (res.return_code == '000000') {
						if (res.return_data.length > 0) {
							_this.discountList = res.return_data;

							// console.log(_this.discountList, "优惠券")
						}
					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			//优惠券弹射方法
			selectYhq(yhq) {
				this.yhqId = yhq;
				if (this.yhqId == 0) {
					this.yhqPrice = 0;
				} else {
					this.discountList.map(item => {
						if (this.yhqId == item.id) {
							// console.log(this.yhqId,item.id,)
							if (item.discountType == 1) {
								this.yhqPrice = item.discountPrice;
							} else if (item.discountType == 2) { //直抵券
								this.yhqPrice = item.discountPrice;
							} else if (item.discountType == 3) { //折扣券
								this.yhqPrice =parseFloat((this.priceOrigin * (1 - item.discountPrice)).toFixed(2)) ;
							}
						}
					})



				}
			},

			cilikRadio() {
				this.isSelectJf = !this.isSelectJf;
			},

			//查询用户相关内容
			findUser() {

				findUser().then(res => {
					if (res.return_code == '000000') {
						this.userInfo = res.return_data;
						// this.availIntegal = this.userInfo.gold;	
						if (this.userInfo.gold > 0) {
							// 查询积分使用比例
							this.getThirdPartyByDetail()
						} else {
							this.availIntegal = 0;
						}

						// console.log(this.userInfo, "this.userInfo", "积分", this.availIntegal)

					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}



				})
			},

			//查询积分使用比例
			//查询支付方式
			getThirdPartyByDetail() {
				// #ifdef H5
				this.showType = 2;
				// #endif
				// #ifdef MP
				this.showType = 1;
				// #endif
				let datas = {
					platformId: this.showType,
					"companyId": app.globalData.companyId,
					productType: 10
				}
				getThirdPartyByDetail(datas).then(res => {
					if (res.return_code == '000000') {
						let jfPercent = parseFloat((res.return_data.integralDiscount / 100).toFixed(2));
						
						this.availIntegal =Math.floor(parseFloat(this.userInfo.gold * jfPercent)) 
				
						
					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}
				});
			},
			




			//goods货品, freight运费,integral积分,coupon优惠券
			showPopup(str) {
				if (str == 'goods') {
					let yhqID = this.yhqId
					this.$refs.detailPopup.show(str, this.goodsList,yhqID);
				} else if (str == 'freight') {
					if (!this.addressDetail&&!this.haveAddress) {
						uni.showToast({
							title: '请先选择地址',
							duration: 1000,
							icon: 'none'
						});
						return
					}
					let obj = JSON.parse(JSON.stringify(this.postPrice));
					obj.totalPrice = this.priceAll
					this.$refs.detailPopup.show(str, obj);
				} else if (str == 'coupon') { //优惠券
					let obj = {};
					obj.discountList = this.discountList;
					obj.totalPrice = this.priceOrigin;
					this.$refs.detailPopup.show(str, obj);
				} else if (str == 'integral') { //积分
					this.$refs.detailPopup.show(str);
				}

			},
			// 去支付按钮,下单
			settleAccount() {
				
				if(this.noClick){
					this.noClick = false;
					setTimeout(()=>{
						this.noClick = true;
					},2000)
				}else{
					return
				}
				

				
				if (!this.addressDetail&&!this.haveAddress) {
					uni.showToast({
						title: '请选择地址',
						duration: 1000,
						icon: 'none'
					});
					return
				}

				//小计金额为0时
				if (this.priceSettle == 0) {
					//没有设置支付密码
					if (!this.userInfo.isSetPayPwd) {
						uni.navigateTo({
							url: '/pages/login/updatePas/updatePas'
						})
						return;
					}
					
					if (this.PaymentPassword ==  0) {
						//确认设置的密码
						this.$refs.paymentPassword.modalFun('show');

						return;
					}
					
					
					
				}
				
				this.createOrder();
				
				
			},

			createOrder() {
				//处理商品信息
				let childOrderList = [];
				this.goodsList.map(item => {
					let obj = {};
					obj.goodsType = 11;
					obj.goodsId = item.goodsId;
					obj.skuId = item.sku;
					obj.saleCount = item.num;
					if (item.id) {
						obj.shopCartId = item.id;
					} else {
						obj.shopCartId = ""
					}
					childOrderList.push(obj)
				})
				let _this = this;
				
				//处理优惠券
				let yhqId = 0;
				_this.yhqId == 0?yhqId = null:yhqId = _this.yhqId;
				
				
				//处理积分
				let jfNum = 0;
				_this.jifenPrice == 0?(jfNum = 0):(jfNum = _this.availIntegalUse)
				

				let params = {
					companyId: app.globalData.companyId,
					remarks: _this.noteValue, //备注
					memDiscountId: yhqId, //优惠券id_this.yhqId,没选优惠券时为null
					deliveryAddressId: _this.addressDetail.id, //地址id
					payGold:jfNum , //积分数量
					payPwd: _this.PaymentPassword, //支付密码
					childOrderList: childOrderList //购买的商品信息	
				}

				

				uni.showLoading({
					title: '支付中...'
				})
				createOrder(params).then(res => {
					uni.hideLoading();
					if (res.return_code == '000000') {
						// console.log(res,"订单信息")
						let obj = {
							orderNo : res.return_data.orderNo,
							createTime:res.return_data.createTime,
							payPrice:res.return_data.payPrice
							
						}
						obj = JSON.stringify(obj)
						
						// console.log(_this.priceSettle,_this.availIntegalUse)
						
						if(_this.priceSettle ==0&&_this.availIntegalUse!=0){
							uni.redirectTo({
								url: "/physical-merchants/classify/order/paymentResult?id=" + res.return_data.orderNo
							});
							
							return
						}
						
						uni.redirectTo({
							url: '/physical-merchants/classify/order/pay?obj=' + obj
						})
						return
					} 
				
				   //支付密码错误
					if(res.return_code == '102132'){
						_this.PaymentPassword = 0;
					}
					
					
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					
				})
			},
			//密码支付完成
			submitHandle(e) {
				this.PaymentPassword = e.value;
				
				if (this.PaymentPassword == 0) {
					uni.showToast({
						title: '请勿手动关闭弹窗',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				this.createOrder();

			},
		}
	}
</script>

<style lang="scss" scoped>
	.text-ov {
		// text-overflow: ellipsis;
		// white-space: nowrap;
		// width: 100%;
	}

	// 地址
	.select-address {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.border-bt {
		border-bottom: 1px solid #f6f6f6;
	}

	.container-price {
		padding: 10px;
		font-size: 16px;
	}

	// 
	.settleAccounts {

		box-sizing: border-box;
		padding-bottom: 140px;
	}

	//商品图片
	.po-ra {
		position: relative;
	}

	.settle-goods {
		width: auto;
	}

	.settle-con {

		display: flex;
		justify-content: flex-start;
		align-items: center;

		.settle-img {
			font-size: 0;
			margin-left: 10px;

			.st-img {
				width: 82px;
				height: 82px;
			}
		}

		.settle-msg {
			flex: 1;
			padding: 0 10px;

			.settle-title {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
		}


	}

	.fix-soon {
		position: absolute;
		right: 0;
		top: 0;
		width: 82px;
		height: 82px;
		line-height: 82px;
		opacity: 0.8;
		background-color: #ffffff;
		text-align: center;
	}

	//备注
	.note {
		width: auto;
	}

	// 底部结算按钮
	.tool-contain {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 10;
	}

	.tool-right {
		// flex: 1;
		display: flex;
		justify-content: space-between;
		padding: 10px;
		align-items: center;

		.tool-jiesuan {}

		.jiesuan-btn {
			flex: 1;
			// width: 200rpx;
			width: 100%;
			height: 50px;
			line-height: 50px;
			text-align: center;
			border-radius: 25px;
			background: linear-gradient(to right, #FFCC1E, #FF8F19);
		}
	}

	// 底部地址确认
	.adressConfirm {
		// height: 20px;
		padding: 10px;
		line-height: 20px;
		background-color: #FEFBDA;
	}
</style>