import * as React from 'react';
import { WedaApp, isEnableWecom } from '@cloudbase/lowcode-render';
import { default as data, sub_cals, dependencies } from './data';
import config from '../datasources/config';
import { loadDependencies } from '../utils/adapter/dependencies';
import lowcodeModulesMap from '../utils/adapter/lowcodeModules';

const STATUS_STYLE = `.weda-loading-container {
  position: fixed;
  left:0;
  top:0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height:100%;
  padding: 0 20px;
}
.weda-loading-container .logo {
  width: 100%;
  display: flex;
  justify-content: center;
  text-align: center;
  margin-bottom: 50px;
}

.weda-loading-container .sp{
  width: 48px;
  height:48px;
}

.weda-loading-container .sp-circle {
  border: 6px rgba(0,82,217,0.25) solid;
  border-top: 6px rgba(0,82,217,1) solid;
  border-radius: 50%;
  -webkit-animation: spCircRot .6s infinite linear;
  animation: spCircRot .6s infinite linear;
}
@-webkit-keyframes spCircRot {
  from { -webkit-transform: rotate(0deg); }
  to { -webkit-transform: rotate(359deg); }
}
@keyframes spCircRot {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}`;

function Loading({ message = "数据加载中..." }) {
  const [show, setShow] = React.useState(false)
  React.useEffect(() => {
    const enableWecom = isEnableWecom(data?.extra?.envId || data?.envId)
    const enableLoading = data?.extra?.enableLoading === undefined ? enableWecom : data?.extra?.enableLoading
    if (enableLoading) {
      setTimeout(() => {
        setShow(true)
      }, 100)
    }
  }, [])
  return (
    <>
      <style
        type="text/css"
        dangerouslySetInnerHTML={{
          __html: STATUS_STYLE,
        }}
      />
      {show && <div className="weda-loading-container">
        <div className="logo">
          <div className="sp sp-circle"></div>
        </div>
        <div className="text">
          {message === '正在加载组件、编译代码...' ? "登录鉴权中..." : message}
        </div>
      </div>}
    </>
  );
}

function Info({ message = '' }) {
  return (
    <>
      <style
        type="text/css"
        dangerouslySetInnerHTML={{
          __html: STATUS_STYLE,
        }}
      />
      <div className="weda-loading-container">
        <div className="logo">
          <img
            width="50"
            src="data:image/svg+xml;base64,PHN2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DAgMDAwLTEuMTYzTDE1LjI2IDcuN2ExLjM0NCAxLjM0NCAwIDAwLTEuMzQ2IDBMOS45MzQgMTB6IiBmaWxsPSIjNDc4N0YwIi8+PC9zdmc+"
          />
        </div>
        <div className="text" id="message">
          {message}
        </div>
      </div>
    </>
  );
}

function Modal({ visible, hide, children }) {
  const onKeyDown = (event) => {
    if (event.keyCode === 27 && visible) {
      hide();
    }
  };

  React.useEffect(() => {
    document.addEventListener('keydown', onKeyDown, false);
    return () => {
      document.removeEventListener('keydown', onKeyDown, false);
    };
  }, [visible, hide]);

  return visible ? (
    <>
      <div
        style={{
          position: 'fixed',
          width: '100%',
          height: '100%',
          top: 0,
          left: 0,
          background: 'rgb(74, 74, 75)',
          'z-index': 500,
        }}
        onClick={hide}
      />
      <div
        aria-modal
        tabIndex={-1}
        role="dialog"
        style={{
          position: 'fixed',
          top: '50%',
          left: ' 50%',
          transform: 'translate(-50%, -50%)',
          'z-index': 777,
          width: '80%',
          maxWidth: "400px",
          outline: 0,
        }}
      >
        <div
          style={{ 'z-index': 100, background: 'white', position: 'relative', margin: 'auto', 'border-radius': '8px' }}
        >
          <div style={{ padding: '10px', 'overflow-x': 'hidden', 'overflow-y': 'auto' }}>
            {children}
          </div>
        </div>
      </div>
    </>
  ) : null;
}

function formatLifecycle(time) {
  let str = '';
  const times = [time / 1000, 0, 0, 0];
  const unit = ['秒', '分', '小时', '天'];
  const delta = [1, 60, 60, 24];
  for (let i = 1; i < times.length; i++) {
    if (times[i - 1]) {
      times[i] = Math.floor(times[i - 1] / delta[i]);
      times[i - 1] = times[i - 1] % delta[i];
    }
  }
  for (let i = times.length - 1; i >= 0; i--) {
    if (times[i]) {
      str += times[i] + unit[i];
    }
  }
  return str;
}

function ExpiredMessage({ expLifeTime }) {
  const [visible, setVisible] = React.useState(false);
  return (
    <>
      <p>
        该版本为微搭免费套餐（长期免费，按月续期），需要再次发布激活，每次发布应用活跃时间为{formatLifecycle(expLifeTime)}，可多次发布。您也可以升级为
        <a target="_blank" href="https://buy.cloud.tencent.com/lowcode">
          付费套餐
        </a>
        ，无应用活跃时间限制。
        <a
          href="javascript:;"
          onClick={() => {
            setVisible(true);
          }}
        >
          添加客服
        </a>
        可获得付费套餐折扣优惠。
      </p>
      <Modal
        visible={visible}
        hide={() => {
          setVisible(false);
        }}
      >
        <img style={{ width: '100%' }} src="https://weda.cloud.tencent.com/img/customer_service.jpeg"></img>
      </Modal>
    </>
  );
}

function useExpired(createdTime = 0) {
  const [expired, setExpired] = React.useState(false);

  React.useEffect(() => {
    async function run() {
      const response = await fetch(
        'https://comp-public-replace-1303824488-cos.weda.tencent.com/release_config/runtime/exp_runtime.json'
      );
      const json = await response.json();
      const { expLifeTime = Infinity } = json;
      if (Date.now() - createdTime > expLifeTime) {
        setExpired(<ExpiredMessage expLifeTime={expLifeTime} />);
      }
    }
    try {
      if (createdTime) {
        run();
      }
    } catch (e) { }
  }, []);
  return expired;
}

export default function App() {
  const expiredMessage = useExpired(<%= expirationStartTimesnap %>);

  return expiredMessage ? (<>
    <>
      <Info message={expiredMessage} />
    </>
  </>
  ) : (
    <>
      <% if(enableAd){ %>
      <div style={{ fontSize: 12, paddingTop: '2.5em' }}></div>
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 10000,
        background: 'rgba(255, 103, 112, 0.95)',
        fontSize: 12,
        color: '#fff',
        lineHeight: '2.5em',
        padding: '0 .5em'
      }}>基于腾讯云开发搭建与部署，升级套餐可移除此说明。<a style={{ color: '#fff' }} target='_blank' href="https://docs.cloudbase.net/faq/knowledge/app-version-restriction">查看升级指引 &gt;</a></div>
      <% } %>
      <WedaApp
        cals={data}
        sub_cals={sub_cals || []}
        dependencies={dependencies}
        historyOption={{
          type:
            process.env.historyType === 'HASH'
              ? 'HASH'
              : 'BROWSER',
          basename: '<%= basename %>',
          _indexPage: <%= context.history._indexPage ? 'true' : 'false' %>
        }}
      _processDependencies={(deps) => {
        return deps
      }}
      loadDependencies={loadDependencies}
      loadLowcodes={async (cals) => {
        return lowcodeModulesMap
      }}
      loadExternalResources={async () => null}
      context={{
        basic: <%= context.basic ? 'true' : 'false' %>,
        getDatasourceConfig: () => {
            return config;
          },
      checkPageAuth: <%= context.checkPageAuth %>
        }}
      ErrorBoundary={React.Fragment}
      renderLoading={({ message }) => <Loading message={message} />}
      ></WedaApp >
    </>
  );
}
