import { AreaCodes, User, FundBasic } from '@/types/common';
import { loadAreaCode, storeAreaCode, loadUser, storeUser } from '@/utils/storage';
import http from '@/utils/http';

export function globalState() {
  return (window as any).g_app._store.getState();
}

export async function getAreaCodes(): Promise<AreaCodes> {
  const areaCodeCache = loadAreaCode();
  if (areaCodeCache) {
    return areaCodeCache;
  }

  const res = await http.get<AreaCodes>('/sign/code');
  if (res.ok && res.data) {
    res.data = res.data.map((it: any) => ({
      id: it.id || it.pode,
      areacode: it.areacode || it.itc.match(/\d+/)[0],
      areaname: it.areaname || it.name_native || it.name_en,
    }));
    storeAreaCode(res.data);
    return res.data;
  }

  throw Error(res.msg);
}

export async function getUserInfo(refresh = false): Promise<User> {
  if (!refresh) {
    const userCache = loadUser() as User;
    if (userCache && userCache.id) {
      return userCache;
    }
  }

  const { ok, msg, data } = await http.get<User>('/user/info');
  if (ok && data) {
    data.token = globalState().user.user.token;
    storeUser(data);
    return data;
  }

  throw Error(msg);
}

export async function getFundBasic(): Promise<FundBasic> {
  const {
    ok,
    data,
    msg,
  } = await http.get<FundBasic>('/fund/detail');
  if (ok && data) {
    return data;
  }
  throw Error(msg);
}

export async function checkFundPwd(): Promise<boolean> {
  const { ok, msg, data } = await http.get<number>('/user/checkFundPwd');
  if (ok) {
    // 0 未设置；1 已设置
    return data === 1;
  }

  throw Error(msg);
}
