<template>
	<view :class="['qn-page-' + theme]" class="app">
		<view class="price-box">
			<text>支付金额</text>
			<text class="price primary-color">{{ price }}</text>
		</view>
		<view class="pay-type-list" @click="changePayType(item)" v-for="(item, index) in payWay" :key="index">
			<view class="type-item">
				<text v-if="item.title.indexOf('微信') !== -1" class="ibonfont ibonweixinzhifu"></text>
				<text v-else-if="item.title.indexOf('支付宝') !== -1" class="ibonfont ibonumidd17"></text>
				<text v-else class="ibonfont ibonhuodaofukuan"></text>
				<view class="con">
					<view class="tit">
						<text>{{ item.title }}</text>
						<text class="user-balance" v-if="item.id === 7">（余额：¥{{ Number(userInfo.memberBalance) }}）</text>
					</view>
					<text v-if="item.defaultStatus === 5">推荐使用{{ item.title }}</text>
					<block v-if="item.id === 7">
						<text v-if="price > Number(userInfo.memberBalance)" class="balance-tip primary-color">可支付余额不足，请搭配其他支付方式</text>
					</block>
				</view>
				<label class="radio"><radio :value="item.id" :color="primaryColor" :checked="pay_id.indexOf(parseInt(item.id)) > -1"></radio></label>
			</view>
		</view>
		<text class="mix-btn primary-bg" @click="confirm">确认支付</text>
		<!-- 余额支付密码弹窗 -->
		<u-keyboard
			default=""
			ref="uKeyboard"
			mode="number"
			:mask="true"
			:mask-close-able="false"
			:dot-enabled="false"
			v-model="pwd_show"
			:safe-area-inset-bottom="true"
			:tooltip="false"
			@change="balancePopChange"
			@backspace="onBackspace"
		>
			<view>
				<view class="u-text-center u-padding-20 balance-money">
					<text v-if="pay_id.length > 1">{{ Number(userInfo.memberBalance) }}</text>
					<text v-else>{{ price }}</text>
					<text class="u-font-20 u-padding-left-10">元</text>
					<view class="u-padding-10 close" data-flag="false" @tap="balanceShowPop(false)"><u-icon name="close" color="#333333" size="28"></u-icon></view>
				</view>
				<view class="u-flex u-row-center">
					<u-message-input mode="box" :maxlength="6" :dot-fill="true" v-model="balance_pwd" :disabled-keyboard="true" @finish="balanceFinish"></u-message-input>
				</view>
				<view class="u-text-center u-padding-top-10 u-padding-bottom-20 tips">支付键盘</view>
			</view>
		</u-keyboard>
		<!-- 提示去设置支付密码 -->
		<u-modal
			v-model="tip_show"
			content="抱歉,您未设置支付密码,无法使用余额支付"
			:show-cancel-button="true"
			confirm-text="立即设置"
			cancel-text="取消"
			@confirm="setPassword"
		></u-modal>
	</view>
</template>

<script>
import QiniuUpload from '../components/qiniu/QiniuUpload.vue';
export default {
	components: {
		QiniuUpload
	},
	data() {
		return {
			tip_show: false, // 余额支付提示
			pwd_show: false, // 余额支付密码输入弹窗
			balance_pwd: '', // 余额支付密码
			bank_data: {
				// 银行信息
				id: '',
				name: '',
				bankName: '',
				accountNumber: '',
				image: ''
			},
			pay_id: [],
			orderInfo: {},
			vipId: '',
			payWay: {},
			price: '',
			no: '',
			orderId: '',
			vip: 0,
			source: '', //订单来源
			payInfo: '',
			tmplIds: []
		};
	},
	onLoad(options) {
		if (options.payType) {
			this.pay_id = options.payType.split(',').map(item => parseInt(item));
		}
		this.orderId = options.id ? Number(options.id) : '';
		this.price = Number(options.price);
		this.vip = options.vip || '';
		this.vipId = options.vipId || '';
		this.source = this.$common.source();
		this.no = options.no;
		this.getPaymentType();
		this.getCustomerInfo();
	},
	computed: {
		userInfo() {
			return this.$store.state.userStatus;
		}
	},
	methods: {
		// 获取用户信息
		getCustomerInfo() {
			this.$u.api.getCustomerInfo().then(({ data }) => {
				this.userInfo = data;
				// 如果余额为0 则不能选择余额支付方式
				const index = this.pay_id.findIndex(item => item === 7);
				if (!Number(data.memberBalance)) {
					if (index > -1) {
						this.pay_id.splice(index, 1);
					}
				}

				this.$store.commit('commit_userStatus', data);
			});
		},
		// 选择支付的方式
		changePayType(item) {
			if (item.id === 7 && Number(this.userInfo.memberBalance) <= 0) {
				this.$u.toast('抱歉，您的可用余额不足');
			} else {
				// 已选择过该支付方式就把支付方式从数组去掉
				const payIndex = this.pay_id.indexOf(item.id);
				if (payIndex > -1) {
					this.pay_id.splice(payIndex, 1);
					return;
				}
				// 用户可支付余额不足
				if (this.price > Number(this.userInfo.memberBalance)) {
					// 查找余额支付的支付方式ID
					const balaceObj = this.payWay.find(item => item.id === 7);
					// 已选择过余额支付，可选择其他支付
					const balaceindex = balaceObj ? this.pay_id.indexOf(balaceObj.id) : -1;
					if (balaceObj && balaceindex > -1) {
						//余额付款只能和微信支付进行组合
						if (item.id !== 1) {
							this.pay_id = [item.id];
							return;
						}
						if (this.pay_id.length >= 2) {
							if (balaceindex === 0) {
								this.$set(this.pay_id, 1, item.id);
							} else {
								this.$set(this.pay_id, 0, item.id);
							}
						} else {
							this.pay_id.push(item.id);
						}
					} else {
						// 未选择余额支付,当支付数组length未0，直接把支付方式放入数组
						if (this.pay_id.length === 0) {
							this.pay_id.push(item.id);
						} else {
							//余额付款只能和微信支付进行组合
							if (this.pay_id.indexOf(1) === -1) {
								//  替换 之前选择的支付方式
								this.pay_id.splice(0, 1, item.id);
							} else {
								// 如果当前选择的支付方式是余额支付，则放入数组
								if (item.id === 7) {
									this.pay_id.push(item.id);
								} else {
									// 否则 替换 之前选择的支付方式
									this.pay_id.splice(0, 1, item.id);
								}
							}
						}
					}
				} else {
					this.$set(this.pay_id, 0, item.id);
				}
			}
		},
		// 支付列表
		getPaymentType() {
			this.$u.api
				.getPaymentType({
					price: this.price
				})
				.then(({ data }) => {
					this.payWay = data.filter(item => item.id !== 3);
					// 判断支付购买会员卡，支付列表没有货到付款
					if (this.vip) {
						this.payWay = data.filter(item => item.id === 1);
					} else {
						this.payWay = data.filter(item => item.title.indexOf('支付宝') === -1);
					}
					// 银行信息
					const banck_data = this.payWay.find(item => item.id === 4);
					this.bank_data = banck_data
						? {
								id: banck_data.accountData.id,
								name: banck_data.accountData.name,
								bankName: banck_data.accountData.bankName,
								accountNumber: banck_data.accountData.accountNumber,
								image: ''
						  }
						: {};
				});
		},
		// 余额支付密码键盘按键被点击(不包含退格键被点击)
		balancePopChange(val) {
			if (this.balance_pwd.length < 6) {
				this.balance_pwd += val;
			}

			if (this.balance_pwd.length >= 6) {
				// 唤起密码验证
				this.checkPayPassword();
			}
		},
		//键盘退格键被点击
		onBackspace(e) {
			if (this.balance_pwd.length > 0) {
				this.balance_pwd = this.balance_pwd.substring(0, this.balance_pwd.length - 1);
			}
		},
		// 余额密码弹窗显示
		balanceShowPop(flag = true) {
			this.balance_pwd = '';
			this.pwd_show = flag;
		},
		// 余额密码输入完成
		balanceFinish() {
			// 唤起支付
			this.addOrder();
		},
		// 去设置支付密码
		setPassword() {
			this.goPage('/pagesT/money/PayPassword');
		},
		// 支付密码校验
		checkPayPassword() {
			this.$u.api
				.checkPayPassword({
					id: this.userInfo.id,
					payPassword: this.balance_pwd
				})
				.then(res => {
					this.addOrder();
				})
				.catch(res => {
					this.balance_pwd = '';
				});
		},
		//确认支付
		confirm() {
			if (!this.pay_id.length) {
				uni.showToast({
					title: '请选择支付方式',
					icon: 'none'
				});
				return false;
			}
			if (this.price > Number(this.userInfo.memberBalance)) {
				if (this.pay_id.indexOf(7) > -1 && this.pay_id.length !== 2) {
					this.$u.toast('可支付余额不足，请搭配其他支付方式');
					return;
				}
			}
			// 余额支付弹窗
			if (this.pay_id.indexOf(7) > -1) {
				if (this.userInfo.payPassword) {
					this.balanceShowPop();
				} else {
					this.tip_show = true;
				}
				return;
			}
			this.addOrder();
		},
		// 打开银行上传凭证弹窗
		openBankPop() {
			// 银行打款弹窗
			if (this.pay_id.indexOf(4) > -1) {
				uni.redirectTo({
					url: `/pagesT/money/BankPay?orderId=${this.orderId}&payAmount=${this.price}`
				});
				return;
			}
		},
		addOrder() {
			this.createOrder();
			return;
			// #ifdef MP-WEIXIN
			if (this.tmplIds.length) {
				uni.requestSubscribeMessage({
					tmplIds: this.tmplIds,
					success: res => {
						this.createOrder();
					},
					fail: res => {
						this.createOrder();
					}
				});
			} else {
				this.createOrder();
			}
			// #endif
			// #ifdef APP-PLUS
			this.createOrder();
			// #endif
		},
		createOrder() {
			if (!this.vip) {
				// 余额支付数据
				let admixPayData = [];
				if (this.pay_id.length === 2) {
					// 查找余额支付的支付方式ID
					const balaceObj = this.payWay.find(item => item.id === 7);
					admixPayData = this.pay_id.map(item => {
						let obj = {};
						if (balaceObj.id === item) {
							obj = {
								payType: item,
								title: balaceObj.title,
								payMoney: Number(this.userInfo.memberBalance)
							};
						} else {
							obj = {
								payType: item,
								title: this.payWay.find(pay => pay.id === item).title,
								payMoney: (this.price - this.userInfo.memberBalance).toFixed(2)
							};
						}

						return obj;
					});
				}

				const params = {
					payType: this.pay_id.join(','),
					no: this.no,
					source: this.source
				};
				if (this.pay_id.length === 2) {
					params.admixPayData = admixPayData;
				}

				this.$u.api.payOrder(params).then(({ data }) => {
					// 货到付款 直接进入订单页面
					if (this.pay_id.length === 1) {
						if (this.pay_id.indexOf(3) > -1) {
							uni.redirectTo({
								url: '/pagesT/order/order?state=0'
							});
							return;
						} else if (this.pay_id.indexOf(4) > -1) {
							// 银行打款弹窗
							this.openBankPop();
							return;
						}
					}

					this.payInfo = data;
					this.requestPayment();
				});
			} else {
				this.$u.api
					.createVipCardOrder({
						payType: this.pay_id.join(','),
						source: this.source,
						vipCardId: this.vipId
					})
					.then(({ data }) => {
						this.payInfo = data;
						this.requestPayment();
					});
			}
		},
		requestPayment() {
			// #ifdef APP-PLUS
			let provider = '';
			if (this.pay_id.indexOf(1) > 1) {
				provider = 'wxpay';
			} else if (this.pay_id.indexOf(2) > 1) {
				provider = 'alipay';
			}
			if (!provider) {
				if (!this.vip) {
					uni.redirectTo({
						url: '/pagesT/order/order?state=0'
					});
				} else {
					uni.redirectTo({
						url: '/pagesT/user/VipList'
					});
				}
				return;
			}
			uni.requestPayment({
				provider: provider, //供应商
				orderInfo: this.payInfo,
				success: res => {
					if (!this.vip) {
						// 银行打款弹窗
						this.openBankPop();
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/money/paySuccess?price=' + this.price
							});
						}, 2000);
					} else {
						this.$api.msg('支付成功');
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/user/VipList'
							});
						}, 2000);
					}
				},
				fail: err => {
					this.$api.msg('支付未成功');
					if (!this.vip) {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/order/order?state=0'
							});
						}, 2000);
					} else {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/user/VipList'
							});
						}, 2000);
					}
				}
			});
			// #endif
			// #ifdef MP-TOUTIAO
			if (this.pay_id.indexOf(1) === 1) {
				uni.redirectTo({
					url: '/pagesT/order/order?state=0'
				});
				return;
			}
			uni.requestPayment({
				provider: 'toutiao',
				service: 3, //字节跳动小程序必填，service=3： 微信API支付，不拉起小程序收银台；service=4： 支付宝API支付，不拉起小程序收银台。
				orderInfo: this.payInfo,
				success: res => {
					this.$u.api
						.orderquery({
							out_trade_no: this.payInfo.out_order_no
						})
						.then(data => {
							const payStatus = data.data;
							if (payStatus === 'SUCCESS') {
								if (!this.vip) {
									// 银行打款弹窗
									this.openBankPop();
									setTimeout(() => {
										uni.redirectTo({
											url: '/pagesT/money/paySuccess?price=' + this.price
										});
									}, 2000);
								} else {
									this.$api.msg('支付成功');
									setTimeout(() => {
										uni.redirectTo({
											url: '/pagesT/user/VipList'
										});
									}, 2000);
								}
							} else {
								uni.redirectTo({
									url: '/pagesT/order/order?state=0'
								});
							}
						});
				},
				fail: err => {
					console.log('err:', err);
					if (!this.vip) {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/order/order?state=0'
							});
						}, 2000);
					} else {
						this.$api.msg('支付未成功');
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/user/VipList'
							});
						}, 2000);
					}
				}
			});
			// #endif
			// #ifdef MP-WEIXIN
			if (this.pay_id.indexOf(1) === -1) {
				uni.redirectTo({
					url: '/pagesT/order/order?state=0'
				});
				return;
			}
			uni.requestPayment({
				provider: this.payInfo.provider, //供应商
				timeStamp: this.payInfo.timeStamp, //当前时间
				nonceStr: this.payInfo.nonceStr, //随机字符串，长度在32一下
				package: this.payInfo.package, //统一单接口返回的prepay_id
				signType: this.payInfo.signType, //签名算法，目前支持MD5
				paySign: this.payInfo.paySign, //签名
				success: res => {
					if (!this.vip) {
						// 银行打款弹窗
						this.openBankPop();
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/money/paySuccess?price=' + this.price
							});
						}, 100);
					} else {
						this.$api.msg('支付成功');
						uni.redirectTo({
							url: '/pagesT/user/VipList'
						});
					}
				},
				fail: err => {
					this.$api.msg('支付未成功');
					if (!this.vip) {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pagesT/order/order?state=0'
							});
						}, 100);
					}
				}
			});
			// #endif
		},
		// 获取消息模版ID
		getSettingDataByMessageId() {
			this.$u.api
				.getSettingDataByMessageId({
					id: [2]
				})
				.then(res => {
					if (res.data.length) {
						this.tmplIds = res.data.map(item => {
							return item.weixinTemplateId;
						});
					}
				});
		}
	}
};
</script>

<style lang="scss">
.app {
	width: 100%;
}

.imgLogo {
	width: 52upx;
	height: 54upx;
	border-radius: 50%;
}

.price-box {
	background-color: #fff;
	height: 265upx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 28upx;
	color: #909399;

	.price {
		font-size: 52upx;
		color: $price-color;
		font-weight: bold;
		margin-top: 12upx;
		font-family: DIN-Medium;
		&:before {
			content: '￥';
			font-size: 28upx;
		}
	}
}

.pay-type-list {
	width: 710rpx;
	margin: 20rpx auto;
	background-color: #fff;
	padding-left: 60upx;
	border-radius: 16rpx;

	.type-item {
		height: 120upx;
		padding: 20upx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-right: 60upx;
		font-size: 30upx;
		position: relative;
		.balance-tip {
			font-size: 22rpx;
			line-height: 36rpx;
			bottom: 10rpx;
			left: 0;
		}
	}

	.ibonfont {
		width: 80upx;
		font-size: 48upx;
	}

	.ibonhuodaofukuan {
		color: #fe8e2e;
	}

	.ibonweixinzhifu {
		color: #36cb59;
	}

	.ibonumidd17 {
		color: #01aaef;
	}

	.tit {
		font-size: 28rpx;
		color: $font-color-dark;
		margin-bottom: 4upx;
	}
	.user-balance {
		font-size: 24rpx;
		color: #999999;
	}
	.con {
		flex: 1;
		display: flex;
		flex-direction: column;
		font-size: $font-sm;
		color: $font-color-light;
	}
}

.mix-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 630upx;
	height: 80upx;
	margin: 80upx auto 30upx;
	font-size: $font-lg;
	color: #fff;
	background-color: #f53c28;
	border-radius: 10upx;
}
.self-shop-title {
	padding: 0 30upx;
	line-height: 88upx;
	font-weight: bold;
	font-size: 32upx;
	.ibonfont {
		color: #999;
		font-weight: 400;
	}
}
.confirm-btn {
	color: #ffffff;
	line-height: 90rpx;
	text-align: center;
}
.balance-money {
	font-size: 80rpx;
	color: $u-type-warning;
	position: relative;

	.close {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		line-height: 28rpx;
		font-size: 28rpx;
	}
}
</style>
