<template>
	<sc-dialog v-model="visible" title="修改密码" width="600" :showFullscreen="false" @close="$emit('closed')">
		<el-alert title="密码更新成功后，您将被重定向到登录页面，您可以使用新密码重新登录。" type="info" show-icon :closable="false" style="margin-bottom: 20px;"/>
		
		<el-form ref="form" :model="form" :rules="rules" label-width="100px">
			<el-form-item label="当前密码:" prop="userPassword">
				<el-input v-model="form.userPassword" type="password" show-password placeholder="请输入当前密码"></el-input>
				<div class="el-form-item-msg">必须提供当前登录用户密码才能进行更改</div>
			</el-form-item>
			<el-form-item label="新密码:" prop="newPassword">
				<el-input v-model="form.newPassword" type="password" show-password placeholder="请输入新密码"></el-input>
				<sc-password-strength v-model="form.newPassword"></sc-password-strength>
			</el-form-item>
			<el-form-item label="确认新密码:" prop="confirmNewPassword">
				<el-input v-model="form.confirmNewPassword" type="password" show-password placeholder="请再次输入新密码"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">确 定</el-button>
		</template>
	</sc-dialog>
</template>

<script>
	import scPasswordStrength from "@/components/scPasswordStrength";
	
	export default {
		components: {
			scPasswordStrength
		},

		data() {
			return {
				visible: true,
				isSaveing: false,
				
				form: {
					userPassword: "",
					newPassword: "",
					confirmNewPassword: ""
				},

				rules: {
					userPassword: [{ required: true, message: "请输入当前密码" }],
					newPassword: [{ required: true, message: "请输入新密码" }],
					confirmNewPassword: [
						{ required: true, message: "请再次输入新密码" },
						{ validator: (rule, value, callback) => {
							if (value !== this.form.newPassword) {
								callback(new Error("两次输入密码不一致"));
							} else {
								callback();
							}
						}}
					]
				}
			}
		},
		
		methods: {
			submit() {
				this.$refs.form.validate(valid => {
					if (valid) {
						this.isSaveing = true;
						this.$API.auth.updatePassword.post(this.form).then(() => {
							this.$notify.success({
								title: "提示",
								message: "密码修改成功，请重新登录",
								duration: 1500
							});
							setTimeout(() => {
								this.isSaveing = false;
								this.$TOOL.cookie.remove("TOKEN");
								this.$TOOL.data.remove("USER_INFO");
								this.$TOOL.data.remove("OA_USER_INFO");
			                    this.$TOOL.data.remove("APPLY_SQL");
								this.$router.replace({ path: "/login" });
							}, 1500);
						}).catch(() => this.isSaveing = false);
					} else {
						return false;
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.el-alert {
  width: fit-content;
  margin: auto;
}

.el-form {
  width: 80%;
  margin: 20px auto 0;
}
</style>