render.js 12.2 KB
Newer Older
邓晓峰's avatar
邓晓峰 committed
1
import React, { useEffect } from 'react';
2
import ReactDOM from 'react-dom';
邓晓峰's avatar
邓晓峰 committed
3

杨思琦's avatar
杨思琦 committed
4
import { ConfigProvider, message, Modal, notification } from 'antd';
5
import { ConnectedRouter } from 'connected-react-router/immutable';
邓晓峰's avatar
邓晓峰 committed
6
import Cookies from 'js-cookie';
邓晓峰's avatar
邓晓峰 committed
7
import canUseDom from 'rc-util/lib/Dom/canUseDom';
邓晓峰's avatar
邓晓峰 committed
8 9 10 11 12
import { updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import { Provider } from 'react-redux';

import { LocaleContainer } from '@wisdom-utils/components';
import { history } from '@wisdom-utils/runtime';
杨思琦's avatar
杨思琦 committed
13
import { params, Storeage } from '@wisdom-utils/utils/lib/helpers';
邓晓峰's avatar
邓晓峰 committed
14

邓晓峰's avatar
邓晓峰 committed
15
import { appService } from './api';
邓晓峰's avatar
邓晓峰 committed
16 17
import Container from './components/Container';
import App from './containers/App';
邓晓峰's avatar
邓晓峰 committed
18
import { actionCreators } from './containers/App/store';
杨思琦's avatar
杨思琦 committed
19
import { defaultApp, findMenuPath } from './micro';
邓晓峰's avatar
邓晓峰 committed
20 21
import Login from './pages/user/login/login';
import store from './stores';
22
import { getToken, searchUrl } from './utils/utils';
邓晓峰's avatar
邓晓峰 committed
23

邓晓峰's avatar
邓晓峰 committed
24 25
const { getThemeVariables } = require('antd/dist/theme');
const defaultSetting = require('../config/defaultSetting');
26
const MOUNT_NODE = document.getElementById('root');
27
const customPrefixCls = 'panda-console-base';
杨思琦's avatar
杨思琦 committed
28
// eslint-disable-next-line no-restricted-globals
邓晓峰's avatar
邓晓峰 committed
29 30 31 32 33 34 35 36
const namespace = `__PANDA_STORE__${location.hostname}`;
window.createStoreage = new Storeage(namespace);

const dynamicStyleMark = `-panda-${Date.now()}-${Math.random()}`;
function getStyle(prefixCls, theme) {
  const variables = {};

  Object.keys(theme).forEach(item => {
杨思琦's avatar
杨思琦 committed
37 38 39
    variables[item] = theme[item];
  });
  const cssList = Object.keys(variables).map(key => `--${prefixCls}-${key}: ${variables[key]};`);
邓晓峰's avatar
邓晓峰 committed
40 41 42 43 44 45 46 47

  return `
  :root {
    ${cssList.join('\n')}
  }
  `.trim();
}

48
const registerTheme = function(prefixCls, theme) {
邓晓峰's avatar
邓晓峰 committed
49
  const style = getStyle(prefixCls, theme);
杨思琦's avatar
杨思琦 committed
50 51
  if (canUseDom()) {
    updateCSS(style, `${dynamicStyleMark}-dynamic-theme`);
邓晓峰's avatar
邓晓峰 committed
52
  }
杨思琦's avatar
杨思琦 committed
53
};
邓晓峰's avatar
邓晓峰 committed
54 55 56

export const AppInitState = () => {
  const getClient = () => {
57
    const value = params.getParams('client') || sessionStorage.getItem('client');
邓晓峰's avatar
邓晓峰 committed
58 59
    const client = value && value !== 'undefined' ? value : 'city';
    return client;
杨思琦's avatar
杨思琦 committed
60
  };
杨思琦's avatar
杨思琦 committed
61 62 63 64 65
  const getUrlToken = () => {
    const value = params.getParams('token');
    const token = value && value !== 'undefined' ? value : null;
    return token;
  };
66 67 68 69 70
  const getHDToken = () => {
    const value = params.getParams('uniwater_utoken');
    const hdtoken = value && value !== 'undefined' ? value : null;
    return hdtoken;
  };
邓晓峰's avatar
邓晓峰 committed
71 72

  const client = getClient();
杨思琦's avatar
杨思琦 committed
73
  const token = getUrlToken();
74
  const HDtoken = getHDToken();
杨思琦's avatar
杨思琦 committed
75
  if (sessionStorage.getItem('client') !== client) {
杨思琦's avatar
杨思琦 committed
76 77
    sessionStorage.setItem('client', client);
  }
邓晓峰's avatar
邓晓峰 committed
78
  let config = window.globalConfig || {};
杨思琦's avatar
杨思琦 committed
79
  // eslint-disable-next-line no-undef, no-restricted-globals
邓晓峰's avatar
邓晓峰 committed
80
  createStoreage.remove(`__PANDA_STORE__${location.hostname}`);
81

邓晓峰's avatar
邓晓峰 committed
82
  window.globalConfig = {};
杨思琦's avatar
杨思琦 committed
83
  // eslint-disable-next-line no-underscore-dangle
邓晓峰's avatar
邓晓峰 committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  window.__INITIAL_STATE__ = {};

  if (!getToken() || config.token == null) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
    config = {};
  }
  if (!params.getParams('client', window.location.search) && config) {
    // eslint-disable-next-line no-undef
    createStoreage.remove(namespace);
  }

  // eslint-disable-next-line no-undef
  if (!createStoreage.get('globalConfig')) {
    window.createStoreage = new Storeage(namespace);
  }

  if (!getToken()) {
    localStorage.removeItem('loginSite');
  }

  const initGeteWay = () => {
杨思琦's avatar
杨思琦 committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    appService
      .getWateWayConfig({ ignoreSite: true })
      .then(res => {
        // eslint-disable-next-line prettier/prettier, no-undef
        const hasGateWay = !res || !res.data ? false : _.isString(res.data) ? JSON.parse(res.data) : (typeof res.data === 'boolean' ? res.data : false);
        return {
          hasGateWay,
          apiGatewayDomain: `${window.location.origin}${hasGateWay ? '/PandaCore/GateWay' : ''}`,
        };
      })
      .then(gateWayConfig => {
        // eslint-disable-next-line no-use-before-define
        initGlobalConfig(gateWayConfig);
      })
      .catch(err => {
        // eslint-disable-next-line no-use-before-define
        initGlobalConfig();
      });
  };
邓晓峰's avatar
邓晓峰 committed
125 126

  const initGlobalConfig = (gateWayConfig = {}) => {
杨思琦's avatar
杨思琦 committed
127 128 129 130 131
    appService
      .queryConfig({
        client: client || 'city',
        ignoreSite: true,
      })
132
      .then(async res => {
杨思琦's avatar
杨思琦 committed
133 134 135 136
        if (res) {
          const { data } = res;
          if (!data.client) {
            data.client = client;
邓晓峰's avatar
邓晓峰 committed
137
          }
杨思琦's avatar
杨思琦 committed
138 139
          if (data.pwdRegex) {
            localStorage.setItem('password_pwdRegex', data.pwdRegex);
杨思琦's avatar
杨思琦 committed
140 141
          } else {
            localStorage.removeItem('password_pwdRegex');
杨思琦's avatar
杨思琦 committed
142 143 144
          }
          if (data.pwdRegexTip) {
            localStorage.setItem('password_pwdRegexTip', data.pwdRegexTip);
杨思琦's avatar
杨思琦 committed
145 146
          } else {
            localStorage.removeItem('password_pwdRegexTip');
杨思琦's avatar
杨思琦 committed
147
          }
148 149 150 151

          if (data.webState === '1' || data.webState === '3') {
            data.isIntegration = '1';
          }
152 153 154 155
          window.qiankunIsCache =
            window.location.origin.replace(/^(http|https):\/\//, '') === 'panda-water.cn'
              ? false
              : data.isCache || false;
156 157 158 159
          const serverRes = await appService.getMainServer();
          const serverData = serverRes?.data || [];
          const mainserverConf = serverData.find(item => item.name === 'mainserver');
          const mainserver = mainserverConf?.url || '';
杨思琦's avatar
杨思琦 committed
160 161 162 163 164
          store.dispatch(
            actionCreators.getConfig(
              Object.assign(
                {},
                data,
邓晓峰's avatar
邓晓峰 committed
165
                {
杨思琦's avatar
杨思琦 committed
166 167 168
                  token: '',
                  access_token: '',
                  userInfo: null,
邓晓峰's avatar
邓晓峰 committed
169
                },
170 171 172
                {
                  mainserver,
                },
邓晓峰's avatar
邓晓峰 committed
173 174
                gateWayConfig,
              ),
杨思琦's avatar
杨思琦 committed
175
            ),
邓晓峰's avatar
邓晓峰 committed
176
          );
杨思琦's avatar
杨思琦 committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
          const products = (data.products || []).map(item => {
            if (item.PackageName === 'civweb4') {
              return 'web4_console';
            }
            return `${item.PackageName}-main`;
          });

          if (products && products.length > 0) {
            Object.keys(products).forEach(item => {
              window[products[item]] &&
                window[products[item]] &&
                window[products[item]].unmount &&
                window[products[item]].unmount({ store });
            });
          }
          // eslint-disable-next-line no-new
杨思琦's avatar
杨思琦 committed
193
          // 增加免登判定
194
          if (!token && !HDtoken && getToken()) {
杨思琦's avatar
杨思琦 committed
195 196 197 198 199 200 201 202 203
            // eslint-disable-next-line no-new
            const action = new Login(
              {
                global: Object.assign(
                  {},
                  data,
                  {
                    token: getToken(),
                  },
204 205 206
                  {
                    mainserver,
                  },
杨思琦's avatar
杨思琦 committed
207 208
                  gateWayConfig,
                ),
209 210
                createContext: value => store.dispatch(actionCreators.createContext(value)),
                updateConfig: value => store.dispatch(actionCreators.getConfig(value)),
杨思琦's avatar
杨思琦 committed
211 212 213 214
                isInit: false,
                logout: () => store.dispatch(actionCreators.logout()),
              },
              () => {
杨思琦's avatar
杨思琦 committed
215 216 217 218 219
                // (async () => {
                //   (await (getToken() && window.globalConfig && window.globalConfig.token)) &&
                //     // eslint-disable-next-line no-use-before-define
                //     initMicroApps(loader, store);
                // })();
杨思琦's avatar
杨思琦 committed
220 221 222 223 224 225 226
              },
              true,
            );
            action.events.on('loginSuccess', event => {
              window.history.pushState('', '', `/?client=${client}`);
              defaultApp();
            });
杨思琦's avatar
杨思琦 committed
227 228
            action.events.on('loginHomePage', event => {
              window.history.pushState('', '', `/?client=${client}`);
杨思琦's avatar
杨思琦 committed
229 230 231
              const { allWidgets } = window.globalConfig;
              const url = `civbase/${findMenuPath([allWidgets[0]])}`;
              defaultApp(url);
杨思琦's avatar
杨思琦 committed
232
            });
233 234 235
            action.events.on('loginIndustry', event => {
              window.history.pushState('', '', `/civbase/industry`);
            });
杨思琦's avatar
杨思琦 committed
236 237
          }
          return window.globalConfig.variableTheme;
邓晓峰's avatar
邓晓峰 committed
238
        }
杨思琦's avatar
杨思琦 committed
239 240 241 242 243 244 245 246
      })
      .then(themeConfig => {
        ConfigProvider.config({
          prefixCls: customPrefixCls,
          theme: {
            primaryColor: themeConfig.primaryColor,
          },
        });
邓晓峰's avatar
邓晓峰 committed
247

杨思琦's avatar
杨思琦 committed
248 249 250 251 252 253 254
        registerTheme(customPrefixCls, {
          'header-bg-color': themeConfig.headerPrimaryColor,
          // 'linear-gradient(0deg, #0066d6, #39a9ff 100%)'
        });
      })
      .catch(error => {
        store.dispatch(actionCreators.getConfigError(error));
邓晓峰's avatar
邓晓峰 committed
255
      });
杨思琦's avatar
杨思琦 committed
256
  };
邓晓峰's avatar
邓晓峰 committed
257 258 259 260 261 262 263

  const initLocale = () => {
    localStorage.setItem('umi_locale', 'zh-CN');
  };

  // 语音播报全局拦截
  const initMessageVoice = () => {
264
    if (!window.speechSynthesis) return;
邓晓峰's avatar
邓晓峰 committed
265
    const rawSpeak = window.speechSynthesis.speak;
266
    window.speechSynthesis.speak = function(...args) {
邓晓峰's avatar
邓晓峰 committed
267 268 269 270 271 272 273 274 275 276 277
      if (
        window.globalConfig &&
        // eslint-disable-next-line no-prototype-builtins
        window.globalConfig.hasOwnProperty('messageVoice') &&
        window.globalConfig.messageVoice === false
      )
        return;
      rawSpeak.apply(window.speechSynthesis, args);
    };
  };

278 279 280
  // 添加主题变更事件监听
  const initAppTheme = () => {
    const hasThemeChanged = (preTheme, theme) => {
杨思琦's avatar
杨思琦 committed
281
      if (!preTheme && !theme) return false;
282
      if (
杨思琦's avatar
杨思琦 committed
283 284 285 286 287 288 289 290 291 292
        preTheme &&
        theme &&
        (!theme.primaryColor || theme.primaryColor === preTheme.primaryColor) &&
        (!theme.navTheme || theme.navTheme === preTheme.navTheme) &&
        (!theme.headerPrimaryColor || theme.headerPrimaryColor === preTheme.headerPrimaryColor)
      )
        return false;
      return true;
    };
    store.subscribe(
293
      (function() {
杨思琦's avatar
杨思琦 committed
294
        const preVariableTheme = store.getState().toJS().global?.globalConfig?.variableTheme;
295
        return function() {
杨思琦's avatar
杨思琦 committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
          // if (!preVariableTheme)
          const variableTheme = store.getState().toJS().global?.globalConfig?.variableTheme;
          if (!hasThemeChanged(preVariableTheme, variableTheme)) return false;
          const { primaryColor: prePrimaryColor, navTheme: preNavTheme, headerPrimaryColor: preHeaderPrimaryColor } =
            preVariableTheme || {};
          const { primaryColor, headerPrimaryColor } = variableTheme;
          if (primaryColor && primaryColor !== prePrimaryColor) {
            ConfigProvider.config({
              prefixCls: customPrefixCls,
              theme: {
                primaryColor,
              },
            });
          }
          if (headerPrimaryColor && headerPrimaryColor !== preHeaderPrimaryColor) {
            registerTheme(customPrefixCls, {
              'header-bg-color': headerPrimaryColor,
            });
          }
        };
      })(),
    );
318
  };
邓晓峰's avatar
邓晓峰 committed
319 320 321
  initLocale();
  initMessageVoice();
  initGeteWay();
322
  initAppTheme();
杨思琦's avatar
杨思琦 committed
323
};
邓晓峰's avatar
邓晓峰 committed
324

杨思琦's avatar
杨思琦 committed
325
const RootContainer = props => {
326
  const { loading } = props;
邓晓峰's avatar
邓晓峰 committed
327 328 329 330 331 332 333 334 335

  useEffect(() => {
    AppInitState();
  }, []);

  const finalConfig = {
    ...{
      prefixCls: customPrefixCls,
      theme: {
336
        'root-entry-name': 'default',
邓晓峰's avatar
邓晓峰 committed
337 338 339
        ...getThemeVariables({}),
        primaryColor: defaultSetting.primaryColor,
      },
340 341
    },
  };
邓晓峰's avatar
邓晓峰 committed
342

343
  if (finalConfig.prefixCls) {
杨思琦's avatar
杨思琦 committed
344
    ConfigProvider.config({
345
      rootPrefixCls: customPrefixCls,
邓晓峰's avatar
邓晓峰 committed
346 347
    });
    message.config({
348
      rootPrefixCls: `${finalConfig.prefixCls}-message`,
邓晓峰's avatar
邓晓峰 committed
349 350
    });
    notification.config({
351
      rootPrefixCls: `${finalConfig.prefixCls}-notification`,
邓晓峰's avatar
邓晓峰 committed
352 353 354
    });
  }

杨思琦's avatar
杨思琦 committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  return React.createElement(
    Provider,
    {
      store,
    },
    React.createElement(
      ConnectedRouter,
      {
        history,
      },
      React.createElement(
        LocaleContainer,
        {
          prefixCls: customPrefixCls,
        },
        React.createElement(
          ConfigProvider,
          {
            prefixCls: customPrefixCls,
          },
          React.createElement(
            Container,
            null,
            React.createElement(App, {
              loading,
            }),
          ),
        ),
      ),
    ),
  );
386 387 388
};

export const render = ({ loading }) => {
邓晓峰's avatar
邓晓峰 committed
389
  // eslint-disable-next-line react-hooks/rules-of-hooks
杨思琦's avatar
杨思琦 committed
390
  ReactDOM.render(<RootContainer loading={loading} />, MOUNT_NODE);
邓晓峰's avatar
邓晓峰 committed
391
};
邓晓峰's avatar
邓晓峰 committed
392

邓晓峰's avatar
邓晓峰 committed
393
// updateTheme('#ff9600');
杨思琦's avatar
杨思琦 committed
394
const loader = loading => render({ loading });
395

邓晓峰's avatar
邓晓峰 committed
396
export default loader;