import { host } from "../utils/constant";
import Storage from "../utils/storage";

const _tokenStorage = new Storage("AUTH");

const _tokenQueue: {
  pending: boolean;
  list: {
    resolve: (value: string) => void;
    reject: (err: any) => void;
  }[];
} = {
  pending: false,
  list: [],
};

let _onTokenListener: {
  cb: (token: string) => void;
}[] = [];

const _resolveTokenQueue = function (res: any) {
  _tokenQueue.pending = false;
  uni.hideLoading();
  if (res.errMsg) {
    console.log(res);
    uni.showModal({
      title: "登录失败",
      content: `${res.errMsg}`,
    });
    _tokenQueue.list.forEach((item) => {
      item.reject(res);
    });
  } else {
    uni.showToast({
      icon: "success",
      title: "登录成功",
    });
    setToken(res as string);
    _onTokenListener.forEach((item) => {
      item.cb(res as string);
    });
    _tokenQueue.list.forEach((item) => {
      item.resolve(res as string);
    });
  }
  _onTokenListener = [];
  _tokenQueue.list = [];
};

export function login(e: any): Promise<string> {
  return new Promise((resolve, reject) => {
    if (/deny|cancel/.test(e.detail.errMsg)) {
      reject();
      return;
    }
    if (!e.detail.code) {
      uni.showModal({
        title: `${e.detail.errMsg},请重试`,
      });
      reject();
      return;
    }
    _tokenQueue.list.push({
      resolve,
      reject,
    });
    if (_tokenQueue.pending) {
      return;
    }
    _tokenQueue.pending = true;
    uni.showLoading({
      title: "登录中",
      mask: true,
    });
    uni.login({
      success: (res) => {
        uni.request<any>({
          url: `${host}/user/wxLogin`,
          method: "POST",
          dataType: "json",
          data: {
            phoneCode: e.detail.code,
            code: res.code,
            avatar: "",
            nickname: "",
          },
          success: (res: any) => {
            const { statusCode, data } = res;
            if (
              statusCode === 200 &&
              data &&
              data.message === "ok" &&
              data.code === 200
            ) {
              _resolveTokenQueue(data.data.satoken);
            } else {
              _resolveTokenQueue({
                errMsg: data.msg ? data.msg : `${JSON.stringify(res)}`,
              });
            }
          },
          fail: _resolveTokenQueue,
        });
      },
      fail: _resolveTokenQueue,
    });
  });
}

export function refresh(): Promise<string> {
  return new Promise((resolve, reject) => {
    _tokenStorage.get("token").then((token) => {
      if (!token) {
        clearToken();
        reject({
          errMsg: "请登录",
        });
        uni.reLaunch({
          url: "/pages/map/map",
        });
      } else {
        getApp<any>().globalData.token = "";
        _tokenStorage.clear("token");
        uni.request({
          url: `${host}/user/refresh`,
          method: "GET",
          dataType: "json",
          header: {
            Authorization: token,
          },
          success: (res: any) => {
            console.log("refresh返回", res);
            const { statusCode, data } = res;
            if (
              statusCode === 200 &&
              data &&
              data.msg === "OK" &&
              data.code === 200
            ) {
              resolve(data.data.access_token);
            } else {
              if (data.code === 21005) {
                uni.reLaunch({
                  url: "/pages/map/map",
                });
              }
              reject({
                errMsg: `${JSON.stringify(res)}`,
              });
            }
          },
          fail: reject,
        });
      }
    });
  });
}

export function onLogin(cb: (token: string) => void) {
  _onTokenListener.push({
    cb,
  });
}

export function fetchToken() {
  return _tokenStorage.get("token");
}

export function setToken(token: string) {
  getApp<any>().globalData.token = token;
  return _tokenStorage.set("token", token);
}

export function clearToken() {
  getApp<any>().globalData.token = "";
  return _tokenStorage.clear("token");
}
