import { getSmsCode } from "../../modules-part/login/api";

const wstorage = {
  set(key, value, expire = null) {
    window.localStorage.setItem(key, JSON.stringify({ value, expire }));
  },
  get(key, defaultVal = null) {
    const lsvalue = JSON.parse(window.localStorage.getItem(key));
    return lsvalue && (!lsvalue.expire || lsvalue.expire > new Date().getTime())
      ? lsvalue.value
      : defaultVal;
  },
  remove(key) {
    window.localStorage.removeItem(key);
  }
};

const codeWaitingTime = 60;

export default {
  data() {
    return {
      isFetchingCode: false,
      codeContent: "获取验证码",
      codeWaitingTime,
      time: codeWaitingTime
    };
  },
  methods: {
    setWaitingTime() {
      let codetime = wstorage.get(this.nameWaitTime);
      if (codetime) {
        let num = Math.floor((codetime.expire - new Date().getTime()) / 1000);
        if (num > 0) {
          this.time = num;
          this.isFetchingCode = true;
          this.changeContent();
        }
      }
    },
    fetchSmsCode() {
      this.$refs.modalFormComp.validateField("phone", async valid => {
        if (valid) return;
        this.isFetchingCode = true;
        const data = await getSmsCode(this.modalForm.phone).catch(() => {
          this.isFetchingCode = false;
        });
        if (!data) return;
        this.changeContent();
      });
    },
    changeContent() {
      if (!this.isFetchingCode) return;
      this.codeContent = "倒计时" + this.time + "s";
      const circleTime = time => {
        let t = setInterval(() => {
          if (time > 1) {
            time--;
            let expire = new Date().getTime() + time * 1000;
            wstorage.set(
              this.nameWaitTime,
              {
                time,
                expire
              },
              expire
            );
            this.codeContent = "倒计时" + time + "s";
          } else {
            this.time = this.codeWaitingTime;
            wstorage.remove(this.nameWaitTime);
            this.codeContent = "获取验证码";
            this.isFetchingCode = false;
            clearInterval(t);
          }
        }, 1e3);
      };
      circleTime(this.time);
    }
  }
};
