<template>
  <Modal
    class="reset-pswd"
    v-model="modalIsShow"
    title="修改密码"
    :mask-closable="false"
    @on-visible-change="visibleChange"
  >
    <Form ref="resetForm" :model="reset" :rules="resetRules">
      <!-- <FormItem prop="password">
        <Input
          type="password"
          v-model="reset.password"
          placeholder="请输入旧密码"
          clearable
        ></Input>
      </FormItem> -->
      <FormItem prop="newpswd">
        <Input
          type="password"
          v-model="reset.newpswd"
          placeholder="请输入新密码"
          clearable
        ></Input>
      </FormItem>
      <FormItem prop="renewpswd">
        <Input
          type="password"
          v-model="reset.renewpswd"
          placeholder="请再次输入新密码"
          clearable
        ></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :disabled="isSubmit" @click="submit">确定</Button>
    </div>
  </Modal>
</template>

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

const initModalForm = {
  // password: "",
  newpswd: "",
  renewpswd: ""
};
export default {
  name: "reset-pswd",
  data() {
    const equalToPswd = (rule, value, callback) => {
      if (value !== this.reset.newpswd) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    return {
      modalIsShow: false,
      isSubmit: false,
      userId: "",
      reset: {
        ...initModalForm
      },
      resetRules: {
        // password,
        newpswd: password,
        renewpswd: [
          ...password,
          {
            validator: equalToPswd,
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    visibleChange(visible) {
      if (visible) {
        this.reset = { ...initModalForm };
        this.userId = this.$ls.get("user", { id: "" }).id;
      }
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit(name) {
      const valid = await this.$refs.resetForm.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let result = true;
      await resetPwd({
        userId: this.userId,
        password: this.reset.newpswd
      }).catch(() => {
        result = false;
      });
      this.isSubmit = false;
      if (!result) return;
      this.cancel();
      this.$emit("confirm", this.reset.newpswd);
    }
  }
};
</script>
