<template>
	<view class="content">
		<view class="title">
			<text class="iconfont icon-qian"></text>
			<text>江西南昌交通学院</text>
		</view>
		<view class="input_amount">
			<view class="amount_tip">充值金额（元）</view>
			<view class="amount_inp">
				<text></text>
				<input type="number" maxlength="3" v-model="amount" @input="onInput" @blur="onBlur"
					placeholder="请输入大于10,小于100元" placeholder-class="ph_class" />
			</view>
			<text>最多可输入金额100元</text>
		</view>
		<view class="amount_select">
			<view class="amount_btn">
				<text @tap="sel_amount(10)" :class="{selStyle:amount == 10}">充10元</text>
				<text @tap="sel_amount(20)" :class="{selStyle:amount == 20}">充20元</text>
				<text @tap="sel_amount(50)" :class="{selStyle:amount == 50}">充50元</text>
				<text @tap="sel_amount(100)" :class="{selStyle:amount == 100}">充100元</text>
			</view>
			<view class="reminder">温馨提示：最少充值金额为10元</view>
			<view class="payment">支付金额：<text>{{amount}}</text>元</view>
			<button class="btn_submit" type="primary" @tap="chongzhi">确认提交</button>
			<button class="btn_tel" type="default" @tap="callPhone">客服热线：{{phone_number}}</button>
			<view class="tips">
				尊敬的用户，你好！因项目提现业务配置问题导致您无法提现对此，我们深表歉意！您可致电运营商处理提现问题，运营商电话：13645689854。感谢您对我们工作的支持和理解。
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				amount: 10.0.toFixed(0), // 金额
				phone_number: '13645689854', // 客户热线电话
				userinfo: '', // 用户信息
				order_id: '', // 订单号
				pay_info: '', // 支付参数。将此参数透传给支付 SDK 发起支付
				access_token: ''
			};
		},
		onLoad(options) {
			try {
				// 获取存储的用户数据
				const value = uni.getStorageSync('userinfo_storage_key')
				let item = decodeURIComponent(options.item)
				if (item === '{}' && value == '') { // 如果没有用户信息，返回首页
					uni.redirectTo({
						url: '../index/index'
					});
					return;
				}
				// 先用传过来的用户信息
				if (item != '') {
					// 处理JSON字符串
					// this.userinfo = item.replace(/"/g, "'");
					this.userinfo = JSON.parse(item)
					// 更新存储的用户信息
					uni.setStorageSync('userinfo_storage_key', this.userinfo)
				} else if (value != '') {
					// 处理JSON字符串
					// this.userinfo = value.replace(/"/g, "'");
					this.userinfo = value;
				}
			} catch (e) {
				console.log(e)
			}

			// 获取应用有效凭证
			this.get_valid_credentials()
		},
		methods: {
			/**
			 * 获取应用有效凭证
			 */
			async get_valid_credentials() {
				const res = await this.$myRequest({
					host: 'wecard',
					url: '/cgi-bin/oauth2/token',
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {
						'app_key': this.userinfo.appkey,
						'app_secret': this.userinfo.app_secret,
						'grant_type': 'client_credentials',
						'scope': 'base',
						'ocode': this.userinfo.ocode
					}
				});

				if (typeof(res.data.access_token) != 'undefined') {
					// 获取到应用有效凭证，保存到页面变量中
					this.access_token = res.data.access_token
				} else {
					uni.showToast({
						title: '获取凭证失败',
						duration: 2000
					})
				}
			},
			/**
			 * 组合地址，发起支付
			 */
			async jsapi() {
				const res = await this.$myRequest({
					host: 'wecard',
					url: '/cgi-bin/pay/app/mppay',
					method: 'POST',
					header: {
						'content-type': 'application/json'
					},
					data: {
						'access_token': this.access_token,
						'sub_appid': this.userinfo.sub_appid,
						'user_id': this.userinfo.card_number,
						'order_id': this.order_id = get_order_id(),
						'amount': this.amount * 100
					}
				})
				console.log(this.access_token)
				console.log(this.userinfo.sub_appid)
				console.log(this.userinfo.card_number)
				console.log(this.order_id)
				console.log(this.amount)
				console.log(res.data)
				if (res.data.code == 0) {
					this.pay_info = res.data.data.pay_info
					// 发起支付
					this.pay_amount()
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.message,
						duration: 3000
					})
				}
			},
			// 调起支付
			pay_amount() {
				var OpenMidas = require("@/static/openMidas.js") // 引入小程序目录下的SDK文件
				
				// 设置支付配置
				wx['OpenMidasConfig'] = {
				    apiCommonConf: {
				        version: "weixiao"
				    },
				    cgiDomain: {
				        test: "midas.weixiao.qq.com/api",  // 私有化参数联系微卡客服进行获取
				    },
				    webDomain: "https://midas.weixiao.qq.com/h5",// 私有化参数联系微卡客服进行获取
				    sandboxWebDomain: "https://midas.weixiao.qq.com/h5"// 私有化参数联系微卡客服进行获取
				}
				
				var payInfo = this.pay_info; // 请求mppay接口返回的数据
				var appMetaData = "app=test&version=1.1"; // 自定义回调数据
				
				OpenMidas.init("test");
				OpenMidas.pay(
				  payInfo,
				  function(resultCode, innerCode, resultMsg, appMetaData) {
				    console.log(resultCode); // 支付响应状态码
				    console.log(innerCode); // 支付响应内部错误码
				    console.log(resultMsg); // 支付响应说明
				    console.log(appMetaData); // 自定义回调数据
				
				    // todo：处理业务逻辑
				  },
				  appMetaData
				)
			},
			/**
			 * 输入充值金额
			 */
			onInput(e) {
				const v = e.detail.value
				this.amount = 10

				const zero = /^(0{1,})|[^0-9]/g
				let final = 0
				if (!v) {
					final = 0
				} else {
					final = v.toString().replace(zero, (v) => {
						return 0
					})

					if (final.split('')[0] * 1 === 0) {
						final = final.slice(1) - 0 || 0
					}

					if (final > 100) {
						final = 100
					}
				}
				this.$nextTick(() => {
					this.amount = final.toString() || '0'
				})
				// setTimeout(() => {
				// 	this.amount = final.toString() || '0'
				// }, 100)
			},
			onBlur() {
				if (this.amount < 10) {
					this.amount = 10
				}
			},
			/**
			 * 选择充值金额
			 */
			sel_amount(m) {
				this.amount = m
			},
			/**
			 * 调用接口实现充值功能
			 */
			chongzhi() {
				if (this.amount < 10 || this.amount > 100) {
					uni.showToast({
						icon: 'none',
						title: '最少充值10元，最多充值100元！',
						mask: true,
						duration: 3000
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '您选择了充值：￥' + this.amount + ' 元',
						cancelText: '算了',
						confirmText: '充值',
						success: (res) => {
							if (res.confirm) {
								// 组合地址，发起支付
								this.jsapi()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					})
				}
			},
			/**
			 * 拨打电话
			 */
			callPhone() {
				uni.makePhoneCall({
					phoneNumber: this.phone_number
				});
			}
		}
	}
	/**
	 * 时间生成订单号
	 */
	function get_order_id() {
		const date = new Date()

		let year = date.getFullYear()
		let month = date.getMonth() + 1
		let day = date.getDate()
		let hour = date.getHours()
		let minute = date.getMinutes()
		let second = date.getSeconds()
		let millisecond = date.getMilliseconds()

		month = month > 9 ? month : '0' + month
		day = day > 9 ? day : '0' + day
		second = second > 9 ? second : '0' + second
		// 小于4位数，前补0
		millisecond = millisecond.length < 3 ? '0' + millisecond : millisecond

		return `${year}${month}${day}${hour}${minute}${second}${millisecond}`
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		background-color: #F5F5F5;
		width: 750rpx;
		// height: 100%;
		// align-items: stretch;

		.title {
			display: flex;
			align-items: center;
			padding: 40rpx;

			text:nth-child(1) {
				color: $my-color-primary;
				font-size: 50rpx;
			}

			text:nth-child(2) {
				font-size: 32rpx;
				margin-left: 15rpx;
				font-family: Microsoft YaHei-3970(82674968);
				color: #333333;
			}
		}

		.input_amount {
			background-color: #FFFFFF;
			width: 670rpx;
			height: 210rpx;
			padding: 40rpx 40rpx 0 40rpx;
			border-radius: 40rpx 40rpx 0 0;

			.amount_tip {
				font-size: 32rpx;
				font-family: Microsoft YaHei-3970(82674968);
			}

			.amount_inp {
				display: flex;
				flex-direction: row;
				border-bottom: 1px solid #cccccc;
				margin-top: 20rpx;
				margin-bottom: 10rpx;

				text {
					width: 50rpx;
					height: 74rpx;
					font-size: 50rpx;
					font-weight: bold;
					padding-top: 6rpx;
					font-family: Microsoft YaHei-3970(82674968);
				}

				text::before {
					content: '￥';
				}

				input {
					width: 620rpx;
					height: 80rpx;
					font-size: 50rpx;
					font-weight: bold;
					font-family: Microsoft YaHei-3970(82674968);
				}

				/deep/.ph_class {
					font-size: 28rpx;
					font-weight: normal;
				}
			}

			text {
				font-size: 26rpx;
				font-family: Microsoft YaHei-3970(82674968);
				font-weight: 500;
			}
		}

		.amount_select {
			padding: 40rpx;

			.amount_btn {
				display: flex;
				justify-content: space-between;
				margin: 30rpx 0 20rpx;

				text {
					width: 150rpx;
					height: 120rpx;
					line-height: 120rpx;
					font-size: 32rpx;
					font-family: Microsoft YaHei-3970(82674968);
					color: #333333;
					text-align: center;
					background: #FFFFFF;
					border: 3rpx solid #AAAAAA;
				}

				.selStyle {
					border: 0rpx;
					width: 156rpx;
					height: 126rpx;
					background: url(../../static/images/jinebeijing2x.png) 0rpx 0rpx no-repeat;
					background-size: 100%;
				}
			}

			.reminder {
				height: 26rpx;
				font-size: 26rpx;
				font-family: Microsoft YaHei-3970(82674968);
				color: $my-color-primary;
			}


			.payment {
				margin-top: 65rpx;
				font-size: 32rpx;
				font-family: Microsoft YaHei-3970(82674968);
				color: #333333;

				text {
					color: $my-color-primary;
				}
			}

			button {
				margin-top: 38rpx;
			}

			.btn_submit {
				border-radius: 10rpx;
				background-color: $my-color-primary;
				font-family: Microsoft YaHei-3970(82674968);
				color: #FFFFFF;
			}

			.btn_tel {
				border-radius: 10rpx;
				background: #CCCCCC;
				font-family: Microsoft YaHei-3970(82674968);
				color: #FFFFFF;
			}

			.tips {
				margin-top: 20rpx;
				font-size: 24rpx;
				font-family: Microsoft YaHei-3970(82674968);
				color: $my-color-primary;
				line-height: 36rpx;
			}
		}
	}
</style>
