<template>
	<view class="content">
		<view id="box"  v-if="whichPage === '1'">

			<view id="top" class="">
				<view class="top_le"></view>
				<view class="top_ri"></view>
			</view>
			<view class="title2">
				<image
						src="/static/logintitle.png"
						mode=""
						style="width: 50%;height: 90%;"
				></image>
			</view>
			<view class="title">
				<view style="background: linear-gradient(to bottom, #33bae3  0%, #1d6fb5  100%); -webkit-background-clip: text;color: transparent;"
				>垃圾清运管理系统</view>
			</view>
			<view class="login-form">
				<u--form :model="inputForm" labelWidth="100px"  labelPosition="left" :rules="rules" ref="uForm">
						<u-form-item label="手机号" borderBottom prop="username">
							<u-input border="none" v-model="inputForm.username" placeholder="请输入手机号"/>
						</u-form-item>

						<u-form-item label="验证码" borderBottom prop="loginPhoneCode">
							<u-input border="none" v-model="inputForm.loginPhoneCode" placeholder="请输入验证码"></u-input>
							<!--<u-button type="primary" @click="getLoginPushPhoneCode" :loading="!showLoginPhoneCode" style="background-color: #3595f9; width: 100px;">
								<span v-if="showLoginPhoneCode" style="color: white;">获取验证码</span>
								<span v-else class="count" style="color: white;">${loginCount} s</span>
							</u-button>-->

							<u-button type="primary" class="send" @click="getLoginPushPhoneCode" style="background-color: #3595f9; width: 100px;" :disabled="loginCounting">{{ loginCounting ? `请等待${loginCount}秒` : '获取验证码' }}</u-button>

						</u-form-item>
						<!--<u-form-item label="密码" borderBottom prop="password">
							<u-input border="none" password v-model="inputForm.password" />
						</u-form-item>
						<u-form-item label="验证码" borderBottom prop="code" v-if="passwordErrorCount >= 5">
							<u-input border="none" v-model="inputForm.code" />
							<u&#45;&#45;image :showLoading="true" :src="captchaImg" width="140px" height="40px" @click="getCaptcha"></u&#45;&#45;image>
						</u-form-item>-->
				</u--form>
			</view>
			<view class="but">
				<u-button type="primary" shape="circle" color="linear-gradient(90deg, #1989FA, #19C2FA)" @click="bindLogin" text="立即登录"></u-button>
			</view>
			<view class="fot">
				<!--<text @tap="reg_ok">免费注册</text>
				<text style="display: inline-block;width: 10vw;"></text>-->
				<!--<text @tap="openForgetPassword" style="color: #1989FA;">忘记密码</text>-->
			</view>
	</view>
		<view id="box" v-else-if="whichPage === '2'">

			<view id="top" class="">
				<view class="top_le"></view>
				<view class="top_ri"></view>
			</view>
			<view class="title">
				<view>修改密码</view>
				<view>使用账号绑定的手机号找回密码</view>
			</view>
			<view class="login-form">
				<u--form :model="inputForm" labelWidth="100px"  labelPosition="left" :rules="rules" ref="uForm">
					<u-form-item label="绑定手机号" borderBottom prop="phoneNumber">
						<u-input border="none" v-model="inputForm.phoneNumber" placeholder='请输入绑定手机号'/>
					</u-form-item>
					<u-form-item label="验证码" borderBottom prop="phoneCode">
						<u-input border="none" v-model="inputForm.phoneCode" placeholder="请输入验证码"></u-input>
						<!--<u-button type="primary" @click="pushPhoneCode" :loading="!showPhoneCode" style="background-color: #3595f9; width: 100px;">
							<span v-if="showPhoneCode" style="color: white;">获取验证码</span>
							<span v-else class="count" style="color: white;">请等待 {{count}} s</span>
						</u-button>-->
						<u-button type="primary" class="send" @click="pushPhoneCode" style="background-color: #3595f9; width: 100px;" :disabled="counting">{{ counting ? `请等待${count}秒` : '获取验证码' }}</u-button>
					</u-form-item>
					<u-form-item label="新密码" borderBottom prop="newPassword" >
						<u-input border="none" v-model="inputForm.newPassword" placeholder='请输入新密码'/>
					</u-form-item>
					<u-form-item label="确认密码" borderBottom prop="newPasswordAgain" >
						<u-input border="none" v-model="inputForm.newPasswordAgain" placeholder='请输入确认密码'/>
					</u-form-item>
				</u--form>
			</view>
			<view class="but">
				<u-button type="primary" shape="circle" color="linear-gradient(90deg, #1989FA, #19C2FA)" @click="saveNewPass" text="保存"></u-button>
			</view>
			<view class="fot">
				<!--				<text @tap="reg_ok">免费注册</text>-->
				<!--				<text style="display: inline-block;width: 10vw;"></text>-->
				<text @tap="backLogin" style="color: #1989FA;">前往登录页面</text>
			</view>
		</view>
	</view>
</template>

<script>
	import * as $auth from "@/common/auth.js"
	import loginService from "@/api/auth/loginService"
	import {mapActions} from 'vuex'
	var  graceChecker = require("@/common/graceChecker.js");
	export default {
		data() {
			return {
				showPhoneCode: true,
				loginCount: 60, // 初始化 loginCount
				loginCounting: false, // 是否正在倒计时
				counting: false, // 是否正在倒计时
				count: 60, // 初始化 count
				timer: null, // 定时器
				showLoginPhoneCode: true,
				captchaImg: '',
				inputForm: {
					'username': '',
					'password': '',
					'code': '',
					'uuid': '',
					'phoneNumber': '',
					'phoneCode': '',
					'loginPhoneCode': '',
					'newPassword': '',
					'newPasswordAgain': '',
				},
				passwordErrorCount: 0,
				whichPage: '1', // 1为登录页面，2为忘记密码页面
				rules: {
					username: [
						{
							required: true,
							message: '请输入手机号',
							trigger: ['blur', 'change']
						}
					],
					password: [
						{
							required: true,
							message: '请输入密码',
							trigger: ['blur', 'change']
						}
					],
					code: [
						{
							required: true,
							message: '请输入验证码',
							trigger: ['blur', 'change']
						}
					],
					phoneNumber: [
						{
							required: true,
							message: '请输入绑定手机号',
							trigger: ['blur', 'change']
						}
					],
					loginPhoneCode: [
						{
							required: true,
							message: '请输入登录验证码',
							trigger: ['blur', 'change']
						}
					],
					phoneCode: [
						{
							required: true,
							message: '请输入验证码',
							trigger: ['blur', 'change']
						}
					],
					newPassword: [
						{
							required: true,
							message: '请输入新密码',
							trigger: ['blur', 'change']
						}
					],
					newPasswordAgain: [
						{
							required: true,
							message: '请输入确认密码',
							trigger: ['blur', 'change']
						}
					],
				}
			}
		},
		created() {
			this.getCaptcha()
		},
		methods: {
			...mapActions(['refreshUserInfo']),
			// 登录
			bindLogin() {
				/**
				 * 客户端对账号信息进行一些必要的校验。
				 * 实际开发中，根据业务需要进行处理，这里仅做示例。
				 */
				this.$refs.uForm.validate().then(res => {
					this.inputForm.openId = uni.getStorageSync('openId');
					loginService.login(this.inputForm).then((data) => {
						this.$store.commit('SET_TOKEN',data.token);
						this.refreshUserInfo();
						// uni.reLaunch({
						// 	url: '/pages/index/index',
						// });
						this.$router.push('/pages/index/index');
					}).catch(e => {
						// 密码错误次数增加
						this.passwordErrorCount++;
						// 如果密码错误次数超过5次，显示验证码
						if (this.passwordErrorCount >= 5) {
							this.inputForm.code = ''; // 清空验证码输入框
							this.getCaptcha(); // 获取验证码
						}
						this.getCaptcha()
						console.error(e)
					})
				})
			},
			// 获取验证码
			getCaptcha () {
				loginService.getCode().then((data) => {
					this.captchaImg = 'data:image/gif;base64,' + data.codeImg
					this.inputForm.uuid = data.uuid
				})
			},
			openForgetPassword () {
				console.log('进来了')
				this.inputForm.username = ''
				this.inputForm.password = ''
				this.inputForm.code = ''
				this.$nextTick(() => {
					this.whichPage = '2' // 打开忘记密码页面
				})
			},
			backLogin () {
				this.inputForm.phoneNumber = ''
				this.inputForm.phoneCode = ''
				this.inputForm.loginPhoneCode = ''
				this.inputForm.newPassword = ''
				this.inputForm.newPasswordAgain = ''
				this.whichPage = '1' // 打开登录页面
			},
			getLoginPushPhoneCode () {
				// 验证手机号码格式是否正确
				if (this.isNotEmpty(this.inputForm.username) && this.checkLoginMobile(this.inputForm.username)) {
					// 向手机号发送验证码
					loginService.getLoginPhoneCode(this.inputForm.username).then((data) => {
						if (data.success) {
							uni.showToast({ title: data.message, icon: "success" });

							this.loginCounting = true;
							const timer = setInterval(() => {
								this.loginCount--;
								if (this.loginCount <= 0) {
									clearInterval(timer);
									this.loginCounting = false;
									this.loginCount = 60; // 重置倒计时时长
								}
							}, 1000);


							// ‘发送验证码’按钮倒计时
							/*const TIME_COUNT = 60 // 更改倒计时时间
							if (!this.timer) {
								this.loginCount = TIME_COUNT; // 设置倒计时初始值
								this.showLoginPhoneCode = false;
								this.timer = setInterval(() => {
									console.log("定时时间：",this.loginCount)
									if (this.loginCount > 0) {
										this.loginCount--;
									} else {
										this.showLoginPhoneCode = true;
										clearInterval(this.timer); // 清除定时器
										this.timer = null;
									}
								}, 1000);
							}*/

						} else {
							this.$message.error(data.message)
						}
					})
				} else {
					uni.showToast({
						title: '请填写正确的手机号',
						icon: "none",
						duration:2000
					})
				}
			},
			pushPhoneCode () {
				// 验证手机号码格式是否正确
				console.log('this.inputForm.phoneNumber', this.inputForm.phoneNumber)
				console.log('this.checkMobile(this.inputForm.phoneNumber)', this.checkMobile(this.inputForm.phoneNumber))
				if (this.isNotEmpty(this.inputForm.phoneNumber) && this.checkMobile(this.inputForm.phoneNumber)) {
					// 向手机号发送验证码
					loginService.getPhoneCode(this.inputForm.phoneNumber).then((data) => {
						if (data.success) {
							uni.showToast({ title: data.message, icon: "success" });
							// ‘发送验证码’按钮倒计时

							this.counting = true;
							const timer = setInterval(() => {
								this.count--;
								if (this.count <= 0) {
									clearInterval(timer);
									this.counting = false;
									this.count = 60; // 重置倒计时时长
								}
							}, 1000);

							/*const TIME_COUNT = 60 // 更改倒计时时间
							if (!this.timer) {
								this.count = TIME_COUNT
								this.showPhoneCode = false
								this.timer = setInterval(() => {
									if (this.count > 0 && this.count <= TIME_COUNT) {
										this.count--
									} else {
										this.showPhoneCode = true
										clearInterval(this.timer) // 清除定时器
										this.timer = null
									}
								}, 1000)
							}*/
						} else {
							this.$message.error(data.message)
						}
					})
				} else {
					uni.showToast({
						title: '请填写正确的手机号',
						icon: "none",
						duration:2000
					})
				}
			},
			checkLoginMobile (str) {
				const phone = /(^(\d{3,4}-)?\d{6,8}$)|(^(\d{3,4}-)?\d{6,8}(-\d{1,5})?$)|(^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$)/
				if (str && !phone.test(str)) {
					uni.showToast({
						title: '登陆手机号填写不正确，请重新填写',
						icon: "none",
						duration:2000
					})
					this.inputForm.username = ''
					return false;
				} else {
					return true;
				}
			},
			checkMobile (str) {
				const phone = /(^(\d{3,4}-)?\d{6,8}$)|(^(\d{3,4}-)?\d{6,8}(-\d{1,5})?$)|(^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$)/
				if (str && !phone.test(str)) {
					uni.showToast({
						title: '绑定手机号填写不正确，请重新填写',
						icon: "none",
						duration:2000
					})
					this.inputForm.phoneNumber = ''
					return false;
				} else {
					return true;
				}
			},
			isEmpty(value) {
				let result = false;
				if (value == null || value == undefined) {
					result = true;
				}
				if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
					result = true;
				}
				if (typeof value == "object" && value instanceof Array && value.length === 0) {
					result = true;
				}
				return result;
			},
			isNotEmpty (value) {
				return !this.isEmpty(value)
			},
			saveNewPass () {

				return new Promise((resolve, reject) => {

					let errors = [];

					if (this.inputForm.newPassword !== this.inputForm.newPasswordAgain) {
						errors.push('两次输入的密码不相同，请重新输入!');
					}

					if (errors.length > 0) {
						// 存在错误，显示提示信息
						errors.forEach(error => {
							uni.showToast({
								title: error,
								icon: 'none',
								duration: 1500
							});
						});
						reject('Form validation failed');
					} else {
						loginService.savePwd(this.inputForm).then((data) => {
							if (data.success) {
								this.$message.success(data.message)
								this.inputForm.username = this.inputForm.phoneNumber
								this.inputForm.newPassword = this.inputForm.newPassword
								this.backLogin() // 修改密码成功后返回登录页面
								this.loading = false
							} else {
								this.$message.error(data.message)
								this.loading = false
							}
						}).catch(() => {
							this.loading = false
						})
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	#box {
		position: relative;
		// color: $u-content-color;
	}

	.title {
		position: absolute;
		top: 35vh;
		width: 100vw;
		text-align: center;
		font-size: 28rpx;
		color: #198bfa;

	}

	.title2 {
		position: absolute;
		top: 10vh;
		width: 100vw;
		text-align: center;
		font-size: 28rpx;
		color: #198bfa;
		height: 200px;

	}

	.title view:nth-child(1) {
		height: 100px;
		font-size: 56rpx;
		font-family: PingFang SC;
		font-weight: bold;
		text-shadow: 0px 2px 24px rgba(58, 199, 118, 0.4);

	}

	.title view:nth-child(2) {
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #198BFA;
		margin-top: 5vw;
	}



	#top {
		width: 100vw;
		height: 40vh;
		position: relative;
	}

	.top_ri {
		width: 100vw;
		height: 100vw;
		background: linear-gradient(141deg, #19C0FA 0%, #198BFA 100%);
		opacity: 0.1;
		border-radius: 50%;
		position: absolute;
		right: -47vw;
		top: -37vw;
	}

	.top_le {
		width: 100vw;
		height: 100vw;
		background: linear-gradient(141deg, #19C0FA 0%, #198BFA 100%);
		opacity: 0.1;
		border-radius: 50%;
		position: absolute;
		left: -34vw;
		top: -54vw;
	}

	.inp {
		padding-left: 5vw;
		position: relative;
		top: -4vh;

	}

	.inp text {
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		margin-left: 5px;
	}


	.but {
		padding-left: 50rpx;
		padding-right: 50rpx;
		margin-top: 60rpx;
	}

	.fot {
		width: 100vw;
		height: 26px;
		text-align: center;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #8E8E8E;
		margin-top: 20px;
	}
	.login-form {
		padding-left: 100rpx;
		padding-right: 30rpx;
	}
</style>
