import RenderAuthorize from '@/components/Authorized/index.jsx';
import { isDev } from './tools.ts';
// const isDev = false;
let auth = [];
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable import/no-mutable-exports */
// 获取url地址参数
const getQueryVariable = name => {
  // 获取url上的参数（使用decodeURIComponent对url参数进行解码）
  let search = decodeURIComponent(window.location.search).replace('?', '');
  const tempArr = search !== '' ? search.split('&') : [];

  // 将参数名转小写，参数值保留原大小写
  tempArr.forEach(item => {
    if (item) {
      const itemArr = item.split('=');
      search = search.replace(itemArr[0], itemArr[0].toLowerCase());
    }
  });

  // 正则匹配指定的参数
  const reg = new RegExp(`(^|&)${name.toLowerCase()}=([^&]*)(&|$)`);
  const result = search.match(reg);

  return result != null ? result[2] : '';
};
let Authorized = RenderAuthorize(getAuthority());

// Reload the rights component
const reloadAuthorized = () => {
  Authorized = RenderAuthorize(getAuthority());
};

/**
 * hard code
 * block need it。
 */
window.reloadAuthorized = reloadAuthorized;

export { reloadAuthorized };
export default Authorized;

// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str) {
  const isSandBox = getQueryVariable('sandbox');
  const sandbox = sessionStorage.getItem('_omsticket');
  if (!isDev) {
    // return [...auth];

    // 支持可以指直接访问
    // if (isSandBox == 'true') {
    //   sessionStorage.setItem('_omsticket', 'd438aaf9578f405299ae740c4eb75aae');
    //   return ['LOGIN', 'admin'];
    // }
    if (sandbox == 'd438aaf9578f405299ae740c4eb75aae') {
      return ['LOGIN', 'admin'];
    }
    return [...auth];
  }
  const authorityString =
    typeof str === 'undefined' && localStorage ? localStorage.getItem('panda-oms-authority') : str;
  // authorityString could be admin, "admin", ["admin"]
  let authority;
  try {
    if (authorityString) {
      authority = JSON.parse(authorityString);
    }
  } catch (e) {
    authority = authorityString;
  }
  if (typeof authority === 'string') {
    return [authority];
  }

  return authority;
}

export function setAuthority(authority) {
  const proAuthority = typeof authority === 'string' ? [authority] : authority;
  if (isDev) {
    localStorage.setItem('panda-oms-authority', JSON.stringify(proAuthority));
  } else {
    auth = proAuthority;
  }
  // auto reload
  reloadAuthorized();
}
