<template>
	<div class="login-form-wrapper">
		<div class="login_config">
			<!--<el-dropdown trigger="click" placement="bottom-end">
				<el-button circle text>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						xmlns:xlink="http://www.w3.org/1999/xlink"
						aria-hidden="true"
						role="img"
						width="1em"
						height="1em"
						preserveAspectRatio="xMidYMid meet"
						viewBox="0 0 512 512"
					>
						<path
							d="M478.33 433.6l-90-218a22 22 0 0 0-40.67 0l-90 218a22 22 0 1 0 40.67 16.79L316.66 406h102.67l18.33 44.39A22 22 0 0 0 458 464a22 22 0 0 0 20.32-30.4zM334.83 362L368 281.65L401.17 362z"
							fill="currentColor"
						></path>
						<path
							d="M267.84 342.92a22 22 0 0 0-4.89-30.7c-.2-.15-15-11.13-36.49-34.73c39.65-53.68 62.11-114.75 71.27-143.49H330a22 22 0 0 0 0-44H214V70a22 22 0 0 0-44 0v20H54a22 22 0 0 0 0 44h197.25c-9.52 26.95-27.05 69.5-53.79 108.36c-31.41-41.68-43.08-68.65-43.17-68.87a22 22 0 0 0-40.58 17c.58 1.38 14.55 34.23 52.86 83.93c.92 1.19 1.83 2.35 2.74 3.51c-39.24 44.35-77.74 71.86-93.85 80.74a22 22 0 1 0 21.07 38.63c2.16-1.18 48.6-26.89 101.63-85.59c22.52 24.08 38 35.44 38.93 36.1a22 22 0 0 0 30.75-4.9z"
							fill="currentColor"
						></path>
					</svg>
				</el-button>
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item @click="changeLanguage('zh')"
							>中文</el-dropdown-item
						>
						<el-dropdown-item @click="changeLanguage('en')"
							>EngLish</el-dropdown-item
						>
						<el-dropdown-item @click="changeLanguage('ja')"
							>日本語</el-dropdown-item
						>
					</el-dropdown-menu>
				</template>
</el-dropdown>-->
		</div>
		<div v-if="whichPage === '1'" class="login-border">
			<div class="login-form-title">登录</div>
			<div class="login-form-sub-title">{{ $t2("t_login_description") }}</div>
			<div class="login-form-error-msg">{{ errorMessage }}</div>
			<el-form ref="loginForm" :model="inputForm" size="large" :rules="rules" class="login-form"
				@keyup.enter="login()" @submit.prevent>
				<el-form-item prop="username">
					<el-input prefix-icon="user" placeholder="请输入账号" clearable v-model="inputForm.username"
						@blur="getLoginCodeNumber($event.target.value)"></el-input>
				</el-form-item>
				<el-form-item prop="password">
					<el-input type="password" prefix-icon="lock" placeholder="请输入密码" clearable
						v-model="inputForm.password"></el-input>
				</el-form-item>


				<el-form-item>
					<el-row :gutter="10" v-if="inputForm.isShow">
						<el-col :span="16">
							<el-form-item prop="code">
								<el-input placeholder="请输入验证码" v-model="inputForm.code" text clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8"><el-image @click="getCaptcha" :src="captchaImg"
								style="height: 34px"></el-image></el-col>
					</el-row>
				</el-form-item>

				<el-form-item>
					<div style="width: 100%">
						<div style="margin-left: 5px;margin-bottom: 20px; float: left;height: 40px;line-height:40px;">
							<!-- 记住我 -->
							<el-checkbox v-model="checked" class="rememberMe">记住我</el-checkbox>
						</div>
						<!-- 找回密码 -->
						<div style="float:right;margin-bottom: 20px;margin-right: 5px;color: #1890ff;">
							<el-button style="float: right" type="text" @click="openForgetPassword"
								class="forgetPw">忘记密码</el-button>
						</div>
					</div>

				</el-form-item>

				<el-form-item>
					<el-button type="primary" :loading="loading" class="login-submit" @click="login"
						:disabled="isLoginDisabled">登录</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div v-else-if="whichPage === '2'" class="login-border">
			<div class="login-main">
				<div class="login-form-title">修改密码</div>
				<div class="login-form-sub-title">使用账号绑定的手机号找回密码</div>
				<el-form size="large" ref="loginForm2" :model="inputForm" :loading="loading" :rules="rules"
					class="login-form" @keyup.enter.native="saveNewPass()" @submit.native.prevent>
					<el-form-item prop="phoneNumber">
						<el-input type="text" placeholder="请输入绑定手机号" v-model="inputForm.phoneNumber"></el-input>
					</el-form-item>
					<el-form-item prop="phoneCode">
						<el-input type="text" placeholder="请输入验证码" v-model="inputForm.phoneCode"
							style="width: 300px"></el-input>
						<el-button slot="append" 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>
						</el-button>
					</el-form-item>
					<el-form-item prop="newPassword" :error="passwordError">
						<el-input type="password" placeholder="新密码" v-model="inputForm.newPassword"
							@input="validatePassword"></el-input>
					</el-form-item>
					<el-form-item prop="newPasswordAgain">
						<el-input type="password" placeholder="确认密码" v-model="inputForm.newPasswordAgain"></el-input>
					</el-form-item>
					<el-form-item style="float:right;margin-bottom: 20px;color: #1890ff;">
						<!-- 返回登录页面 -->
						<div>
							<el-button type="text" @click="backLogin()" class="forgetPw">前往登录页面</el-button>
						</div>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" :loading="loading" class="login-submit"
							@click="saveNewPass">保存</el-button>
					</el-form-item>


				</el-form>
			</div>
		</div>
	</div>

</template>

<script>
import config from "@/config";
import loginService from "@/api/auth/loginService";
import userService from "@/api/sys/userService";
import tenantService from "@/api/sys/tenantService";

//在运用页面引入
import { Base64 } from 'js-base64' //引入base64加密，用于记住密码
export default {
	data() {
		return {
			time: "",
			logo: "",
			productName: "",
			loading: false,
			isShow: false,
			captchaImg: "",
			checked: false,
			inputForm: {
				username: "",
				password: "",
				uuid: "",
				captcha: "",
				/*修改密码*/
				phoneNumber: '',
				phoneCode: '',
				oldPassword: '',
				newPassword: '',
				newPasswordAgain: ''
			},
			rules: {
				username: [
					{
						required: true,
						message: "帐号不能为空",
						trigger: "blur",
					},
				],
				password: [
					{
						required: true,
						message: "密码不能为空",
						trigger: "blur",
					},
				],
				code: [
					{
						required: true,
						message: "验证码不能为空",
						trigger: "blur",
					},
				],
				phoneNumber: [
					{ required: true, message: '手机号不能为空', trigger: 'blur' }
				],
				phoneCode: [
					{ required: true, message: '验证码不能为空', trigger: 'blur' }
				],
				oldPassword: [
					{ required: true, message: '旧密码不能为空', trigger: 'blur' }
				],
				newPassword: [
					{ required: true, message: '新的密码不能为空', trigger: 'blur' },
					{
						validator: (rule, value, callback) => {
							const passwordRegex = /^(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*\d))|(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*[!@#$%^&*.,]))|(?=(.*[A-Z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))|(?=(.*[a-z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))[A-Za-z\d!@#$%^&*.,]{8,20}$/;

							if (!value) {
								callback(new Error('新的密码不能为空'));
							} else if (!passwordRegex.test(value)) {
								callback(new Error('密码必须包含大写字母、小写字母、数字或特殊字符中的三种，且长度为8到20个字符'));
							} else {
								callback(); // 验证通过
							}
						},
						trigger: 'blur'
					}
				],
				newPasswordAgain: [
					{ required: true, message: '再次输入的新密码不能为空', trigger: 'blur' },
					{
						validator: (rule, value, callback) => {
							const passwordRegex = /^(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*\d))|(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*[!@#$%^&*.,]))|(?=(.*[A-Z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))|(?=(.*[a-z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))[A-Za-z\d!@#$%^&*.,]{8,20}$/;

							if (!value) {
								callback(new Error('确认密码不能为空'));
							} else if (!passwordRegex.test(value)) {
								callback(new Error('密码必须包含大写字母、小写字母、数字或特殊字符中的三种，且长度为8到20个字符'));
							} else {
								callback(); // 验证通过
							}
						},
						trigger: 'blur'
					}
				]
			},
			captchaPath: "",
			whichPage: '1', // 1为登录页面，2为忘记密码页面
			showPhoneCode: true,
			count: '', // 初始化次数
			timer: null,
			passwordError: '', // 保存错误信息
			isLoginDisabled: false, //登录按钮禁用状态
		};
	},
	created() {
		this.$cookies.remove(config.TOKEN);
		this.$TOOL.data.remove("DICT_LIST");
		this.$TOOL.data.remove("TENANT_LIST");
		this.$TOOL.data.remove("IS_PRIMARY_TENANT");
		this.$TOOL.data.remove(config.TOKEN);
		this.$TOOL.data.remove("USER_INFO");
		this.$TOOL.data.remove("MENU");
		this.$TOOL.data.remove("PERMISSIONS");
		this.$TOOL.data.remove("grid");
		this.$store.commit("clearViewTags");
		this.$store.commit("clearKeepLive");
		this.$store.commit("clearIframeList");
	},
	mounted() {

		this.getCookie()
		// this.getCaptcha();
		if (this.inputForm.username) {
			this.getLoginCodeNumber(this.inputForm.username)
		}
	},
	computed: {
		appName() {
			return this.$store.state.global.appName;
		},
	},
	methods: {
		// 验证密码的函数
		validatePassword() {
			const password = this.inputForm.newPassword;
			const passwordRegex = /^(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*\d))|(?=(.*[A-Z]))(?=(.*[a-z]))(?=(.*[!@#$%^&*.,]))|(?=(.*[A-Z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))|(?=(.*[a-z]))(?=(.*\d))(?=(.*[!@#$%^&*.,]))[A-Za-z\d!@#$%^&*.,]{8,20}$/;

			if (!passwordRegex.test(password)) {
				this.passwordError = '密码必须包含大写字母、小写字母、数字或特殊字符中的三种，且长度为8到20个字符';
			} else {
				this.passwordError = ''; // 验证通过，清空错误信息
			}
		},
		// 提交表单
		async login() {
			var checked = this.checked
			var password = this.inputForm.password
			var username = this.inputForm.username
			this.$refs.loginForm.validate((valid) => {
				if (valid) {
					this.loading = true;
					loginService
						.login(this.inputForm)
						.then(async (loginResp) => {
							this.$TOOL.data.set(config.TOKEN, loginResp.token);
							this.$cookies.set(
								config.TOKEN,
								loginResp.token,
								-1
							);
							let { user } = await userService.info();
							this.$TOOL.data.set("USER_INFO", user);
							this.$store.commit("user/updateUser", user);
							let isPrimaryTenant = user.tenantDTO.id === "10000";
							this.$TOOL.data.set(
								"IS_PRIMARY_TENANT",
								isPrimaryTenant
							);
							if (isPrimaryTenant) {
								tenantService.list().then((data) => {
									this.$TOOL.data.set(
										"TENANT_LIST",
										data.records
									);
								});
							}
							let { menuList, permissions, dictList } =
								await userService.getMenus();
							if (menuList.length == 0) {
								this.loading = false;
								this.$alert(
									"当前用户无任何菜单权限，请联系系统管理员",
									"无权限访问",
									{
										type: "error",
										center: true,
									}
								);
								return false;
							}
							this.$TOOL.data.set("MENU", menuList);
							this.$TOOL.data.set("PERMISSIONS", permissions);
							this.$TOOL.data.set("DICT_LIST", dictList);

							// let Base64 = require('js-base64').Base64
							/* ------ 账号密码的存储 ------ */
							if (checked) {
								// eslint-disable-next-line no-undef
								// let password = Base64.encode(passwordLogin) // base64加密
								this.setCookie(Base64.encode(username), Base64.encode(password), 7)
							} else {
								this.setCookie('', '', -1) // 修改2值都为空，天数为负1天就好了
							}
							/* ------ http登录请求 ------ */
							this.$notify({
								title: "登录成功",
								message: `欢迎回来！<br/>你上次的登录IP是 ${loginResp.oldLoginIp}，登录时间是 ${loginResp.oldLoginDate}。`,
								dangerouslyUseHTMLString: true,
								duration: 10000,
								type: "success",
							});
							this.$router.replace({
								path: "/",
							});
						})
						.catch(() => {
							this.loading = false;
							this.getLoginErrorMethod();
						});
				}
			});
		},
		configTheme() {
			this.config.theme =
				this.config.theme == "default" ? "dark" : "default";
		},
		configLang(command) {
			this.config.lang = command.value;
		},
		// 获取验证码
		getCaptcha() {
			loginService.getCode().then((data) => {
				this.captchaImg = "data:image/gif;base64," + data.codeImg;
				this.inputForm.uuid = data.uuid;
			});
		},
		//登陆失败时访问的方法
		getLoginErrorMethod() {
			loginService.getCode().then((data) => {
				this.captchaImg = "data:image/gif;base64," + data.codeImg;
				this.inputForm.uuid = data.uuid;
			});
			if (this.inputForm.username) {
				loginService.getLoginCodeNumber(this.inputForm.username).then((data) => {
					if (data.redisLoginNumber >= data.loginNumber) {
						this.inputForm.isShow = true
					} else {
						this.inputForm.isShow = false
					}
				})
			}
		},
		// 获取验证码
		getLoginCodeNumber(username) {
			loginService.getLoginCodeNumber(username).then((data) => {
				if (data.redisLoginNumber >= data.loginNumber) {
					if (data.redisLoginNumber >= 5 && data.redisLoginNumber < 10) {
						if (!this.inputForm.isShow) {
							this.getCaptcha()
							this.inputForm.isShow = true
							this.isLoginDisabled = false
						}
					} else if (data.redisLoginNumber >= 10) {
						this.inputForm.isShow = false
						this.isLoginDisabled = true
						this.$message.error('当日登录已达最大次数,请明天再登录')

					}

				} else {
					this.isLoginDisabled = false
					this.inputForm.isShow = false
				}
			})
		},
		// 设置cookie
		setCookie(username, password, days) {
			let date = new Date() // 获取时间
			date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * days) // 保存的天数
			// 字符串拼接cookie
			window.document.cookie =
				'username' + '=' + username + ';path=/;expires=' + date.toGMTString()
			window.document.cookie =
				'password' + '=' + password + ';path=/;expires=' + date.toGMTString()
		},

		// 读取cookie 将用户名和密码回显到input框中
		getCookie() {
			// let Base64 = require('js-base64').Base64
			if (document.cookie.length > 0) {
				let arr = document.cookie.split('; ') // 分割成一个个独立的“key=value”的形式
				for (let i = 0; i < arr.length; i++) {
					let arr2 = arr[i].split('=') // 再次切割，arr2[0]为key值，arr2[1]为对应的value
					if (arr2[0] === 'username') {
						this.inputForm.username = Base64.decode(arr2[1])// base64解密
					} else if (arr2[0] === 'password') {
						// eslint-disable-next-line no-undef
						this.inputForm.password = Base64.decode(arr2[1])// base64解密
						this.checked = true
					}
				}
			}
		},
		// 切换语言
		changeLanguage(language) {
			this.$TOOL.data.set("APP_LANG", language);
			this.$store.commit("updateLanguage", language);
		},
		openForgetPassword() {
			this.inputForm.username = ''
			this.inputForm.password = ''
			this.inputForm.code = ''
			this.$refs.loginForm.resetFields()
			this.$nextTick(() => {
				this.whichPage = '2' // 打开忘记密码页面
			})
		},
		backLogin() {
			this.inputForm.phoneNumber = ''
			this.inputForm.phoneCode = ''
			this.inputForm.newPassword = ''
			this.inputForm.newPasswordAgain = ''
			this.$refs.loginForm2.resetFields()
			this.whichPage = '1' // 打开登录页面
		},
		pushPhoneCode() {
			// 验证手机号码格式是否正确
			if (this.commonJS.isNotEmpty(this.inputForm.phoneNumber) && this.validateXG.isMobile(this.inputForm.phoneNumber)) {
				// 向手机号发送验证码
				loginService.getPhoneCode(this.inputForm.phoneNumber).then((data) => {
					if (data.success) {
						this.$message.success(data.message)
						// ‘发送验证码’按钮倒计时
						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 {
				this.$message.error('请填写正确的手机号')
			}
		},
		saveNewPass() {
			this.loading = true
			this.$refs['loginForm2'].validate((valid) => {
				if (valid) {
					if (this.inputForm.newPassword !== this.inputForm.newPasswordAgain) {
						this.loading = false
						this.$message.error('两次输入的密码不相同，请重新输入!')
						throw new Error('两次输入的密码不相同，请重新输入!')
					}
					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
					})
				} else {
					this.loading = false
				}
			})
		},

	},
};
</script>

<style lang="less" scoped>
.login_config {
	position: absolute;
	top: 60px;
	right: 60px;
}

.login-form {
	&-wrapper {
		width: 400px;
	}

	&-title {
		text-align: center;
		color: #475055;
		font-weight: 500;
		font-size: 24px;
		line-height: 32px;
	}

	&-sub-title {
		text-align: center;
		color: #86909c;
		font-size: 14px;
		line-height: 34px;
	}

	&-error-msg {
		height: 32px;
		color: rgb(var(--red-6));
		line-height: 32px;
	}

	&-password-actions {
		display: flex;
		justify-content: space-between;
	}

	&-register-btn {
		color: #86909c !important;
	}

	.login-submit {
		width: 100%;
		color: #fff;
		font-size: 16px;
		background-color: #1890ff;
		border-color: #1890ff;
	}


}
</style>
