import qs from "qs";
import cache from "@/utils/cache";
import request from "@/api";
import { ILogin } from "@/const/interface_type";
import { validatenull } from "@/utils/validate";

import website from "@/const/website";

const scope = "server";
// 根据用户名密码登录
export const loginByUsername = ({ username, password, code, randomStr }: ILogin) => {
  // export const loginByUsername = ({ username, password, randomStr }: ILogin) => {
  const grant_type = "password";
  const dataObj = qs.stringify({ username: username, password: password });
  const basicAuth = "Basic " + window.btoa(website.formLoginClient);
  // 保存当前选中的 basic 认证信息
  cache.local.set("basicAuth", basicAuth);
  return request({
    url: "/admin/oauth2/token",
    headers: {
      isToken: false,
      "TENANT-ID": "1",
      Authorization: basicAuth
    },
    method: "post",
    params: { randomStr, code, grant_type, scope },
    data: dataObj
  });
};

// 刷新token
export const refreshToken = (refresh_token: string) => {
  const grant_type = "refresh_token";
  // 获取当前选中的 basic 认证信息
  const basicAuth = cache.local.get("basicAuth");

  return request({
    url: "/admin/oauth2/token",
    headers: {
      isToken: false,
      "TENANT-ID": "1",
      Authorization: basicAuth
    },
    method: "post",
    params: { refresh_token, grant_type, scope }
  });
};

// 查询用户信息
export const getUserInfo = () => {
  return request({
    url: "/admin/user/info",
    method: "get"
  });
};

// 登出
export const logout = () => {
  return request({
    url: "/admin/token/logout",
    method: "delete"
  });
};

/**
 * 校验令牌，若有效期小于半小时自动续期
 * @param refreshLock
 */
export const checkToken = (refreshTime: any, refreshLock: boolean, store: any) => {
  const token = store.getters.access_token;
  // 获取当前选中的 basic 认证信息
  const basicAuth = cache.local.get("basicAuth");
  request({
    url: "/admin/token/check_token",
    headers: {
      isToken: false,
      Authorization: basicAuth
    },
    method: "get",
    params: { token }
  })
    .then((response) => {
      if (validatenull(response)) {
        clearInterval(refreshTime);
        return;
      }

      const expire = response && response.data && response.data.exp;
      console.log(response);
      if (expire) {
        const expiredPeriod = expire * 1000 - new Date().getTime();
        // 小于半小时自动续约
        if (expiredPeriod <= 10 * 60 * 1000) {
          if (!refreshLock) {
            refreshLock = true;
            store.dispatch("RefreshToken").catch(() => {
              clearInterval(refreshTime);
            });
            refreshLock = false;
          }
        }
      }
    })
    .catch((error) => {
      console.error(error);
    });
};
