import ApiConstant from "@/api/ApiConstant";

export default {
  computed: {
    user() {
      return this.$store.state.auth.user?.user || {};
    },
    systemConfig() {
      return this.$store.state.app.systemConfig || {};
    },
    instance() {
      if (window) {
        return window.$nuxt;
      }
      return null;
    },
  },
  methods: {
    handleLogin() {
      return new Promise((resolve, reject) => {
        // 缓存上一次登录用户id
        this.$store.commit("account/SET_USER_ID", this.user.id);
        this.jumpReset()
          .then(() => {
            const $axios = this.$axios || this.instance?.$axios || null;
            if ($axios) {
              this.$store
                .dispatch("fetchSysInfoByToken", $axios)
                .then(() => {
                  resolve();
                })
                .catch(() => {
                  reject(new Error("请查看用户菜单接口响应"));
                });
            } else {
              reject(new Error("请查看 Vue 实例对象"));
            }
          })
          .catch(() => {
            this.$store.commit("account/SET_IS_RESET", true);
            const $router = this.$router || this.instance?.$router || null;
            $router && $router.push("/reset");
          });
      });
    },
    // 判断重置
    jumpReset() {
      return new Promise((resolve, reject) => {
        if (this.systemConfig?.IS_FORCE_MODIFY_PWD === "Y") {
          if (this.user.pwdModifyTime === null) {
            reject();
          } else {
            const date = new Date(this.user.pwdModifyTime);
            const dateFormat = `${date.getFullYear()}-${
              date.getMonth() + 1
            }-${date.getDate()}-`;
            if (
              this.dateFun(dateFormat) >=
              Number(this.systemConfig?.PWD_EXPIRE_DAYS)
            ) {
              reject();
            } else {
              resolve();
            }
          }
        } else {
          resolve();
        }
      });
    },
    dateFun(val) {
      const ts = new Date(val);
      const tss = ts.getTime();
      const t = tss / 1000; // 时间戳（秒）
      const ot = new Date(t * 1000); // 转为时间对象（js的时间戳是毫秒数）
      const oy = ot.getFullYear(); // 年
      const om = ot.getMonth() + 1; // 月
      const tt = new Date(); // 今天
      const ty = tt.getFullYear(); // 今天年
      const tm = tt.getMonth() + 1; // 今天月
      const gm = (ty - oy) * 12 + (tm - om); // 距今月数
      return gm;
    },
  },
};
