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

邓晓峰's avatar
邓晓峰 committed
15 16 17 18 19
import {
  Button,
  message,
  notification,
} from 'antd';
dengxiaofeng's avatar
dengxiaofeng committed
20 21
import { ConnectedRouter } from 'connected-react-router/immutable';
import Immutable from 'immutable';
邓晓峰's avatar
邓晓峰 committed
22 23 24 25
import {
  params,
  Storeage,
} from 'kit_utils';
dengxiaofeng's avatar
dengxiaofeng committed
26
import { Provider } from 'react-redux';
27 28 29 30 31

import { useIntl } from '@/locales/localeExports';
import { ErrorBoundary } from '@ant-design/pro-utils';
import { history } from '@wisdom-utils/runtime';

邓晓峰's avatar
邓晓峰 committed
32
import defaultSettings from '../config/defaultSetting';
33 34 35
// import themePluginConfig from '../config/themePluginConfig';
import { appService } from './api';
import { updateTheme } from './common/helpers/settingColor';
邓晓峰's avatar
邓晓峰 committed
36
import Container from './components/Container';
dengxiaofeng's avatar
dengxiaofeng committed
37 38 39
import configureStore from './configureStore';
import App from './containers/App';
import { actionCreators } from './containers/App/store';
40
import { LocaleContainer } from './locales/locale';
邓晓峰's avatar
邓晓峰 committed
41
import { initMicroApps } from './micro';
邓晓峰's avatar
邓晓峰 committed
42
import Login from './pages/user/login/login';
邓晓峰's avatar
邓晓峰 committed
43 44 45 46
import {
  getToken,
  isString,
} from './utils/utils';
47
import './utils/event';
48
import Cookies from 'js-cookie';
邓晓峰's avatar
邓晓峰 committed
49 50 51 52
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
53
window.createStoreage = new Storeage(namespace);
邓晓峰's avatar
邓晓峰 committed
54
// eslint-disable-next-line no-underscore-dangle
dengxiaofeng's avatar
dengxiaofeng committed
55 56
const initialState = Immutable.Map();
const store = configureStore(initialState, history);
57 58 59
const MOUNT_NODE = document.getElementById('root');

// window.umi_plugin_ant_themeVar = themePluginConfig.theme;
dengxiaofeng's avatar
dengxiaofeng committed
60
const render = () => {
邓晓峰's avatar
邓晓峰 committed
61
  // eslint-disable-next-line react-hooks/rules-of-hooks
dengxiaofeng's avatar
dengxiaofeng committed
62 63 64
  ReactDOM.render(
    <Provider store={store}>
      <ConnectedRouter history={history}>
65
        <LocaleContainer>
邓晓峰's avatar
邓晓峰 committed
66 67 68 69 70
          <ErrorBoundary>
            <Container>
              <App />
            </Container>
          </ErrorBoundary>
71
        </LocaleContainer>
dengxiaofeng's avatar
dengxiaofeng committed
72 73 74 75 76
      </ConnectedRouter>
    </Provider>,
    MOUNT_NODE,
  );
};
邓晓峰's avatar
邓晓峰 committed
77

dengxiaofeng's avatar
dengxiaofeng committed
78 79 80
const loader = (appContent, loading) => render({ appContent, loading });

const initLocale = () => {
邓晓峰's avatar
邓晓峰 committed
81 82
  localStorage.setItem('umi_locale', 'zh-CN');
};
83
const PRODUCT_NAME = ['civ_water', 'civ_monitor'];
dengxiaofeng's avatar
dengxiaofeng committed
84 85

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

邓晓峰's avatar
邓晓峰 committed
100
  // eslint-disable-next-line no-undef
邓晓峰's avatar
邓晓峰 committed
101
  if (!createStoreage.get('globalConfig')) {
邓晓峰's avatar
邓晓峰 committed
102
    window.createStoreage = new Storeage(namespace);
dengxiaofeng's avatar
dengxiaofeng committed
103
  }
104
  if (!getToken()) {
邓晓峰's avatar
邓晓峰 committed
105 106
    localStorage.removeItem('loginSite');
  }
107

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

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

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

189 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
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
224 225
initGlobalConfig();
initLocale();
邓晓峰's avatar
邓晓峰 committed
226
window.share &&
邓晓峰's avatar
邓晓峰 committed
227 228
  window.share.event &&
  window.share.event.on('triggerMicro', () => {
229
    initMicroApps(loader, store);
邓晓峰's avatar
邓晓峰 committed
230
  });
邓晓峰's avatar
邓晓峰 committed
231

邓晓峰's avatar
邓晓峰 committed
232 233

if (pwa) {
234
  // const appPWA = window.i18n.getI18n('app');
邓晓峰's avatar
邓晓峰 committed
235
  window.addEventListener('sw.offline', () => {
236
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
邓晓峰's avatar
邓晓峰 committed
237 238 239 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
  });

  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();
        }}
      >
269
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
邓晓峰's avatar
邓晓峰 committed
270 271 272
      </Button>
    );
    notification.open({
273 274 275 276
      message: useIntl().formatMessage({ id: 'pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({
        id: 'pwa.serviceworker.updated.hint',
      }),
邓晓峰's avatar
邓晓峰 committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
      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);
      });
    });
  }
}