<template>
	<view>
		<view class="password-type-2">
			<!--顶部返回按钮-->
			<text class="back-btn iconfont iconzuo" @tap="navBack"></text>
			<view class="login-top" :class="'bg-' + themeColor.name">
				<view class="desc">
					<view class="title">Hi~</view>
					<text>{{ this.$i18n.locale == 'zh' ? '找回密码' : 'RetrievePassword' }}！</text>
				</view>
				<image class="login-pic" :src="loginPic"></image>
			</view>
			<view class="login-type-content">
				<image class="login-bg" :src="loginBg"></image>
				<view class="main">
					<view class="login-type-form">
						<view class="input-item" style="display: flex;">
							<!-- <text class="iconfont iconxiangxiajiantou" :class="'text-' + themeColor.name"></text> -->
							<u-icon name="email" color="#4BC0E2" size="50"></u-icon>
							<input class="login-type-input" v-model="resetPasswordParams.email"
								:placeholder="i18n('EnterEmail')" maxlength="20" style="padding-left: 32upx;" />
						</view>

						<view class="input-item input-item-sms-code">
							<text class="iconfont iconyanzhengma" :class="'text-' + themeColor.name"></text>
							<view class="input-wrapper">
								<view class="rf-input-wrapper">
									<input type="number" class="login-type-input" v-model="resetPasswordParams.code"
										:placeholder="i18n('EnterVerification')" maxlength="6" />
								</view>
								<button class="sms-code-btn" :disabled="smsCodeBtnDisabled" @click="getSmsCode">
									<text v-if="!smsCodeBtnDisabled">{{i18n('GetVerification')}}</text>
									<text v-else class="sms-code-resend">{{codeSeconds}}s{{i18n('resend')}}</text>
									<!-- {{`重新发送 (${codeSeconds})`}}</text> -->
								</button>
							</view>
						</view>
						<view class="input-item">
							<text class="iconfont iconmimaffffffpx" :class="'text-' + themeColor.name"></text>
							<input class="login-type-input" type="password" v-model="resetPasswordParams.password"
								:placeholder="this.$i18n.locale == 'zh' ? '请输入密码':'Please input a password'"
								maxlength="20" />
						</view>
						<view class="input-item">
							<text class="iconfont iconmimaffffffpx" :class="'text-' + themeColor.name"></text>
							<input class="login-type-input" type="password"
								v-model="resetPasswordParams.password_repetition"
								:placeholder="this.$i18n.locale == 'zh' ? '请输入确认密码':'Please input a password'"
								maxlength="20" />
						</view>
					</view>
					<view class="login-type-tips">
						<view @tap="navTo('/pages/public/login')" class="forget-section">
							{{this.$i18n.locale == 'zh' ? '马上登陆' :'login'}}
						</view>
						<text @tap="toHome">{{this.$i18n.locale == 'zh' ? '返回主页' :'Home'}}</text>
					</view>
					<button class="confirm-btn" :class="'bg-' + themeColor.name" :disabled="btnLoading"
						:loading="btnLoading" @tap="restPassword">
						{{this.$i18n.locale == 'zh' ? '找回密码' : 'RetrievePassword'}}
					</button>
				</view>
			</view>
			<view class="login-type-bottom" :class="'text-' + themeColor.name">
				{{ appName }}{{this.$i18n.locale == 'zh' ? '版权所有' : 'Copyright'}}
			</view>
			<u-toast ref="uToast" />
		</view>
	</view>
</template>

<script>
	import {
		smsCode,
		updatePassword
	} from '@/api/login';
	import moment from '@/common/moment';
	export default {
		data() {
			return {
				resetPasswordParams: {
					email: '',
					password: '',
					password_repetition: '',
					code: ''
				},
				btnLoading: false,
				type: null,
				smsCodeBtnDisabled: true,
				loginBg: this.$mAssetsPath.loginBg,
				loginPic: this.$mAssetsPath.loginPic,
				appName: this.$mSettingConfig.appName,
				reqBody: {},
				codeSeconds: 0, // 验证码发送时间间隔
				second: 60,
				service: '',
				name: '',
				userInfo: [],
			};
		},
		onLoad(options) {
			const time =
				moment().valueOf() / 1000 - uni.getStorageSync('pwdSmsCodeTime');
			if (time < 60) {
				this.codeSeconds =
					this.$mConstDataConfig.sendCodeTime - parseInt(time, 10);
				this.handleSmsCodeTime(this.codeSeconds);
			} else {
				this.codeSeconds = this.$mConstDataConfig.sendCodeTime;
				this.smsCodeBtnDisabled = false;
				uni.removeStorageSync('pwdSmsCodeTime');
			}
			this.type = options.type;
		},
		methods: {
			async getSmsCode() {
				//获取当前邮箱的用户信息
				this.getUserInfo();
			},
			// 获取邮箱验证码
			async userInfoBack(e) {
				// 邮件：service：YJ
				this.service = "YJ";
				//发送验证码 判断当前是手机号还是邮箱号  短信：service：“TX"   邮件：service：“YJ
				let language = this.$i18n.locale;
				let userName = e
				console.log(userName);
				const res = await this.$myRequest({
					url: '/ums/umsUsers/Code',
					data: {
						account: userName,
						service: this.service,
						language
					},
				});
				if (res.status == '200') {
					this.handleSmsCodeTime(this.second);
					return this.$refs.uToast.show({
						title: res.msg,
						type: 'success',
					});
				} else {
					return this.$refs.uToast.show({
						title: res.msg,
						type: 'error',
					});
				}
			},
			//验证邮箱号合法性
			verificationTel(name) {
				if (!name) {
					return this.$refs.uToast.show({
						title: this.i18n('Themailboxcannotbeempty') + "！",
						type: 'warning',
					}); //邮箱号不能为空
				}
				const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
				if (regEmail.test(name)) {
					return true;
				} else {
					this.$refs.uToast.show({
						title: this.i18n('Pleaseenterlegalemail') + "！",
						type: 'warning',
					}); //请输入合法的手机号
					return false;
				}
			},
			async getUserInfo() {
				var bool = this.verificationTel(this.resetPasswordParams.email);
				if (!bool) {
					return;
				}
				//校验邮箱/验证码格式

				let userName = this.resetPasswordParams.email
				// console.log('userName==', userName)
				this.userInfoBack(userName);
				//获取当前登录邮箱号的用户信息
				// const result = await this.$myRequest({
				// 	url: '/ums/umsUsers/getByUserName',
				// 	data: {
				// 		userName: userName
				// 	}
				// });
				// if (result.status == 200 && result.data != null && result.data != "") {
				// 	this.userInfo = result.data;
				// } else {
				// 	this.$refs.uToast.show({
				// 		title: this.$i18n.locale == 'zh' ? '用户不存在' : 'user does not exist',
				// 		type: 'error',
				// 	})
				// };
			},
			handleSmsCodeTime(time) {
				let timer = setInterval(() => {
					if (time === 0) {
						clearInterval(timer);
						this.smsCodeBtnDisabled = false;
					} else {
						this.codeSeconds = time;
						this.smsCodeBtnDisabled = true;
						time--;
					}
				}, 1000);
			},
			//后台自动登录，获取token值
			async codeLogin() {
				const that = this;
				this.service = "YJ";
				const res = await this.$myRequest({
					url: '/sys/token',
					data: {},
				});
				let token = res.data;
				let VCode = this.resetPasswordParams.code;
				this.name = this.resetPasswordParams.email
				let page = {
					email: this.name,
					code: VCode,
					grant_type: 'password',
					client_id: 'client_2',
					client_secret: '1xapp',
				};
				const login = await this.$myRequest({
					url: '/ums/email/login',
					data: page,
					method: 'post',
					type: 'formData'
				});

				if (login.msg == 'ok') {
					try {
						//存储登录账号
						uni.setStorageSync('user', login.data.userInfo);
						uni.setStorageSync('Auth-Token', login.data.access_token);
						uni.setStorageSync('loginAccount', that.resetPasswordParams.email);
					} catch (e) {

					}

					this.toUpdatePassword();
				} else {
					return this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '修改失败请重新再试' :
							'Modification failed. Please try again',
						type: 'error',
					});
				}
			},
			// 更新密码
			async toUpdatePassword() {
				let Storage_data;
				let token;
				try {
					Storage_data = JSON.parse(uni.getStorageSync('user'));
					token = uni.getStorageSync('Auth-Token');
				} catch (e) {

				}
				let userId = Storage_data.umsUser.id

				if (userId == "" || userId == null) {
					return this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '系统繁忙,请稍后再试' :
							'The system is busy. Please try again later',
						type: 'warning',
					});
				}
				if (this.resetPasswordParams.password == "" || this.resetPasswordParams.password == null) {
					return this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '新密码不能为空' : 'New password cannot be empty',
						type: 'warning',
					});
				}
				if (this.resetPasswordParams.password_repetition == "" || this.resetPasswordParams
					.password_repetition == null) {
					return this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '确认密码不能为空' : 'Confirm password cannot be empty',
						type: 'warning',
					});
				}
				//判断两次密码是否一致
				if (this.resetPasswordParams.password != this.resetPasswordParams.password_repetition) {
					return this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '两次输入密码不一致' : 'The two passwords are inconsistent',
						type: 'warning',
					});
				}
				//校验密码格式
				var msg = /((?=.*\d)(?=.*\D)(?=.*[a-z])(?=.*[A-Z]))(?!^.*[\u4E00-\u9FA5].*$)^\S{8,20}$/.test(
						this.resetPasswordParams.password_repetition) ? "" : this.$i18n.locale == 'zh' ? '请输入8~20为密码' :
					'Your password strength is too low, please enter your password';
				if (msg != "") {
					return this.$refs.uToast.show({
						title: msg,
						type: 'warning',
					});
				}

				let param = JSON.stringify({
					id: userId,
					password: this.resetPasswordParams.password_repetition,
					Authorization: token
				});
				const result = await this.$myRequest({
					url: '/ums/umsUsers/changePassword',
					data: {
						param: param
					},
					method: 'post'
				});
				if (result.status == '200') {
					this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '密码修改成功，请使用新密码重新登录！' :
							'Password modified successfully, please use the new password to login again!',
						type: 'success',
					});
					uni.removeStorageSync('user');
					uni.removeStorageSync('Auth-Token');
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/public/login`
						});
					}, 2000);
				} else {
					this.$refs.uToast.show({
						title: result.msg,
						type: 'error',
					});
					try {
						uni.removeStorageSync('user');
						uni.removeStorageSync('Auth-Token');
					} catch (e) {

					}
				}
			},
			//重置密码
			async restPassword() {
				if (!this.resetPasswordParams.code) {
					this.$refs.uToast.show({
						title: this.$i18n.locale == 'zh' ? '验证码不能为空' : 'verificationCode cannot be empty',
						type: 'warning',
					});
					return;
				}
				this.codeLogin();
			},
			i18n(data) {
				return this.$t('common.' + data);
			},
			navBack() {
				this.$mRouter.back();
			},
			navTo(route) {
				this.$mRouter.push({
					route
				});
			},
			toHome() {
				this.$mRouter.reLaunch({
					route: '/pages/index/index'
				});
			},
		}
	};
</script>

<style lang="scss">
	page {
		background: $color-white;
	}

	.password-type-2 {
		width: 100%;
		position: relative;

		.back-btn {
			position: absolute;
			left: 40upx;
			z-index: 9999;
			padding-top: var(--status-bar-height);
			top: 40upx;
			font-size: 48upx;
			color: $color-white;
		}

		.login-top {
			height: 460upx;
			position: relative;

			.desc {
				position: absolute;
				top: 200upx;
				left: 40upx;
				font-size: 48upx;
				z-index: 2;

				.title {
					font-size: 48upx;
				}
			}

			.login-pic {
				position: absolute;
				width: 750upx;
				height: 270upx;
				right: 30upx;
				top: 100upx;
				z-index: 1;
			}
		}

		.login-type-content {
			position: relative;
			top: -72upx;

			.login-bg {
				width: 94vw;
				height: 114vw;
				margin: 0 3vw;
			}

			.main {
				width: 94vw;
				position: absolute;
				top: 0;
				left: 3vw;

				.nav-bar {
					display: flex;
					height: 100upx;
					justify-content: center;
					align-items: center;
					position: relative;
					z-index: 10;

					.nav-bar-item {
						flex: 1;
						display: flex;
						height: 100%;
						line-height: 96upx;
						font-size: $font-lg;
						display: flex;
						margin: 0 120upx;
						justify-content: center;
					}

					.nav-bar-item-active {
						border-bottom: 5upx solid;
					}
				}

				.login-type-form {
					width: 80%;
					margin: 50upx auto;

					.input-item {
						position: relative;
						height: 90upx;
						line-height: 90upx;
						margin-bottom: $spacing-lg;

						.iconfont {
							font-size: 50upx;
							position: absolute;
							left: 0;
						}

						.login-type-input {
							height: 90upx;
							padding-left: 80upx;
							border-bottom: 1upx solid rgba(0, 0, 0, .1);
						}

						.sms-code-btn,
						sms-code-resend {
							width: 240upx;
							font-size: $font-base - 2upx;
						}
					}
				}

				.login-type-tips {
					padding: 0 50upx;
					display: flex;
					justify-content: space-between;
				}

				.confirm-btn {
					height: 80upx;
					line-height: 80upx;
				}
			}
		}

		.login-type-bottom {
			width: 100%;
			padding-bottom: 30upx;
			text-align: center;
			font-size: $font-lg;
		}
	}
</style>
