<template>
  <el-dialog
    class="reset-pwd"
    :visible.sync="modalIsShow"
    title="修改密码"
    top="10vh"
    width="448px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :show-close="false"
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="resetRules"
      label-width="90px"
    >
      <el-form-item prop="password" label="新密码：">
        <el-input
          type="password"
          v-model="modalForm.password"
          placeholder="请输入新密码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="rePassword" label="再次密码：">
        <el-input
          type="password"
          v-model="modalForm.rePassword"
          placeholder="请再次输入新密码"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { resetPwd } from "../api";
import { password } from "@/plugins/formRules";

const initModalForm = {
  password: "",
  rePassword: "",
};

export default {
  name: "reset-pwd",
  data() {
    const equalToPswd = (rule, value, callback) => {
      if (this.modalForm.rePassword !== this.modalForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      resetRules: {
        password: [...password],
        rePassword: [
          ...password,
          {
            validator: equalToPswd,
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData() {
      this.modalForm = { ...initModalForm };
    },
    visibleChange() {
      this.initData();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await resetPwd(this.modalForm.password).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

      this.isSubmit = false;
      this.$message.success("修改成功！");
      this.$emit("modified", data);
      this.modalIsShow = false;
    },
  },
};
</script>
