import { getPlatForm } from '/@/api/oem';
import { createLocalStorage } from '/@/utils/cache';

enum DefaultPlatform {
  LOGO = '/resource/img/logo.png',
  // TITLE = 'ThingsKit',
  ICO = '/favicon.ico',
}

export const usePlatform = async () => {
  const platformInfo = await getPlatForm();
  const storage = createLocalStorage();
  if (
    platformInfo === '' ||
    platformInfo === null ||
    Object.getOwnPropertyNames(platformInfo).length === 0
  ) {
    storage.set('platformInfo', 1234);
  } else {
    storage.set('platformInfo', platformInfo);
  }

  const createLoadingEffect = () => {
    const wrap = document.createElement('div');
    wrap.setAttribute('class', 'app-loading-wrap');
    const img = document.createElement('img');
    img.setAttribute('src', platformInfo.logo || DefaultPlatform.LOGO);
    img.setAttribute('class', 'app-loading-logo');
    img.setAttribute('alt', 'Logo');
    const dots = document.createElement('div');
    dots.setAttribute('class', 'app-loading-dots');
    const dotWrap = document.createElement('span');
    dotWrap.setAttribute('class', 'dot dot-spin');
    for (let i = 0; i < 4; i++) {
      dotWrap.appendChild(document.createElement('i'));
    }
    const title = document.createElement('div');
    title.setAttribute('class', 'app-loading-title');
    const textNode = document.createTextNode(
      // platformInfo.name || import.meta.env.VITE_GLOB_APP_TITLE
      '空间数据管理平台'
    );
    title.appendChild(textNode);
    wrap.appendChild(img);
    dots.appendChild(dotWrap);
    wrap.appendChild(dots);
    wrap.appendChild(title);
    return wrap;
  };

  const replaceSiteIco = () => {
    const linkEl = document.querySelectorAll('link[rel*="icon"]');
    linkEl.forEach((item) => {
      item.setAttribute('href', platformInfo.logo || DefaultPlatform.ICO);
    });
  };

  const replaceLoadingEffect = () => {
    // const loadingWrapper = document.getElementById('first-screen-loading');
    // loadingWrapper!.innerHTML = '';
    // loadingWrapper?.appendChild(createLoadingEffect());
  };

  const bootstrap = () => {
    replaceSiteIco();
    replaceLoadingEffect();
  };

  bootstrap();
};
