app.js 9.15 KB
Newer Older
1
import './public-path'
dengxiaofeng's avatar
dengxiaofeng committed
2 3
import '!file-loader?name=[name].[ext]!./images/favicon.ico';
import './global.less';
4
// import '@babel/polyfill';
dengxiaofeng's avatar
dengxiaofeng committed
5
import 'animate.css/animate.css';
邓晓峰's avatar
邓晓峰 committed
6
import 'antd/dist/antd.less';
dengxiaofeng's avatar
dengxiaofeng committed
7 8 9
import 'file-loader?name=.htaccess!./.htaccess'; // eslint-disable-line import/extensions
import 'kit_utils/lib/format';
import 'sanitize.css/sanitize.css';
10 11 12
// import './locales/zh-CN';
// import './loader';
// import './vm';
dengxiaofeng's avatar
dengxiaofeng committed
13 14
import React from 'react';
import ReactDOM from 'react-dom';
15

16
import { Button, ConfigProvider, message, notification } from 'antd';
dengxiaofeng's avatar
dengxiaofeng committed
17 18
import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable';
19
import { params, Storeage } from 'kit_utils';
dengxiaofeng's avatar
dengxiaofeng committed
20
import { Provider } from 'react-redux';
21
import { history } from '@wisdom-utils/runtime';
22 23 24
import ErrorBoundary from './components/ErrorBoundary';
import { useIntl } from '@/locales/localeExports';
// import { ErrorBoundary } from '@ant-design/pro-utils';
25

邓晓峰's avatar
邓晓峰 committed
26
import defaultSettings from '../config/defaultSetting';
27 28 29
// import themePluginConfig from '../config/themePluginConfig';
import { appService } from './api';
import { updateTheme } from './common/helpers/settingColor';
邓晓峰's avatar
邓晓峰 committed
30
import Container from './components/Container';
dengxiaofeng's avatar
dengxiaofeng committed
31 32 33
import configureStore from './configureStore';
import App from './containers/App';
import { actionCreators } from './containers/App/store';
34
import { LocaleContainer } from './locales/locale';
邓晓峰's avatar
邓晓峰 committed
35
import { initMicroApps } from './micro';
邓晓峰's avatar
邓晓峰 committed
36
import Login from './pages/user/login/login';
37
import { getToken, isString } from './utils/utils';
38
import './utils/event';
39
import Cookies from 'js-cookie';
邓晓峰's avatar
邓晓峰 committed
40 41 42 43
const isHttps = document.location.protocol === 'https:';
const { pwa } = defaultSettings;
// eslint-disable-next-line no-restricted-globals
const namespace = `__PANDA_STORE__${location.hostname}`;
邓晓峰's avatar
邓晓峰 committed
44
window.createStoreage = new Storeage(namespace);
邓晓峰's avatar
邓晓峰 committed
45
// eslint-disable-next-line no-underscore-dangle
dengxiaofeng's avatar
dengxiaofeng committed
46 47
const initialState = Immutable.Map();
const store = configureStore(initialState, history);
48
const MOUNT_NODE = document.getElementById('root');
49 50 51
ConfigProvider.config({
  prefixCls: 'panda-console-base'
});
dengxiaofeng's avatar
dengxiaofeng committed
52
const render = () => {
邓晓峰's avatar
邓晓峰 committed
53
  // eslint-disable-next-line react-hooks/rules-of-hooks
dengxiaofeng's avatar
dengxiaofeng committed
54 55 56
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
57
        <LocaleContainer>
58
          <ConfigProvider prefixCls="panda-console-base">
59 60
            <ErrorBoundary>
              <Container>
邓晓峰's avatar
邓晓峰 committed
61
                <App />
62 63 64
              </Container>
            </ErrorBoundary>
          </ConfigProvider>
65
        </LocaleContainer>
dengxiaofeng's avatar
dengxiaofeng committed
66 67 68 69 70
      </ConnectedRouter>
    </Provider>,
    MOUNT_NODE,
  );
};
71
// updateTheme('#ff9600');
dengxiaofeng's avatar
dengxiaofeng committed
72 73 74
const loader = (appContent, loading) => render({ appContent, loading });

const initLocale = () => {
邓晓峰's avatar
邓晓峰 committed
75 76
  localStorage.setItem('umi_locale', 'zh-CN');
};
77
const PRODUCT_NAME = ['civ_water', 'civ_monitor'];
dengxiaofeng's avatar
dengxiaofeng committed
78 79

const initGlobalConfig = () => {
邓晓峰's avatar
邓晓峰 committed
80
  // eslint-disable-next-line no-debugger
邓晓峰's avatar
邓晓峰 committed
81
  // eslint-disable-next-line no-undef
邓晓峰's avatar
邓晓峰 committed
82 83
  let config = createStoreage.get('globalConfig') || {};
  store.dispatch(actionCreators.updateComplexConfig({}));
84
  if (!getToken() || config.token == null) {
邓晓峰's avatar
邓晓峰 committed
85
    // eslint-disable-next-line no-undef
邓晓峰's avatar
邓晓峰 committed
86
    createStoreage.remove(namespace);
87
    config = {};
dengxiaofeng's avatar
dengxiaofeng committed
88
  }
邓晓峰's avatar
邓晓峰 committed
89
  if (!params.getParams('client', window.location.search) && config) {
邓晓峰's avatar
邓晓峰 committed
90
    // eslint-disable-next-line no-undef
邓晓峰's avatar
邓晓峰 committed
91
    createStoreage.remove(namespace);
dengxiaofeng's avatar
dengxiaofeng committed
92 93
  }

邓晓峰's avatar
邓晓峰 committed
94
  // eslint-disable-next-line no-undef
邓晓峰's avatar
邓晓峰 committed
95
  if (!createStoreage.get('globalConfig')) {
邓晓峰's avatar
邓晓峰 committed
96
    window.createStoreage = new Storeage(namespace);
dengxiaofeng's avatar
dengxiaofeng committed
97
  }
98
  if (!getToken()) {
邓晓峰's avatar
邓晓峰 committed
99 100
    localStorage.removeItem('loginSite');
  }
101

邓晓峰's avatar
邓晓峰 committed
102
  if (config.token !== null && Object.keys(config).length > 0) {
邓晓峰's avatar
邓晓峰 committed
103
    store.dispatch(actionCreators.getConfig(config));
邓晓峰's avatar
邓晓峰 committed
104 105
    // render({ appContent: '', loading: true });
    initMicroApps(loader, store);
106 107 108
    if (config.isNewYear) {
      updateTheme('#ff9600');
    }
dengxiaofeng's avatar
dengxiaofeng committed
109
  } else {
110 111 112
    appService.getWateWayConfig().then(res => {
      const hasGateWay =
        res && res.data && isString(res.data) ? JSON.parse(res.data) : res.data;
113
      if (res.code === 0 && res.data === 'true') {
114 115 116 117 118 119 120 121 122 123
        store.dispatch(
          actionCreators.getConfig(
            Object.assign({}, window.globalConfig, {
              hasGateWay,
              apiGatewayDomain: `${window.location.origin}/PandaCore`,
            }),
          ),
        );
      }
    });
124
    // eslint-disable-next-line react-hooks/rules-of-hooks
邓晓峰's avatar
邓晓峰 committed
125
    appService
126
      .queryConfig({
邓晓峰's avatar
邓晓峰 committed
127
        client: params.getParams('client')  || 'city',
128
      })
邓晓峰's avatar
邓晓峰 committed
129
      .then(res => {
邓晓峰's avatar
邓晓峰 committed
130 131
        if (res) {
          const data = res;
邓晓峰's avatar
邓晓峰 committed
132
          if (!data.client) {
133
            data.client = params.getParams('client') || 'city';
邓晓峰's avatar
邓晓峰 committed
134
          }
邓晓峰's avatar
邓晓峰 committed
135
          Cookies.set('city', Cookies.get('city'));
邓晓峰's avatar
邓晓峰 committed
136 137 138 139 140
          store.dispatch(
            actionCreators.getConfig(
              Object.assign({}, window.globalConfig, data),
            ),
          );
141
          
邓晓峰's avatar
邓晓峰 committed
142
          //Cookies.set('city', params.getParams('client'))
143

144 145 146
          if (data.loginTemplate === '新春 - 智联.html') {
            updateTheme('#ff9600');
          }
邓晓峰's avatar
邓晓峰 committed
147
          // eslint-disable-next-line no-new
148
          if (getToken()) {
149 150 151 152
            // eslint-disable-next-line no-new
            new Login(
              {
                global: Object.assign({}, data, {
153
                  token: getToken(),
154 155 156 157
                }),
                // eslint-disable-next-line no-shadow
                updateConfig: data =>
                  store.dispatch(actionCreators.getConfig(data)),
邓晓峰's avatar
邓晓峰 committed
158
                isInit: false,
159
                logout: () => store.dispatch(actionCreators.logout()),
160 161 162
              },
              () => {
                (async () => {
163
                  (await (getToken() &&
164
                    window.globalConfig &&
165
                    window.globalConfig.token)) && initMicroApps(loader, store);
166 167 168 169 170 171
                })();
              },
              true,
            );
          }

邓晓峰's avatar
邓晓峰 committed
172
          // eslint-disable-next-line no-shadow
邓晓峰's avatar
邓晓峰 committed
173
        }
邓晓峰's avatar
邓晓峰 committed
174
        return res;
邓晓峰's avatar
邓晓峰 committed
175
      })
邓晓峰's avatar
邓晓峰 committed
176
      // eslint-disable-next-line no-shadow
邓晓峰's avatar
邓晓峰 committed
177
      .then(res => {
邓晓峰's avatar
邓晓峰 committed
178
        // eslint-disable-next-line no-use-before-define
179
        // initSensorType();
邓晓峰's avatar
邓晓峰 committed
180
        // eslint-disable-next-line no-use-before-define
181
        // initIsMock();
邓晓峰's avatar
邓晓峰 committed
182 183 184 185 186
        render({ appContent: '', loading: true });
      })
      .catch(error => {
        store.dispatch(actionCreators.getConfigError(error));
      });
dengxiaofeng's avatar
dengxiaofeng committed
187
  }
邓晓峰's avatar
邓晓峰 committed
188
};
叶飞's avatar
叶飞 committed
189

邓晓峰's avatar
邓晓峰 committed
190 191


192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
const initSensorType = () => {
  let filterProduct =
    (window.globalConfig && window.globalConfig.products) || [];
  filterProduct = filterProduct.filter(item =>
    PRODUCT_NAME.includes(item.PackageName),
  );
  if (filterProduct.length > 0) {
    appService.getSensorType().then(res => {
      store.dispatch(
        actionCreators.getConfig(
          Object.assign({}, window.globalConfig, {
            sensorType: res.data,
          }),
        ),
      );
    });
  }
};

const initIsMock = () => {
  appService
    .sysConfiguration({
      moduleName: '是否mock数据',
    })
    .then(res => {
      store.dispatch(
        actionCreators.getConfig(
          Object.assign({}, window.globalConfig, {
            isMock: res.data === '是',
          }),
        ),
      );
    });
};

邓晓峰's avatar
邓晓峰 committed
227 228
initGlobalConfig();
initLocale();
邓晓峰's avatar
邓晓峰 committed
229
window.share && window.share.event && window.share.event.on('triggerMicro', () => {
230
    initMicroApps(loader, store);
邓晓峰's avatar
邓晓峰 committed
231 232 233 234
});
window.share && window.share.event && window.share.event.on('initConfig', () => {
  initGlobalConfig();
});
邓晓峰's avatar
邓晓峰 committed
235

邓晓峰's avatar
邓晓峰 committed
236
if (pwa) {
237
  // const appPWA = window.i18n.getI18n('app');
邓晓峰's avatar
邓晓峰 committed
238
  window.addEventListener('sw.offline', () => {
239
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
邓晓峰's avatar
邓晓峰 committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  });

  window.addEventListener('sw.updated', event => {
    const e = event;
    const reloadSW = async () => {
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = msgEvent => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });
      window.location.reload(true);
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
272
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
邓晓峰's avatar
邓晓峰 committed
273 274 275
      </Button>
    );
    notification.open({
276 277 278 279
      message: useIntl().formatMessage({ id: 'pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({
        id: 'pwa.serviceworker.updated.hint',
      }),
邓晓峰's avatar
邓晓峰 committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
      btn,
      key,
      onClose: async () => null,
    });
  });
} else if ('serviceWorker' in navigator && isHttps) {
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then(sws => {
      sws.forEach(sw => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then(sw => {
    if (sw) sw.unregister();
  });

  if (window.caches && window.caches.keys) {
    caches.keys().then(keys => {
      keys.forEach(key => {
        caches.delete(key);
      });
    });
  }
}