<template>
  <div class='personal-pwd'>
    <el-form ref='form' :model='form' :rules='rules' class='pass-form' label-position='top'>
      <el-form-item label='新密码' prop='newPwd'>
        <el-input v-model='form.newPwd' type='password' maxlength='20' placeholder='请输入新密码' />
      </el-form-item>
      <el-form-item label='确认密码' prop='agnPwd'>
        <el-input v-model='form.agnPwd' type='password' maxlength='20' placeholder='请输入确认密码' />
      </el-form-item>
    </el-form>
    <div class='tips'>*密码长度在 8 到 20 个字符，至少1个字母，1个数字和1个特殊字符</div>
    <div class='button-box'>
      <el-button type='primary' @click='onSubmit'>确定</el-button>
    </div>
  </div>
</template>

<script>
import { updateUserPwd } from '@api/upms/api-user';
import { encryptByAES } from '@utils/util';

export default {
  name: 'PersonalPwd',
  components: {},
  computed: {},
  props: {},
  data() {
    const checkRePassword = (rule, value, callback) => {
      if (value !== this.form.newPwd) {
        return callback(new Error('确认密码与新密码不一致'));
      }
      return callback();
    };
    return {
      form: {},
      rules: {
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message: '长度在 8 到 20 个字符',
            trigger: 'blur'
          },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()?+-.])[A-Za-z\d!@#$%^&*()?+-.]{8,}$/,
            message: '密码至少1个字母，1个数字和1个特殊字符',
            trigger: 'blur'
          }
        ],
        agnPwd: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message: '长度在 8 到 20 个字符',
            trigger: 'blur'
          },
          { validator: checkRePassword, trigger: 'blur' },
          {
            pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()?+-.])[A-Za-z\d!@#$%^&*()?+-.]{8,}$/,
            message: '密码至少1个字母，1个数字和1个特殊字符',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    onSubmit() {
      let vm = this;
      vm.$refs.form.validate((valid) => {
        if (valid) {
          let params = {
            newPwd: encryptByAES(vm.form.newPwd),
            agnPwd: encryptByAES(vm.form.agnPwd)
          };
          updateUserPwd(params).then(
            (res) => {
              if (res.code === 200) {
                vm.$message.success('修改密码成功');
              } else {
                vm.$message.error(res.msg);
              }
            },
            (error) => {
              vm.$message.success(error.msg);
            }
          );
        }
      });
    }
  }
};
</script>

<style lang='less' scoped>
.personal-pwd {
  .tips {
    margin-top: 30px;
    background-color: @theme-light-color + 10;
    color: @theme-gray-color;
    padding: 10px 20px;
    border-radius: 4px;
    font-size: 14px;
  }

  .button-box {
    padding-top: 50px;
  }
}
</style>
