import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './router';


<% if(processCssUnit === 'rem'){ %>
(function () {
  function flex() {
    try {
      let htmlDom = document.documentElement;
      let width = window.innerWidth || htmlDom.clientWidth;
      let fontSize = width / (375 / 14);
      if (
        !navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i
        ) &&
        width > 768
      ) {
        htmlDom.style.fontSize = `14px`;
      } else {
        htmlDom.style.fontSize = fontSize + `px`;
      }
    } catch (e) {
      console.error(e);
    }
  }

  flex();
  window.addEventListener('resize', flex);
})();
<% } %>

function render(props = null) {
  const root = props?.container || document.body;
  const selector = props?.selector === undefined ? '#root' : props?.selector;
  const container = selector ? root.querySelector(selector) : root;

  ReactDOM.render(
    <App />,
    container
  );
}

if (!window['__POWERED_BY_QIANKUN__']) {
  render();
} else {
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}

/**
 * bootstrap 只会在微应用初始化的时候调用一次，下次微应用重新进入时会直接调用 mount 钩子，不会再重复触发 bootstrap。
 * 通常我们可以在这里做一些全局变量的初始化，比如不会在 unmount 阶段被销毁的应用级别的缓存等。
 */
async function bootstrap() {
  console.log('react app bootstraped');
}

/**
 * 应用每次进入都会调用 mount 方法，通常我们在这里触发应用的渲染方法
 */
async function mount(props) {
  render(props);
}

/**
 * 应用每次切出/卸载 会调用的方法，通常在这里我们会卸载微应用的应用实例
 */
async function unmount(props) {
  const root = props?.container || document.body;
  const selector = props?.selector === undefined ? '#root' : props?.selector;
  const container = selector ? root.querySelector(selector) : root;

  ReactDOM.unmountComponentAtNode(container);
}

export function register(key = '') {
  ((global) => {
    if (key) {
      global[key] = {
        bootstrap,
        mount,
        unmount,
        component: App,
      };
    }
  })(window);
}

<% if(adminPortalKey){ %>
register('<%= adminPortalKey %>');
<% } %>
