import { Router } from './router';

export function setCookie(name: string, val: string, expiresInSecond: number) {
  const date = new Date();
  const value = val;
  date.setTime(date.getTime() + expiresInSecond * 1000);
  document.cookie = `${name}=${value || ''}; expires=${date.toUTCString()}; path=/`;
}

export function getCookie(name: string): string | undefined {
  const ca: Array<string> = document.cookie.split(';');
  const caLen: number = ca.length;
  const cookieName = `${name}=`;
  let c: string;
  for (let i: number = 0; i < caLen; i += 1) {
    c = ca[i].replace(/^\s+/g, '');
    if (c.indexOf(cookieName) == 0) {
      return c.substring(cookieName.length);
    }
  }
  return undefined;
}

// 需存储参数key对照表
const SAVE_KEY_MAP = {
  envId: 'env_id',
  appId: 'app_id',
  clientId: 'client_id',
  // 登录配置版本号
  configVersion: 'config_version',
  // 回跳url
  redirectUrl: 'redirect_uri',
  // 登录来源
  source: 'source',
  // 登录态存储方式
  storageMode: 'storage_mode',
};

// 存储页面参数到cookie，缓存10分钟
export function saveUrlParams(key: string, router: Router) {
  const data = {};
  Object.keys(SAVE_KEY_MAP).forEach((key) => {
    data[key] = router.getUrlParams(SAVE_KEY_MAP[key]);
  });
  setCookie(key, JSON.stringify(data), 600);
}

// 从cookie中恢复页面参数
export function resumeUrlParams(key: string, router: Router) {
  try {
    const data = JSON.parse(getCookie(key));
    Object.keys(SAVE_KEY_MAP).forEach((key) => {
      router.setUrlParams(SAVE_KEY_MAP[key], data[key]);
    });
    setCookie(key, '', -1);
  } catch (e) {
    console.log('无法获取原始数据', e);
  }
}
