<template>
  <el-dialog
    class="reset-pwd"
    :visible.sync="modalIsShow"
    :title="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"
    >
      <template v-if="needResetPwd">
        <el-form-item prop="oldPassword" label="旧密码：">
          <el-input
            type="password"
            v-model="modalForm.oldPassword"
            placeholder="请输入旧密码"
            clearable
          ></el-input>
        </el-form-item>
        <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>
      </template>
      <template v-if="needBindMobile">
        <el-form-item prop="mobileNumber" label="手机号：">
          <el-input
            v-model.trim="modalForm.mobileNumber"
            placeholder="请输入账号"
            name="mobileNumber"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="code" label="验证码：">
          <div class="vlcode">
            <div class="vlcode-right">
              <el-button
                style="width:100%;"
                type="text"
                @click="fetchSmsCode"
                :disabled="isFetchingCode"
                >+{{ codeContent }}</el-button
              >
            </div>
            <div class="vlcode-left">
              <el-input
                v-model.trim="modalForm.code"
                placeholder="请输入手机验证码"
                name="code"
                clearable
              >
              </el-input>
            </div>
          </div>
        </el-form-item>
      </template>
    </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 { updatePwd } from "../api";
import { getSmsCodeForBind } from "@/modules/login/api";
import { password, phone, smscode } from "@/plugins/formRules";
import { Base64 } from "@/plugins/crypto";
import fetchSmsMixins from "@/modules/login/fetchSmsMixins";

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

export default {
  name: "reset-pwd",
  props: {
    userInfo: {
      type: Object,
      default() {
        return {
          userId: "",
          loginName: "",
          schoolCode: "",
          password: "",
          mobileNumber: "",
          pwdCount: ""
        };
      }
    }
  },
  mixins: [fetchSmsMixins],
  data() {
    const equalToOldPswd = (rule, value, callback) => {
      if (value === this.modalForm.oldPassword) {
        callback(new Error("新旧密码不可以相同"));
      } else {
        callback();
      }
    };
    const equalToPswd = (rule, value, callback) => {
      if (value !== this.modalForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      modalIsShow: false,
      isSubmit: false,
      nameWaitTime: "resetpwd",
      isFetchingCode: false,
      modalForm: { ...initModalForm },
      resetRules: {
        code: smscode,
        mobileNumber: phone,
        oldPassword: password,
        password: [
          ...password,
          {
            validator: equalToOldPswd,
            trigger: "change"
          }
        ],
        rePassword: [
          ...password,
          {
            validator: equalToPswd,
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {
    needBindMobile() {
      return !this.userInfo.mobileNumber;
    },
    needResetPwd() {
      return !this.userInfo.pwdCount;
    },
    title() {
      if (this.needBindMobile && this.needResetPwd)
        return "修改密码与绑定手机号";
      if (this.needBindMobile) return "绑定手机号";
      if (this.needResetPwd) return "修改密码";

      return "修改密码";
    }
  },
  methods: {
    initData(val) {
      this.modalForm = { ...initModalForm };
      this.modalForm.oldPassword = this.userInfo.password || "";
      this.modalForm.id = this.userInfo.userId;
    },
    visibleChange() {
      this.initData(this.instance);
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    checkField(field) {
      return new Promise((resolve, reject) => {
        this.$refs.modalFormComp.validateField(field, unvalid => {
          if (unvalid) {
            reject();
          } else {
            resolve();
          }
        });
      });
    },
    async fetchSmsCode() {
      // console.log("111");
      let result = true;
      await this.checkField("mobileNumber").catch(() => {
        result = false;
      });

      if (!result) return;

      this.isFetchingCode = true;
      const data = await getSmsCodeForBind({
        loginName: this.userInfo.loginName,
        schoolCode: this.userInfo.schoolCode,
        password: Base64(this.modalForm.oldPassword),
        mobileNumber: this.modalForm.mobileNumber
      }).catch(() => {
        this.isFetchingCode = false;
      });
      if (!data) return;

      this.$message.success(
        `已向手机尾号【${this.modalForm.mobileNumber.slice(
          -4
        )}】成功发送短信，请在2分钟内进行验证！`
      );
      this.changeContent();
    },
    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,
        oldPassword: Base64(this.modalForm.oldPassword)
      };
      if (this.needBindMobile) {
        datas = {
          ...datas,
          mobileNumber: this.modalForm.mobileNumber,
          verifyCode: this.modalForm.code
        };
      }
      if (this.needResetPwd) {
        datas = {
          ...datas,
          password: Base64(this.modalForm.password)
        };
      }
      const data = await updatePwd(datas).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

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