<template>
  <!-- 新建页面 -->
  <el-dialog
    id="preferences"
    title="修改密码"
    :append-to-body="true"
    :visible.sync="show"
    :close-on-click-modal="true"
    v-drag
  >
    <!-- 新建表单 -->
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      class="automargin"
      status-icon
      label-width="80px"
    >
      <el-form-item label="原密码" prop="pwd">
        <el-input
          v-model="form.pwd"
          show-password="true"
          placeholder="请输入原密码"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="newPwd">
        <el-input
          v-model="form.newPwd"
          show-password="true"
          placeholder="请输入新密码"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="确认密码" prop="newPwd2">
        <el-input
          v-model="form.newPwd2"
          show-password="true"
          placeholder="请输入确认密码"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <!-- 确定按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit()">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
// 引入接口
import { changePwd } from "./service";

// 构造表单
class Form {
  constructor(data) {
    this.pwd = ""; // 名称
    this.newPwd = ""; // 键
    this.newPwd2 = ""; // 值
  }
}

export default {
  data() {
    const confirmPwd = (rule, value, callback) => {
      // 键查重
      if (value != this.form.newPwd) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      show: false,
      form: [],
      rules: {
        pwd: [
          {
            required: true,
            message: "请输入原密码",
          },
        ],
        newPwd: [
          {
            required: true,
            message: "请输入新密码",
          },
        ],
        newPwd2: [
          {
            required: true,
            message: "请输入确认密码",
          },
          {
            validator: confirmPwd,
          },
        ],
      },
    };
  },

  methods: {
    // 页面获取时
    getPage(data) {
      this.form = new Form(data);
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.show = true;
    },
    // 页面提交
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          changePwd(this.form).then((res) => {
            // 调用接口
            if (res.status == "success") {
              // 成功
              this.$message({
                message: "修改密码成功",
                type: "success",
              });
              console.log("修改密码成功");
              this.show = false;
            } else {
              this.$message({
                // 失败
                message: res.message,
                type: "error",
              });
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped></style>
