<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
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="resetRules"
      label-position="top"
    >
      <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 { resetUserPassword } from "@/api/system-user";

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

export default {
  name: "reset-pwd",
  data() {
    const equalToPswd = (rule, value, callback) => {
      if (value !== this.modalForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const password = [
      {
        required: true,
        pattern: /^[a-zA-Z0-9_]{6,20}$/,
        message: "密码只能由数字、字母和下划线组成，长度6-20个字符",
        trigger: "change",
      },
    ];

    return {
      modalIsShow: false,
      isSubmit: false,
      nameWaitTime: "resetpwd",
      isFetchingCode: false,
      modalForm: { ...initModalForm },
      resetRules: {
        password: [...password],
        rePassword: [
          ...password,
          {
            validator: equalToPswd,
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.modalForm.id = this.$store.state.user.id;
    },
    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;
      let datas = {
        id: this.modalForm.id,
        password: this.modalForm.password,
      };
      const data = await resetUserPassword(datas).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

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