<template>
	<view class="content">
		<view class="select-item" @tap="navigateToSelect">
			<view class="picker-item-logol">
				<image class="picker-item-logo-left" src="/static/image/room.png"></image>
			</view>
			<view class="picker-item-label">已选房间</view>
			<view class="picker-item-content" :class="{'font-txt':add_class==1}">{{roomSelect}}</view>
			<view class="picker-item-logor">
				<image class="picker-item-logo-right" src="/static/image/right.png"></image>
			</view>
		</view>
		<view class="show-item">
			<view class="picker-item-logol">
				<image class="picker-item-logo-left" src="/static/image/elec.png"></image>
			</view>
			<view class="picker-item-label">剩余电量</view>
			<view class="picker-item-content font-txt">{{remainElec}} 度</view>
		</view>
		<view class="show-item add-money">
			<view class="add-money-show">
				<view class="picker-item-logol money-logo">
					<image class="picker-item-logo-left" src="/static/image/money.png"></image>
				</view>
				<view class="picker-item-label money-show">请选择金额</view>
			</view>
			<view class="add-money-list">
				<view class="add-money-button">
					<button class="select-submit" :data-item="10" @tap="add_money"
						:class="{'bg-color':add_class1==1}">10元</button>
				</view>
				<view class="add-money-button">
					<button class="select-submit" :data-item="20" @tap="add_money">20元</button>
				</view>
				<view class="add-money-button">
					<button class="select-submit" :data-item="30" @tap="add_money">30元</button>
				</view>
				<view class="add-money-button">
					<button class="select-submit" :data-item="50" @tap="add_money">50元</button>
				</view>
				<view class="add-money-button">
					<button class="select-submit" :data-item="100" @tap="add_money">100元</button>
				</view>
				<view class="add-money-button">
					<button class="select-submit" :data-item="200" @tap="add_money">200元</button>
				</view>
			</view>
		</view>
		<view class="show-item">
			<input type="number" class="input-money" maxlength="4" placeholder="请输入金额(1-200)" v-model:value="inputMoney"
				placeholder-class="#B3B3B3" @input="onInput" @blur="onBlur" />
		</view>
		<view class="submit-item">
			<button class="submit" :data-rooms='room' @tap="input_money">充值</button>
		</view>
		<view class="change-show" @tap="navigateToShow">
			台账管理
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				index: 0,
				roomSelect: '', //房间号
				remainElec: 0.00.toFixed(2), //剩余电量
				add_class: '', //增加class属性
				add_class1: '',
				inputMoney: '', //手动输入增加金额
				addMoney: 0, //选择充值金额
				campus: '', //校区
				sub_appid: '', //商户号
				xiaofei_items: '', // 消费记录
				ceshi: 'code',
				dorm_number: '', //房间号
				compus: '',
				test: this.$store.state.test
			}
		},
		onLoad: function() {
			// 初始化参数
			this.$store.state.building.roomSelect = '';
			this.$store.state.building.add_class = 0;
			this.$store.state.building.dorm_number = '';

			this.getCode()
		},
		onShow() {
			if (this.$store.state.building.roomSelect != '') {
				// 如果是选择宿舍号返回
				this.roomSelect = this.$store.state.building.roomSelect;
				this.add_class = this.$store.state.building.add_class;
				this.dorm_number = this.$store.state.building.dorm_number;

				if (this.roomSelect != '') {
					this.getDianLiang()
				}
			}
		},
		methods: {
			/**
			 * 获得code
			 */
			getCode(param) {
				uni.login({
					success: (res) => {
						// console.log('获得code', res);
						if (res.code) {
							this.code = res.code
							// 请求服务器，获得openid
							if (param == 'comfirm') {
								// 获取IP
								this.getIP()
							} else
								this.getOpenId()
						} else {
							uni.showToast({
								title: res.errMsg,
								icon: 'none'
							});
						}
					}
				})
			},
			/**
			 * 获取IP
			 */
			async getIP() {
				const res = await this.$myRequest({
					host: 'ip',
					url: '/',
					method: 'POST'
				})
			
				if (res) {
					// console.log(res);
					const reg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
					let ip = reg.exec(res.data);
					this.IP = ip[0]
			
					// 组合地址，发起支付
					this.jsapi()
				}
			},
			/**
			 * 请求服务器，获得openid
			 */
			async getOpenId() {
				const res = await this.$myRequest({
					host: this.ceshi,
					url: '/HotWaters/wpget_stu.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						code: this.code
					}
				})

				// console.log('获得openid', res);
				if (res.data.mess == '返回成功') {
					this.$store.state.stu_number = res.data.info[0].stu_number
					// 宿舍号
					this.dorm_number = res.data.info[0].build + res.data.info[0].dom
					// 校区
					this.compus = res.data.info[0].campus
					// 填充校区楼栋号
					this.roomSelect = this.compus + this.dorm_number.split('栋')[1]
					this.$store.state.building.roomSelect = this.roomSelect
					this.add_class = 1

					// 请求选定的月份消费记录
					this.getDianLiang()

				} else if (res.data.mess == '未查询到用户信息') {
					uni.redirectTo({
						url: '../index/index'
					});
				}
			},
			/**
			 * 取得电费额度
			 */
			async getDianLiang() {
				let res;
				res = await this.$myRequest({
					host: 'code',
					url: '/HotWaters/buildoverElec.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						'roomSelect': this.roomSelect
					}
				})

				// console.log('取得电费额度', res);
				if (res.data.mess == '0') {
					setTimeout(() => {
						this.remainElec = res.data.amount.toFixed(2)
					}, 30);
				} else {
					this.remainElec = 0.00.toFixed(2)
					// uni.showToast({
					// 	// 未获取到户号
					// 	title: res.data.mess,
					// 	duration: 2000
					// })
				}
			},

			//跳转到选择页面
			navigateToSelect() {
				uni.navigateTo({
					url: '../select/select',
				});
			},

			//跳转到台账页面
			navigateToShow(e) {
				uni.navigateTo({
					url: '../show/show',
				});
			},

			//增加固定金额
			add_money(e) {
				this.add_class1 = 0
				this.addMoney = e.currentTarget.dataset.item

				this.confirm_room('add_money')
			},
			/**
			 * 确认宿舍号
			 * @param {Object} op
			 */
			confirm_room(op) {
				// 检查房间号
				if (this.roomSelect == '') {
					uni.showToast({
						title: '请选择宿舍号',
						icon: 'success'
					})
					return
				}
				// 输入金额进行充值
				if (op == 'input_money') {
					//判断输入是否为空或不是数字
					if (this.inputMoney == '' || this.inputMoney == null) {
						uni.showToast({
							title: '请输入充值金额',
							duration: 2000
						})
						return
					}

					if (isNaN(this.inputMoney)) {
						uni.showToast({
							title: '请输入正确金额',
							duration: 2000
						})
						return
					}

					if (!this.test) { // 非测试环境
						if (this.inputMoney > 200 || this.inputMoney < 10) {
							uni.showToast({
								title: '限额10～200元',
								duration: 2000
							})
							return
						}
					}

					this.addMoney = this.inputMoney
				}
				// 确认充值对话框
				this.confirm_dialog()
			},

			// 确认充值对话框
			confirm_dialog() {
				uni.showModal({
					// title: '确定充值'+this.inputMoney+'元',
					title: '确定充值' + this.addMoney + '元',
					success: (res) => {
						if (res.confirm) {
							// 获取code
							this.getCode('comfirm')
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				})
			},
			//增加可变金额
			input_money(e) {
				// console.log(e)
				this.confirm_room('input_money')
			},
			/**
			 * 请求服务器，获取支付参数，并支付
			 */
			async jsapi() {
				const res = await this.$myRequest({
					host: this.ceshi,
					url: '/HotWaters/elPay.action',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						code: this.code,
						num: this.addMoney,
						ip: this.IP
					}
				})

				// console.log(res);
				if (res.data.pay == 'error') {
					uni.showToast({
						title: '未获得支付参数',
						icon: 'success',
						duration: 3000
					});
				} else {
					wx.requestPayment({
						timeStamp: res.data.pay.timeStamp,
						nonceStr: res.data.pay.nonceStr,
						package: 'prepay_id=' + res.data.pay.prepay_id,
						signType: res.data.pay.signType,
						paySign: res.data.pay.paySign,
						success: res => {
							if (res.errMsg == 'requestPayment:ok') {
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
							}
						},
						fail: (res) => {
							if (res.errMsg == 'requestPayment:fail cancel') {
								uni.showToast({
									title: '取消支付',
									icon: 'success',
									duration: 2000
								});
							}
						},
						complete: (res) => {
							// console.log(res);
						}
					});
				}
			},
			/**
			 * 输入充值金额
			 */
			onInput(e) {
				if (this.test) { // 测试环境
					return
				}

				const v = e.detail.value
				this.inputMoney = 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 > 200) {
						final = 200
					}
				}
				this.$nextTick(() => {
					this.inputMoney = final.toString() || '0'
				})
			},
			/**
			 * 失去焦点时
			 */
			onBlur() {
				if (this.test) { // 测试环境
					return
				}

				if (this.inputMoney < 10) {
					this.inputMoney = 10
				}
			}
		},
	}
</script>

<style>
	@import url("jiaofei.css");
</style>
