<template>
	<view>
		<view class="concont width94 mart10 backcorfff height45 alijusstart paddtop5 paddbotm5">
			<input class="width100 padleft15 " v-model="customerMobile" placeholder="请输入充值手机号" />
		</view>
		<view class="concont width94 mart10 backcorfff">
			<view class="width94 paddtop10 font14 fcor333">
				充值详情
			</view>
			<view class="width100 bor-botm1 mart10 marb10"></view>
			<view class="width100">
				<view class="width100 alijusstart mart10 bor-botm1 paddbotm10">
					<view class="width70 padleft15">
						<view class="width100 font14 fcor333 fontwig6">{{goodName}}</view>
						<view class="width100 font12 fcor999 mart5">
						</view>
					</view>
					<view class="width10 font12 fcor999">x1</view>
					<view class="width20">
						<view class="width100 fcor333 font12">¥<text class="fontwig6 font16">{{totalprice}}</text>
						</view>
						<view class="width100 fcor999 font12" v-if="totalprice != oldPrice"
							style="text-decoration: line-through;">¥{{oldPrice}}
						</view>
					</view>
				</view>
				<view class="width90 fotrt height50 font13 fcor999">
					共 <text class="fcor333 fontwig6" style="margin: 0px 5px;"> 1 </text> 件 小计:
					<text class="font16 colorc3 fontwig6 margle"> ¥{{totalprice}}</text>
					<text class="font12 fcor999 fontwig6 margle" style="text-decoration: line-through;">
						¥{{orderPrice}}</text>
				</view>
			</view>
		</view>
		<view class="width94 concont mart10 backcorfff marb100">
			<view class="height50 width100 paddtop5 backcorfff" @click="showPopup()">
				<view class="width50 flleft fcor333 fontwig6 font16" style="padding-left: 4%;">
					优惠抵扣<text class="yhqky">{{OrderPreList.length}}张可用</text>
				</view>
				<view class="width40 flright fotrt paddtright10 font15 fontwig6 fcor666 alijun"
					style="align-items: center;" v-if="deductionPrice == 0">
					未使用
					<image style="width: 40rpx;height: 40rpx;" src="../../static/img/jt.png"></image>
				</view>
				<view class="width40 flright fotrt paddtright10 font15 fontwig6 fcoreb5 alijun"
					style="align-items: center;" v-else>
					-￥{{deductionPrice}}
					<image style="width: 40rpx;height: 40rpx;" src="../../static/img/jt.png"></image>
				</view>
			</view>
			<view class="width94 line1 mart5 marb5"></view>
			<view class="Bubble alijusstart font14 fcor999">
				选取: <text class="tests fotct font14 colorc3 paddleft5 paddtright5">{{priceValue[1]}}</text> 分
			</view>
			<view class="width92 alijusstart paddtop10">
				<view class="width30 fcor333 fontwig6 font16">
					积分抵扣
				</view>
				<view class="cj-slider">
					<view class="flleft fotct font14 fcor666" style="width: 15%;">0</view>
					<cj-slider style="width: 60%; float:left;" v-if="isDiscount" v-model="priceValue" :min="0"
						:max="availIntegal" :step="1" :blockWidth="40" @start="blockStart" @moving="blockMoving"
						@end="blockEnd" />
					<view class="flright fotrt font14 fcor666" style="width: 25%;">{{availIntegal}}</view>
				</view>
			</view>
			<view class="width94 line1 mart15 marb5"></view>
			<view class="height50 width100 backcorfff">
				<view class="width70 flleft fcor666 font16 text1" style="padding-left: 4%;">
					抵扣金额
				</view>
				<view class="width20 flright fotrt paddtright10 font15 fcor666 alijun" style="align-items: center;">
					¥{{priceValue[1] / 100}}
				</view>
			</view>
			<view class="height50 width100">
				<view class="width100 flleft fcor333 fontwig6 font16" style="padding-left: 4%;">
					支付方式
				</view>
			</view>
			<view class="width100" v-for="(item,index) in paytypeList" :key="index">
				<view class="width94 line1 mart5 marb5" v-if="item == 2"></view>
				<view class="height50 width100 backcorfff" @tap="paytype='2'" v-if="item == 2">
					<view class="width50 flleft fcor666  font16" style="padding-left: 4%;">
						微信支付
					</view>
					<view class="width40 flright fotrt paddtright10 font15 fontwig6 fcor666 alijun"
						style="align-items: center;" v-if="isUse">
						<radio :checked="paytype=='2'" color="#c72a20" />
					</view>
				</view>
				<view class="width94 line1 mart5 marb5" v-if="item == 3"></view>
				<view class="height50 width100 backcorfff" @tap="paytype='3'" v-if="item == 3">
					<view class="width70 flleft fcor666  font16 text1" style="padding-left: 4%;">
						汇联通工会卡<text class="font14 fcor666 margle">可用余额: {{tongCardPrice}}元</text>
					</view>
					<view class="width20 flright fotrt paddtright10 font15 fontwig6 fcor666 alijun"
						style="align-items: center;" v-if="isUse">
						<radio :checked="paytype=='3'" @click="changeRiado()" color="#c72a20" />
					</view>
				</view>
			</view>
		</view>

		<view class="footbtn width100 height50 backcor33">
			<view class="width94 alijusstart">
				<view class="width70 fcorfff">
					合计: ¥<text class="font16 fontwig6" style="margin: 0px 6px;">{{payPrice}}</text>
				</view>
				<view class="width30 fotrt" @click="qzaddorder()">
					<view class="btnpay fotct font13 fcorfff" style="background-color: #c72a20;">去支付
					</view>
				</view>
			</view>
		</view>

		<wybPopup ref="popup" type="bottom" width="500" :scrollY="true" radius="6" :showCloseIcon="true">
			<view class="fotct font18 fontwig6 fcor333 mart10 height30">优惠券选择</view>
			<view class="width92 height110 tccs mart10" v-for="(items, index) in OrderPreList" :key="index"
				@click="radioChanges(items)">
				<image mode="widthFix" class="mart10" :src="imageUrl+items.discountImg"></image>
				<view class="contrig">
					<view class="width80p flleft">
						<view class="font16 fontwig6 fcor333 text1 paddtop25">{{items.discountName}}</view>
						<view class="font13 fcor999 mart5">有效期:{{items.useEndTime | timeFormat('yyyy-mm-dd hh:mm:ss')}}
						</view>
					</view>
					<view class="width20 flright">
						<view class="yhprice">
							<radio v-if="items.discountCondition && orderPrice >= items.discountCondition"
								color="#c72a20" :checked="items.id == memDiscountId" />
							<radio v-if="items.discountCondition && orderPrice < items.discountCondition"
								color="#c72a20" disabled="true" :checked="items.id == memDiscountId" />
							<radio v-if="!items.discountCondition" color="#c72a20"
								:checked="items.id == memDiscountId" />
						</view>
					</view>
				</view>
			</view>
		</wybPopup>
		<ssPaymentPassword ref="paymentPassword" :mode="1" @submit="submitHandle" />
	</view>
</template>

<script>
	import cjSlider from '@/components/cj-slider/cj-slider.vue';
	import ssPaymentPassword from '@/components/sanshui-payment-password/index.vue';
	import wybPopup from '../../components/wyb-popup/wyb-popup.vue';
	import {
		xbkaddOrder,
		getThirdPartyByDetail,
		getHuiLianTongCardBalance,
		findUser,
		qianzhuorderToPayByWx,
		czhltUnionCardPay,
		getUserOrderPreList,
		thirdCancelOrder
	} from '../../Utils/Api.js';
	// #ifdef H5
	var jweixin = require('jweixin-module');
	// #endif
	let app = getApp();
	export default {
		components: {
			cjSlider,
			ssPaymentPassword,
			wybPopup
		},
		data() {
			return {
				orderList: [],
				paytype: '', //支付方式
				priceValue: [0, 0], // 积分可以指定默认值
				availIntegal: 0, // 可用积分
				totalprice: 0, //总价
				oldPrice: 0, //原价
				disconutprice: 0, //优惠价格
				totalnum: '', //总数量
				customerMobile: '', //电话号码

				paytypeList: [], //支付方式
				tongCardPrice: 0, //工会卡余额
				user: '', //个人信息
				isUse: true, // 是否禁用状态
				payPrice: 0, //支付价格
				isDiscount: true, //刷新组件
				showType: '', //平台
				memDiscountId: '', //优惠券id
				PaymentPassword: '', //支付密码
				goodId: '', //商品id
				goodName: '', //商品name
				orderId: '', //订单id
				deductionPrice: '0.00', //优惠金额
				OrderPreList: [], //优惠券数据
				imageUrl: app.globalData.imgUrl, //图片地址
				orderPrice: 0, //订单价格
				rechargeDes: '', // 支付详情
			}
		},
		onLoad(options) {
			this.goodId = options.goodid;
			this.oldPrice = options.oldprice;
			this.orderPrice = options.oldprice;
			this.totalprice = options.price;
			this.payPrice = options.price;
			this.goodName = options.name;
		},
		onShow() {
			this.customerMobile = app.globalData.userInfo.phone;
			this.findUser();
		},
		methods: {
			//查询支付方式
			getThirdPartyByDetail() {
				// #ifdef H5
				this.showType = 2;
				// #endif
				// #ifdef MP
				this.showType = 1;
				// #endif
				let datas = {
					platformId: this.showType,
					regionId: app.globalData.cityId,
					productType: 3
				}
				getThirdPartyByDetail(datas).then(res => {
					if (res.return_code == '000000') {
						this.rechargeDes = res.return_data;
						this.paytypeList = res.return_data.productPayType.split(',');
						this.paytypeList = this.paytypeList.slice(0, this.paytypeList.length - 1);
						let zkprice = parseFloat(res.return_data.integralDiscount / 100).toFixed(2);
						let pprice = parseFloat(this.totalprice * 100).toFixed(0)
						let payprice = parseFloat(this.totalprice * 100 * zkprice).toFixed(
							0);
						if (payprice > this.user.gold) {
							this.availIntegal = this.user.gold;
						} else {
							this.availIntegal = payprice;
						}
					}
				});
			},
			//查询积分
			findUser() {
				findUser().then(res => {
					if (res.return_code == '000000') {
						app.globalData.userInfo = res.return_data;
						this.user = res.return_data;
						this.getHuiLianTongCardBalance();
						this.getThirdPartyByDetail();
						this.getUserOrderPreList();
						uni.setStorage({
							key: "user",
							data: res.return_data
						})
					}
				});
			},
			//查询工会卡详情
			getHuiLianTongCardBalance() {
				if (!this.user.hltCardNo) {
					return;
				}
				let params = {
					cardNo: this.user.hltCardNo.cardNo
				}
				getHuiLianTongCardBalance(params).then(res => {
					if (res.return_code == '000000') {
						this.tongCardPrice = res.return_data.balance;
					}
				});
			},
			//刷新组件
			reload() {
				this.isDiscount = false;
				this.$nextTick(() => (this.isDiscount = true))
			},
			//滑动开始
			blockStart() {},
			blockMoving() {
				// console.log('正在滑动中')
			},

			//滑动结束
			blockEnd() {
				this.isDiscount = 1;
				if (this.deductionPrice == 0) {
					this.payPrice = Math.abs(parseFloat(this.totalprice - parseFloat(this.priceValue[1] / 100).toFixed(2))
						.toFixed(
							2));
				} else {
					this.payPrice = Math.abs(parseFloat(this.orderPrice - parseFloat(this.priceValue[1] / 100).toFixed(2) -
						this
						.deductionPrice).toFixed(2));
				}
				if (this.payPrice == 0) {
					this.isUse = false;
					this.paytype = '';
				} else {
					this.isUse = true;
				}
			},
			//获取选择支付方式
			changeRiado() {
				if (!this.user.isSetHltCard) {
					uni.showToast({
						icon: 'none',
						title: '当前账号还未绑定,前往绑定',
						duration: 2000,
						success() {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/user/bindingCard/bindingCard'
								})
							}, 1000)
						}
					});
					return;
				}
			},
			//下单
			qzaddorder() {
				if (this.customerMobile == '') {
					uni.showToast({
						title: '请输入充值手机号',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				if (this.payPrice == 0) {
					if (!this.user.isSetPayPwd) {
						uni.navigateTo({
							url: '../../pages/login/updatePas/updatePas'
						})
						return;
					}
					this.$refs.paymentPassword.modalFun('show');
					return;
				}

				if (this.paytype == '') {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				uni.showLoading({
					title: '提交订单中...'
				})
				let datas = {
					"customerMobile": this.customerMobile,
					"regionId": app.globalData.cityId,
					"productType": 3,
					"platformId": this.showType,
					"password": this.PaymentPassword,
					"integralNum": this.priceValue[1],
					"memDiscountId": this.memDiscountId,
					"goodsId": this.goodId
				}

				xbkaddOrder(datas).then(res => {
					uni.hideLoading();
					if (res.return_code == '000000') {
						this.orderId = res.return_data.id;
						let params = {
							"orderId": res.return_data.id,
							"openId": app.globalData.openId,
							"openIdType": this.showType
						}
						this.qianzhuorderToPayByWx(params);
					} else {
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			//查询优惠券
			getUserOrderPreList() {
				let params = {
					useScope: 6
				}
				getUserOrderPreList(params).then(res => {
					if (res.return_code == '000000') {
						this.OrderPreList = res.return_data;
					}
				});
			},
			//弹出优惠券
			showPopup() {
				this.$refs.popup.show();
			},
			//选择优惠券
			radioChanges(item) {
				this.rechangeload();
				if (this.memDiscountId == item.id) { // 如果已经选中，则取消选中
					this.memDiscountId = '';
					this.deductionPrice = '0.00';
					this.priceCaluc(this.totalprice);
				} else { // 否则进行选中赋值
					if (item.discountType == 1) {
						if (this.orderPrice > item.discountCondition) {
							this.memDiscountId = item.id;
							//满减价格
							this.deductionPrice = item.discountPrice;
							let oldprice = this.orderPrice - this.deductionPrice;
							this.priceCaluc(oldprice);
						} else {
							uni.showToast({
								title: '请满' + item.discountCondition + '使用此券',
								icon: 'none',
								duration: 2000
							})
						}
					}
					if (item.discountType == 2) {
						this.memDiscountId = item.id;
						//抵扣价格
						this.deductionPrice = item.discountPrice;
						let oldprice = this.orderPrice - this.deductionPrice;
						this.priceCaluc(oldprice);
					}
					if (item.discountType == 3) {
						this.memDiscountId = item.id;
						// 打折
						this.deductionPrice = parseFloat(this.orderPrice - (this.orderPrice * item.discountPrice))
							.toFixed(2);
						let oldprice = parseFloat(this.orderPrice * item.discountPrice).toFixed(2);
						this.priceCaluc(oldprice);

					}
				}
				this.$refs.popup.hide();
			},
			//计算价格
			priceCaluc(item) {
				let zkprice = parseFloat(this.rechargeDes.integralDiscount / 100).toFixed(2);
				let pprice = parseFloat(item * 100).toFixed(0);
				let payprice = parseFloat(item * 100 * zkprice).toFixed(0);
				if (payprice > this.user.gold) {
					this.availIntegal = this.user.gold;
					this.priceValue[1] = 0;
				} else {
					this.availIntegal = payprice;
					this.priceValue[1] = 0;
				}
				this.reload();
				this.calculatepayPrice();
			},
			//计算支付价格
			calculatepayPrice() {
				if (this.deductionPrice == 0) {
					this.payPrice = Math.abs(parseFloat(this.totalprice - (parseFloat(this.priceValue[1] / 100).toFixed(
							2)))
						.toFixed(2));
				} else {
					this.payPrice = Math.abs(parseFloat(this.orderPrice - (parseFloat(this.priceValue[1] / 100).toFixed(
						2)) - this
						.deductionPrice).toFixed(2));
				}
			},
			rechangeload() {
				this.isUse = false;
				this.$nextTick(() => (this.isUse = true))
			},
			//刷新组件
			reload() {
				this.isDiscount = false;
				this.$nextTick(() => (this.isDiscount = true))
			},
			//获取订单数据
			qianzhuorderToPayByWx(item) {
				let that = this;
				if (that.paytype == '2') {
					qianzhuorderToPayByWx(item).then(res => {
						if (res.return_code == '000000') {
							// #ifdef MP
							uni.showLoading({
								title: '支付中...'
							})
							uni.requestPayment({
								"appId": res.return_data.appId,
								"nonceStr": res.return_data.nonceStr,
								"package": res.return_data.package,
								"paySign": res.return_data.sign,
								"signType": "MD5",
								"timeStamp": res.return_data.timeStamp,
								success: function(res) {
									uni.hideLoading();
									uni.showToast({
										title: '支付成功'
									})
									uni.reLaunch({
										url: '/qianzhu-KFC/order-details/order-details?id=' +
											that.orderId
									})
								},
								fail: function(err) {
									uni.hideLoading();
									uni.navigateBack({})
								},
							});
							// #endif

							//判断是否是公众号
							// #ifdef H5
							that.payRequest(res);
							// #endif

						} else {
							uni.showToast({
								title: res.return_msg,
								duration: 2000,
								icon: 'none'
							})
						}
					})
				} else if (that.paytype == '3') {
					if (that.tongCardPrice < that.payPrice) {
						uni.showToast({
							icon: 'none',
							title: '工会卡余额不足',
							duration: 2000,
						});
						that.thirdCancelOrder();
						return;
					}
					if (!that.user.isSetPayPwd) {
						uni.navigateTo({
							url: '../../pages/login/updatePas/updatePas'
						})
						that.thirdCancelOrder();
						return;
					}
					if (!that.user.isSetHltCard) {
						uni.showToast({
							icon: 'none',
							title: '当前账号还未绑定,前往绑定',
							duration: 2000,
							success() {
								setTimeout(() => {
									uni.navigateTo({
										url: '../../pages/user/bindingCard/bindingCard'
									})
								}, 1000)
							}
						});
						that.thirdCancelOrder();
						return;
					}
					that.$refs.paymentPassword.modalFun('show');
				} else {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none',
						duration: 2000
					})
				}
			},
			//取消订单
			thirdCancelOrder() {
				let params = {
					orderId: this.orderId,
				}
				thirdCancelOrder(params).then(res => {
					if (res.return_code == '000000') {
						this.orderId = '';
					}
				})
			},
			submitHandle(e) {
				uni.showLoading({
					title: '支付中...'
				})
				this.PaymentPassword = e.value;
				if (this.PaymentPassword == '') {
					uni.showToast({
						title: '请勿手动关闭弹窗',
						icon: 'none',
						duration: 2000
					})
					uni.hideLoading();
					return;
				}
				if (this.payPrice == 0) {
					let datas = {
						"customerMobile": this.customerMobile,
						"regionId": app.globalData.cityId,
						"productType": 3,
						"platformId": this.showType,
						"password": this.PaymentPassword,
						"integralNum": this.priceValue[1],
						"memDiscountId": this.memDiscountId,
						"goodsId": this.goodId
					}

					xbkaddOrder(datas).then(res => {
						uni.hideLoading();
						if (res.return_code == '000000') {
							this.orderId = res.return_data.id;
							uni.reLaunch({
								url: '/qianzhu-KFC/order-details/order-details?id=' + this.orderId
							})
							return;
						}
						if (res.return_code == '102130') {
							uni.navigateTo({
								url: '../../login/updatePas/updatePas'
							})
							return;
						}
						this.thirdCancelOrder();
						uni.showToast({
							title: res.return_msg,
							icon: 'none',
							duration: 2000
						});
					})
					return;
				}
				let params = {
					"orderId": this.orderId,
					"cardNo": this.user.hltCardNo.cardNo,
					"password": this.PaymentPassword
				}
				czhltUnionCardPay(params).then(res => {
					uni.hideLoading();
					if (res.return_code == '000000') {
						uni.showToast({
							title: '支付成功'
						})
						uni.reLaunch({
							url: '/qianzhu-KFC/order-details/order-details?id=' + this.orderId
						})
						return;
					}
					if (res.return_code == '102130') {
						uni.navigateTo({
							url: '../../login/updatePas/updatePas'
						})
						return;
					}
					uni.showToast({
						title: res.return_msg,
						icon: 'none',
						duration: 2000
					})
				})


			},
			payRequest: function(self) {
				let that = this;
				uni.showLoading({
					title: '支付中...'
				})
				jweixin.config({
					// debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: self.return_data.appId, // 必填，公众号的唯一标识
					timestamp: self.return_data.timeStamp, // 必填，生成签名的时间戳
					nonceStr: self.return_data.nonceStr, // 必填，生成签名的随机串
					signature: self.return_data.sign, // 必填，签名，见附录1
					jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				uni.hideLoading();
				jweixin.ready(function() {
					jweixin.checkJsApi({
						jsApiList: ['chooseWXPay'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
						success: function(res) {},
						fail: function(res) {}
					});
					jweixin.chooseWXPay({
						appId: self.return_data.appId,
						timestamp: self.return_data
							.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
						nonceStr: self.return_data.nonceStr, // 支付签名随机串，不长于 32 位
						package: self.return_data
							.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
						signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
						paySign: self.return_data.sign, // 支付签名
						success: function(res) {
							// 支付成功后的回调函数
							uni.showToast({
								title: '支付成功'
							})
							uni.reLaunch({
								url: '/qianzhu-KFC/order-details/order-details?id=' + that
									.orderId
							})
						},
						cancel: function(r) {
							uni.navigateBack({})
						},
						fail: function(res) {
							uni.navigateBack({})
						}
					});
				});

				jweixin.error(function(res) {
					uni.showToast({
						icon: 'none',
						title: '支付失败了',
						duration: 4000
					});
				});
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f0f0f0;
	}

	.headsbg {
		border-radius: 0 0 30px 30px;
	}

	.concont {
		border-radius: 12px;
	}

	.Bubble {
		margin-left: 50%;
		padding-top: 15px;
	}

	.tests {
		border-radius: 15px;
		height: 22px;
		line-height: 22px;
	}

	.jfrecharge {
		padding: 3px 20rpx;
		color: #fff;
		margin-left: 50%;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		border-radius: 40rpx;
	}

	.footbtn {
		bottom: 0px;
		position: fixed;
	}

	.btnpay {
		width: 90px;
		border-radius: 22px;
		height: 36px;
		line-height: 36px;
	}

	.takemode {
		width: 48%;
		border-radius: 5px;
		border: 1px solid #999999;
	}

	.aftermode {
		background-color: #faf1f1;
		color: #c72a20;
	}

	.cj-slider {
		width: 100%;
		align-items: center;
		display: flex;
	}

	.yhqky {
		background: #ff0034;
		color: #ffffff;
		font-size: 14px;
		padding-left: 5px;
		padding-right: 5px;
		margin-left: 8px;
		padding-top: 2px;
		padding-bottom: 2px;
	}

	.yhprice {
		margin-top: -30px;
	}

	.contrig {
		margin-left: 180rpx;
	}

	.tccs {
		box-shadow: 0rpx 0rpx 10rpx rgba(0, 0, 0, 0.2);
		border: 1px solid #f6f6f6;
		border-radius: 8px;

		image {
			float: left;
			width: 170rpx;
			max-height: 170rpx;
			margin-left: 10px;
		}
	}
</style>
