<template>
	<el-card shadow="never" header="修改密码">
		<el-alert title="密码更新成功后，您将被重定向到登录页面，您可以使用新密码重新登录。" type="info" show-icon style="margin-bottom: 15px;"/>
		<el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin-top:20px;">
			<el-form-item label="当前密码" prop="old_password">
				<el-input v-model="form.old_password" type="password" show-password placeholder="请输入当前密码"></el-input>
				<div class="el-form-item-msg">必须提供当前登录用户密码才能进行更改</div>
			</el-form-item>
			<el-form-item label="新密码" prop="new_password">
				<el-input v-model="form.new_password" type="password" show-password placeholder="请输入新密码"></el-input>
				<pi-password-strength v-model="form.new_password"></pi-password-strength>
				<div class="el-form-item-msg">请输入包含英文、数字的6位以上密码</div>
			</el-form-item>
			<el-form-item label="确认新密码" prop="confirm_password">
				<el-input v-model="form.confirm_password" type="password" show-password placeholder="请再次输入新密码"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="save">保存密码</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import piPasswordStrength from '@/components/piPasswordStrength'

export default {
	components: {
		piPasswordStrength
	},
	data() {
		return {
			form: {
				old_password: "",
				new_password: "",
				confirm_password: ""
			},
			rules: {
				old_password: [
					{ required: true, message: '请输入当前密码'}
				],
				new_password: [
					{ required: true, message: '请输入新密码'},
					{ min: 6, max: 30, message: '密码长度在6-30位之间' },
					{validator: (rule, value, callback) => {
							if(value === this.form.old_password) {
								callback(new Error('新旧密码不能一致'));
							} else {
								callback();
							}
						}}
				],
				confirm_password: [
					{ required: true, message: '请再次输入新密码'},
					{ min: 6, max: 30, message: '密码长度在6-30位之间' },
					{validator: (rule, value, callback) => {
							if (value !== this.form.new_password) {
								callback(new Error('两次输入密码不一致'));
							} else {
								callback();
							}
						}}
				]
			}
		}
	},
	methods: {
		async save(){
			// 校验登录
			const validate = await this.$refs.form.validate().catch(() => {});
			if(!validate){ return false }
			const res = await this.$API.auth.editPwd({
				old_password: this.$TOOLS.crypto.MD5(this.form.old_password),
				new_password: this.$TOOLS.crypto.MD5(this.form.new_password)
			})
			this.$message.success(res.msg)
			this.$TOOLS.data.clear()
			this.$router.replace({ path: '/login' })
		}
	}
}
</script>

<style>
</style>
