<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="80px">
    <el-form-item :label="initName('oldPwd')" prop="oldPassword">
      <el-input v-model="user.oldPassword" :placeholder="initName('enterOldPwd')" type="password" show-password/>
    </el-form-item>
    <el-form-item :label="initName('newPwd')"  prop="newPassword">
      <el-input v-model="user.newPassword" :placeholder="initName('enterNewPwd')" type="password" show-password/>
    </el-form-item>
    <el-form-item :label="initName('confirmPwd')" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" :placeholder="initName('pleaseConfirmPwd')" type="password" show-password/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="mini" @click="submit">{{ initName('save') }}</el-button>
      <el-button type="danger" size="mini" @click="close">{{ $t('common.close') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUserPwd } from "@/api/system/user";
import {translateCommon} from "../../../../utils/common";

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error(this.$t('personal.pwdNoMatch')));
      } else {
        callback();
      }
    };
    return {
      prefixLabel:"personal.",
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      // 表单校验
      rules: {
        oldPassword: [
          { required: true, message: this.$t('personal.oldPwdRequiredValidate'), trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: this.$t('personal.newPwdRequiredValidate'), trigger: "blur" },
          { min: 6, max: 20, message: this.$t('personal.lengthValidate'), trigger: "blur" },
          { pattern: /^[^<>"'|\\]+$/, message: this.$t('personal.charValidate')+  "：< > \" ' \\\ |", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message:this.$t('personal.confirmPwdRequiredValidate'), trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      },

    };
  },
  methods: {
    initName(key){
      return  translateCommon(this.prefixLabel+key)
    },
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateUserPwd(this.user.oldPassword, this.user.newPassword).then(response => {
            this.$modal.msgSuccess(this.initName('modifySuccess'));
          });
        }
      });
    },
    close() {
      this.$tab.closePage();
    }
  }
};
</script>
