BasicLayout.js 26.5 KB
Newer Older
杨思琦's avatar
杨思琦 committed
1 2 3 4 5 6 7 8 9
/* eslint-disable react/jsx-boolean-value */
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-return-assign */
/* eslint-disable no-shadow */
/* eslint-disable eqeqeq */
/* eslint-disable prettier/prettier */
/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable global-require */
邓晓峰's avatar
邓晓峰 committed
10
// @eslint-disable
杨思琦's avatar
杨思琦 committed
11
import React, { Suspense, useEffect, useRef, useState, useContext } from 'react';
邓晓峰's avatar
邓晓峰 committed
12

杨思琦's avatar
杨思琦 committed
13
import { ConfigProvider, Anchor, Modal, Popover, Radio, Spin, notification, Button } from 'antd';
14 15
import classNames from 'classnames';
import Cookies from 'js-cookie';
邓晓峰's avatar
邓晓峰 committed
16 17
import _ from 'lodash';
import memoized from 'nano-memoize';
杨思琦's avatar
杨思琦 committed
18
import KeepAlive from 'react-activation';
19
import { connect } from 'react-redux';
邓晓峰's avatar
邓晓峰 committed
20 21
import { matchRoutes } from 'react-router-dom';
import RightContent from '@/components/GlobalHeader/SimpleRiightContent';
崔佳豪's avatar
崔佳豪 committed
22
import defaultSetting from '@wisdom-utils/components/lib/AppLayout/layouts/defaultSettings';
邓晓峰's avatar
邓晓峰 committed
23
// import SettingDrawer from '@wisdom-utils/components/lib/layout/components/SettingDrawer';
24
import { actionCreators } from '@/containers/App/store';
邓晓峰's avatar
邓晓峰 committed
25 26
import Icon, { LoadingOutlined } from '@ant-design/icons';
import BasicLayout from '@wisdom-utils/components/lib/layout/BasicLayout';
27 28
import { useHistory, useLocation } from '@wisdom-utils/runtime';
import { helpers, store, event } from '@wisdom-utils/utils';
yzl's avatar
yzl committed
29
import { Storeage as Store } from '@wisdom-utils/utils/lib/helpers';
杨思琦's avatar
杨思琦 committed
30 31 32
import { defaultApp } from '@/micro';
import { appService } from '@/api';
import LoginAction from '@/pages/user/login/login';
33
import Loading from '../components/Loading';
邓晓峰's avatar
邓晓峰 committed
34 35
import { waterMark } from '../utils/mark';
import layoutStyles from './BasicLayout.less';
36 37
import SecurityLayout from './SecurityLayout';
import Site from './Site';
邓晓峰's avatar
邓晓峰 committed
38

邓晓峰's avatar
邓晓峰 committed
39
const { params } = helpers;
邓晓峰's avatar
邓晓峰 committed
40 41 42 43 44

// const ArcgisMap = React.lazy(() => import('../pages/map/arcgis'));
// const AMap = React.lazy(() => import('../pages/map/amap'));
const CesiumMap = React.lazy(() => import('../pages/map/cesiumMap'));

45 46
const waitTime = (time = 100) =>
  new Promise(resolve => {
邓晓峰's avatar
邓晓峰 committed
47 48 49 50
    setTimeout(() => {
      resolve(true);
    }, time);
  });
51
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;
邹绪超's avatar
邹绪超 committed
52
const arrowSvg = ({ fillColor = '#fff' }) => (
53
  <svg
54 55 56 57 58 59 60
    t="1543324489942"
    className="icon"
    viewBox="0 0 1024 1024"
    version="1.1"
    xmlns="http://www.w3.org/2000/svg"
    width="16"
    height="16"
61 62
  >
    <path
63 64
      d="M511.700683 639.423111 191.917496 319.596945 319.830771 319.596945 511.700683 511.715521 703.570595 319.596945 831.48387 319.596945Z"
      p-id="8626"
65
    // fill={fillColor}
66
    />
邓晓峰's avatar
邓晓峰 committed
67 68
  </svg>
);
邹绪超's avatar
邹绪超 committed
69
const ArrowIcon = props => <Icon component={arrowSvg} {...props} />;
70
const optionsWith = [{ label: '按站点', value: 'site' }, { label: '按城市', value: 'city' }];
71
const HOT = ['HOT', '县', '市', 'New'];
杨思琦's avatar
杨思琦 committed
72
const StationsItem = (item, action, onChangeVisible, actionRef, setMenuLoading, cityData) => {
73
  const changeGroup = (event, data) => {
邓晓峰's avatar
邓晓峰 committed
74
    action.changeGroup && action.changeGroup(event, data, onChangeVisible, actionRef);
杨思琦's avatar
杨思琦 committed
75
    window.share.event.emit('updateSite', { ...cityData, currentStationName: data.groupName });
邓晓峰's avatar
邓晓峰 committed
76
    setMenuLoading && setMenuLoading(true);
77 78
  };
  return (
79
    <li key={item.groupID} style={{ marginRight: `${item.style.marginRight}px` }}>
80
      <a
邓晓峰's avatar
邓晓峰 committed
81
        className={classNames(layoutStyles.city_select, layoutStyles.showTip)}
82 83 84 85 86 87
        title={item.city}
        index={item.promoteIndex}
        style={{ fontSize: '13px' }}
        onClick={event => changeGroup(event, item)}
      >
        {item.groupName}
88
        {item.promoteTip && HOT.includes(item.promoteTip) && <div title={`${item.promoteTip}`}>{item.promoteTip}</div>}
89 90 91 92 93
      </a>
    </li>
  );
};

94 95 96
const OnlyFocusStations = props => {
  const data = props.data.stations;
  return (
97
    <Spin spinning={props.loading} tip="加载中" size="small">
98
      <div className={layoutStyles.focusStations} style={{ border: 'none' }}>
99 100
        <ul>
          {Array.isArray(data)
杨思琦's avatar
杨思琦 committed
101
            ? data.map(item => StationsItem(item, props.action, props.setVisible, props.actionRef, props.setMenuLoading, props.data))
102 103
            : null}
        </ul>
104 105
      </div>
    </Spin>
106 107
  );
};
108
const AllStations = props => {
109 110 111 112 113
  const data = props.data.stations;
  const [targetOffset, setTargetOffset] = useState(undefined);
  const cityPane = useRef(null);
  const cityContent = useRef(null);
  const [defaultTab, setDefaultTab] = useState('site');
徐乐's avatar
徐乐 committed
114

115 116 117 118 119 120 121 122 123 124 125 126
  useEffect(() => {
    setTargetOffset(cityPane.current.clientHeight / 2);
  }, []);

  const handleClick = (event, link) => {
    event.preventDefault();
  };

  const handleTabChange = event => {
    setDefaultTab(event.target.value);
  };
  return (
127
    <Spin spinning={props.loading} tip="加载中">
邓晓峰's avatar
邓晓峰 committed
128
      <div className={layoutStyles.focusStations}>
129 130 131
        <ul>
          {Array.isArray(data)
            ? data.map(item =>
杨思琦's avatar
杨思琦 committed
132
              StationsItem(item, props.action, props.setVisible, props.actionRef, props.setMenuLoading, props.data),
133
            )
134 135
            : null}
        </ul>
136 137 138
      </div>
      <Radio.Group
        options={optionsWith}
139 140 141
        optionType="button"
        buttonStyle="solid"
        size="small"
142 143 144 145 146 147
        value={defaultTab}
        onChange={handleTabChange}
        style={{ marginTop: '6px' }}
      />
      <div style={{ maxWidth: '520px', position: 'relative' }}>
        {defaultTab === 'site' ? (
148
          <div className={classNames(layoutStyles.city_pane, layoutStyles.station_container)} ref={cityPane}>
149 150 151 152 153 154
            <Anchor
              affix={false}
              onClick={handleClick}
              targetOffset={targetOffset}
              getContainer={() => cityContent.current}
            >
邓晓峰's avatar
邓晓峰 committed
155
              <ul className={layoutStyles.py}>
156
                {props.data && props.data.siteCityList && props.data.siteCityList.letters}
157
              </ul>
158 159
              <div className={layoutStyles.cityContent} style={{ height: '335px' }} ref={cityContent}>
                {props.data && props.data.siteCityList && props.data.siteCityList.content}
160 161 162 163
              </div>
            </Anchor>
          </div>
        ) : (
164
          <div className="city_pane city_container">{props.data.citySelector}</div>
165 166
        )}
      </div>
167
    </Spin>
168 169 170
  );
};

171
const Stations = props => {
172
  const isAll =
173 174 175 176
    props.data &&
    props.data.siteCityList &&
    ((props.data.siteCityList.letters && props.data.siteCityList.letters.length) ||
      (props.data.siteCityList.content && props.data.siteCityList.content.length));
177 178
  return isAll ? <AllStations {...props} /> : <OnlyFocusStations {...props} />;
};
179

邓晓峰's avatar
邓晓峰 committed
180
const renderSite = ({ data, config, loading, setLoading, action, actionRef, setMenuLoading }) => {
邓晓峰's avatar
邓晓峰 committed
181 182 183
  const [visible, setVisible] = useState(false);
  let loaded = !!((data && !data.stations) || (Array.isArray(data.weathers) && data.weathers.length === 0));
  if (config && config.userInfo && config.userInfo.site === '') {
184
    loaded = false;
185
  }
186
  if (!data.allStation || !_.isArray(data.allStation) || data.allStation.length <= 1) return <></>;
邓晓峰's avatar
邓晓峰 committed
187 188
  return (
    <>
邓晓峰's avatar
邓晓峰 committed
189
      <Spin
邹绪超's avatar
邹绪超 committed
190 191
        indicator={antIcon}
        spinning={loaded}
192
        size="small"
邹绪超's avatar
邹绪超 committed
193
        style={{ marginLeft: '10px' }}
194
        tip=""
195 196
        wrapperClassName={layoutStyles.spinLoadding}
      >
邹绪超's avatar
邹绪超 committed
197 198
        <>
          <Popover
199 200
            placement="bottomLeft"
            trigger="click"
201
            visible={visible}
邹绪超's avatar
邹绪超 committed
202
            content={
203 204 205 206 207 208 209 210 211
              <Stations
                data={data}
                loading={loading}
                setLoading={setLoading}
                setVisible={setVisible}
                action={action}
                actionRef={actionRef}
                setMenuLoading={setMenuLoading}
              />
邹绪超's avatar
邹绪超 committed
212 213
            }
            arrowPointAtCenter
邓晓峰's avatar
邓晓峰 committed
214
            overlayClassName={classNames(layoutStyles.stationsWrapper, layoutStyles.stationsTop)}
杨思琦's avatar
杨思琦 committed
215
            onVisibleChange={value => setVisible(value)}
邹绪超's avatar
邹绪超 committed
216
          >
217 218
            {Array.isArray(data.stations) ? (
              <div className={layoutStyles.toggleSite}>
杨思琦's avatar
杨思琦 committed
219
                <img src={require('../assets/basic/site.png')} className={layoutStyles.site} alt="" />
220 221 222
                <span className={layoutStyles.name}>{data.currentStationName}</span>
                <ArrowIcon
                  className={layoutStyles.arrow}
邓晓峰's avatar
邓晓峰 committed
223
                  // fillColor="#fff"
224 225 226 227 228 229
                  style={{
                    transform: !visible ? `rotate(0deg)` : `rotate(180deg)`,
                  }}
                />
              </div>
            ) : null}
邹绪超's avatar
邹绪超 committed
230 231 232
          </Popover>
        </>
      </Spin>
邓晓峰's avatar
邓晓峰 committed
233
    </>
234 235
  );
};
徐乐's avatar
徐乐 committed
236

邓晓峰's avatar
邓晓峰 committed
237 238
// import defaultProps from '../defaultProps';
const pickRoutes = memoized((routes, pathname, locale) => {
239 240
  const matches = matchRoutes(routes, { pathname });
  const routeConfig = matches ? matches[matches.length - 1].route : null;
邓晓峰's avatar
邓晓峰 committed
241

242 243 244 245 246 247
  return {
    locale, // just for cache
    routeConfig,
    // matchPath: matches ? matches.map(match => _.replace(match.route.path,'/*','')).join('/') : null // 解决下微端/*路径的问题
    matchPath: routeConfig ? _.replace(routeConfig.key, '/*', '') : '',
  };
邓晓峰's avatar
邓晓峰 committed
248 249
});

250
const Layout = props => {
251 252 253
  const currentProduct = `__global__recent_productIndex__micro_${window.location.hostname}_${params.getParams(
    'client',
  ) ||
254 255
    sessionStorage.getItem('client') ||
    'city'}`;
yzl's avatar
yzl committed
256
  const menuState = sessionStorage.getItem('menuState') || 'open';
257 258
  const [cityData, setCityData] = useState({});
  const [siteLoading, setSiteLoading] = useState(false);
259
  const [siteAction, setSiteAction] = useState(() => new Site(props, setSiteLoading));
杨思琦's avatar
杨思琦 committed
260
  const [cityLoading, setCityLoading] = useState(false);
邓晓峰's avatar
邓晓峰 committed
261
  const [menuLoading, setMenuLoading] = useState(true);
262
  const [subLoading, setSubLoading] = useState(true);
杨思琦's avatar
杨思琦 committed
263
  const [initWebContent, setInitWebContent] = useState(false);
徐乐's avatar
徐乐 committed
264 265
  const [integrationData, setIntegrationData] = useState([]);
  const [loginAction, setAction] = useState(() => new LoginAction(props));
邓晓峰's avatar
邓晓峰 committed
266 267 268 269
  // const [settings, setSetting] = useState({});
  // const [routeConfig, setRouteConfig] = useState(null);
  // const [matchPath, setMatchPath] = useState('');
  const actionRef = useRef();
270
  const history = useHistory();
邓晓峰's avatar
邓晓峰 committed
271
  const location = useLocation();
徐乐's avatar
徐乐 committed
272 273
  const [visible, setVisible] = useState(false);
  const [integrationLoading, setIntegrationLoading] = useState(false);
邓晓峰's avatar
邓晓峰 committed
274
  const { routeConfig = {}, matchPath } = pickRoutes(props.flatMenu, location.pathname);
杨思琦's avatar
杨思琦 committed
275 276
  const context = useContext(ConfigProvider.ConfigContext);
  const prefixCls = props.prefixCls ?? context.getPrefixCls();
徐乐's avatar
徐乐 committed
277
  const [first, setFirst] = useState(true);
邓晓峰's avatar
邓晓峰 committed
278 279 280 281 282 283
  // useEffect(() => {

  //   setRouteConfig(routeConfig);
  //   setMatchPath(match)
  // }, [location.pathname])

284 285 286 287
  useEffect(() => {
    event.on('loading', ret => {
      setSubLoading(ret);
    });
杨思琦's avatar
杨思琦 committed
288 289 290
    event.on('initweb', ret => {
      setInitWebContent(ret);
    });
杨思琦's avatar
杨思琦 committed
291
    event.on('finishInitWeb', path => {
292 293
      const urlParams = path.split('/').slice(-1) ?? 'civweb4';
      window.history.replaceState(null, null, path.replace(urlParams, ''));
杨思琦's avatar
杨思琦 committed
294 295 296 297 298
      setTimeout(() => {
        setInitWebContent(false);
        window.history.replaceState(null, null, path);
      });
    });
299 300
  }, []);

301
  useEffect(() => {
崔佳豪's avatar
崔佳豪 committed
302
    siteAction.setGlobalConfig(props.global);
303
    const tk = Cookies.get('token') || props.global.token;
304
    const isLogin = tk !== null && tk !== 'undefined' && tk !== void 0;
杨思琦's avatar
杨思琦 committed
305 306 307 308 309 310 311 312
    let client = props?.global?.client || sessionStorage.getItem('client') || null;
    client = client !== 'undefined' && !_.isNull(client) && !_.isUndefined(client) ? client : 'city';
    // eslint-disable-next-line no-prototype-builtins
    let generateType = props.global && props.global.hasOwnProperty('get') ? props.global.get('generateType') : null;
    generateType =
      !_.isNull(generateType) && !_.isUndefined(generateType) && generateType !== 'undefined'
        ? `&generateType=${generateType}`
        : '';
313
    if (!isLogin) {
314
      history.push(`/user/login?client=${client}${generateType}`, { reload: true });
315 316
      props.logout();
    }
杨思琦's avatar
杨思琦 committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    store.on('event:unauthorized', () => {
      store.off('event:unauthorized');
      const key = `open${Date.now()}`;
      notification.open({
        description: '登录认证过期,即将跳转到登录页',
        duration: null,
        btn: (
          <Button
            className={classNames(`${prefixCls}-btn`, `${prefixCls}-btn-primary`)}
            type="primary"
            onClick={() => {
              notification.close(key);
              setTimeout(() => {
                history.push(`/user/login?client=${client}${generateType}`, { reload: true });
                props.logout();
              })
            }}>确认
          </Button>
        ),
        key,
        closeIcon: <></>,
      });
    });
    return () => {
      store.off('event:unauthorized');
    };
  }, [history, prefixCls, props, props.global, siteAction]);
344 345

  useEffect(() => {
346 347 348 349 350
    if (
      props.global &&
      props.global.userInfo &&
      props.global.userInfo.token !== null &&
      props.global.userInfo.loginName &&
杨思琦's avatar
杨思琦 committed
351 352
      Object.keys(cityData).length === 0 &&
      !cityLoading
353
    ) {
杨思琦's avatar
杨思琦 committed
354 355
      setCityLoading(true);
      siteAction.getCityStationsForUser(props.global.userInfo?.Groups).then(res => {
356
        setCityData(res);
杨思琦's avatar
杨思琦 committed
357
        setCityLoading(false);
358 359
      });
    }
杨思琦's avatar
杨思琦 committed
360
  }, [cityData, cityLoading, props.global, props.global.userInfo, siteAction]);
361

杨思琦's avatar
杨思琦 committed
362
  const GetIntegrationConfig = () => {
徐乐's avatar
徐乐 committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    if (first) {
      appService
        .GetIntegrationConfig({
          type: '集成登录',
          userId: window.globalConfig.userInfo?.OID ?? null,
          isEnable: true,
        })
        .then(res => {
          setFirst(false);
          const { code, data } = res;
          if (code == '0') {
            setIntegrationData(data);
          } else {
            setIntegrationData([]);
          }
        })
    }

杨思琦's avatar
杨思琦 committed
381 382
  }

邓晓峰's avatar
邓晓峰 committed
383
  useEffect(() => {
徐乐's avatar
徐乐 committed
384
    if (window?.globalConfig?.isIntegration >= 1) {
徐乐's avatar
徐乐 committed
385 386
      GetIntegrationConfig();
    }
387
    window.share.event.on('updateSite', res => {
388
      setCityData(res);
389
    });
徐乐's avatar
徐乐 committed
390 391 392 393

    const handleToggleIndustry = event => {
      setVisible(false);
      setIntegrationLoading(false);
徐乐's avatar
徐乐 committed
394
      props.history.push(`/?client=${window.globalConfig.client}`);
徐乐's avatar
徐乐 committed
395 396 397 398
      props.updateCurrentIndex(0);
      defaultApp();
    };

徐乐's avatar
徐乐 committed
399
    if (window?.globalConfig?.isIntegration >= 1) {
徐乐's avatar
徐乐 committed
400 401 402
      loginAction.events.on('toggleIndustry', handleToggleIndustry);
    }

邓晓峰's avatar
邓晓峰 committed
403 404
    return () => {
      window.share.event.removeAllListeners('updateSite');
徐乐's avatar
徐乐 committed
405
      loginAction.events.removeListener('toggleIndustry', handleToggleIndustry);
邓晓峰's avatar
邓晓峰 committed
406
    };
杨思琦's avatar
杨思琦 committed
407
  }, [loginAction.events, props]);
邓晓峰's avatar
邓晓峰 committed
408

409 410
  useEffect(() => {
    const needMark = () =>
崔佳豪's avatar
崔佳豪 committed
411
      (props.global.isHaveMark || window.location.origin.replace(/^(http|https):\/\//, '') === 'panda-water.cn') &&
412
      document.querySelectorAll('.pandawatermark_mask_div').length <= 0 &&
413 414
      props.global.userInfo;
    if (needMark()) {
415
      waterMark({
416
        watermark_txt: `${props.global.userInfo.fullName}${props.global.userInfo.loginName})`,
417 418
      });
    }
419
    return () => {
420 421
      const marks = document.querySelectorAll('.pandawatermark_mask_div');
      if (marks && marks.length) {
422
        Array.prototype.forEach.call(marks, function (dom, index) {
423 424
          document.body.removeChild(dom);
        });
425
      }
426
    };
427
  }, [props.global.isHaveMark, props.global.userInfo]);
428

邓晓峰's avatar
邓晓峰 committed
429
  const onMenuHeaderClick = event => {
杨思琦's avatar
杨思琦 committed
430
    // 集成网站
徐乐's avatar
徐乐 committed
431
    if (window.globalConfig.isIntegration > 1 || integrationData.length > 1) {
432 433 434
      // window.qiankunIsCache = false;
      history.push('/Industry');
    }
435
    // 非云平台不做响应
436
    if (!props.global.get('userInfo.site')) return;
437 438 439

    // 至少2个行业才能回到引导页
    const Industries = props.global.get('userInfo.Industries');
440
    if (Industries && Industries.length > 1) {
杨思琦's avatar
杨思琦 committed
441
      window.qiankunIsCache = false;
442
      history.push('/Industry');
443
    }
邓晓峰's avatar
邓晓峰 committed
444
  };
邓晓峰's avatar
邓晓峰 committed
445 446 447
  // useEffect(async () => {
  //   setMenuLoading(false);
  // }, [props.menu]);
邓晓峰's avatar
邓晓峰 committed
448

邓晓峰's avatar
邓晓峰 committed
449 450 451 452
  const onTopMenuHeaderClick = index => {
    props.updateCurrentIndex(index);
    window.share && window.share.event.emit('trigger:updateMenuIndex', index);
    store.set('updateMenuIndex', index);
453
  };
邓晓峰's avatar
邓晓峰 committed
454

455 456 457
  const logo =
    props.global && _.isFunction(props.global.get) && props.global.get('bannerLogo')
      ? props.global &&
458 459
      _.isFunction(props.global.transformDevAssetsBaseURL) &&
      props.global.transformDevAssetsBaseURL(props.global.get('bannerLogo'))
460
      : defaultSetting.logo;
461

462 463 464 465 466
  // 添加一个路由跳转事件
  useEffect(() => {
    const { share, history } = window;
    const findMenuPath = (flatMenu, url) => {
      const [path, param = ''] = url.split('|');
467
      const params = param.split('&').reduce((pre, item) => {
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        if (!item) return pre;
        const [key, value] = item.split('=');
        pre[key] = value;
        return pre;
      }, {});
      let menu = null;
      if (params.widget) {
        menu = flatMenu.find(item => item.params && item.params.widget === params.widget); // 根据widget匹配菜单
      } else {
        menu = flatMenu.find(item => item.path.indexOf(path) > -1); // 根据路径匹配菜单
      }
      return menu ? menu.path.replace(/^\//, '') : '';
    };
    const skipHandler = (data, title, url) => {
      const targetMenuPath = findMenuPath(props.flatMenu, url);
483

484 485 486
      if (targetMenuPath) {
        history.pushState(data, title, `/civbase/${targetMenuPath}`);
      }
487
    };
488 489 490
    share && share.event && share.event.on('route:pushState', skipHandler);
    return () => {
      share && share.event && share.event.removeListener('route:pushState', skipHandler);
491
    };
492
  }, [props.flatMenu]);
493

494 495
  if (props.global && props.global.userInfo) {
    if (!props.global.userInfo.site) {
496 497 498
      props.global.userInfo.site = '';
    }
  }
499
  const getParams = pathname => {
杨思琦's avatar
杨思琦 committed
500 501
    const ret = {};
    const url = pathname || decodeURIComponent(window.location.pathname);
502 503

    if (url.indexOf('|') > -1) {
杨思琦's avatar
杨思琦 committed
504
      const params = url.split('|')[1];
505
      params.split('&').map(function (item) {
506 507 508 509 510 511 512 513 514 515 516 517
        return (ret[item.split('=')[0]] = item.split('=')[1]);
      });
      return ret;
    }

    return ret;
  };
  const isHaveMap = () => {
    const params = getParams();
    if (params.loadMap === 'true') {
      return true;
    }
杨思琦's avatar
杨思琦 committed
518
    return false;
519
  };
徐乐's avatar
徐乐 committed
520

杨思琦's avatar
杨思琦 committed
521
  // 渲染集成站点切换弹框
徐乐's avatar
徐乐 committed
522 523 524 525
  const renderIntegration = (inData, loginAction, props) => {
    if (inData.length <= 1) {
      return <></>
    }
杨思琦's avatar
杨思琦 committed
526
    const choiceOne = inData?.find(function (a) {
徐乐's avatar
徐乐 committed
527 528 529
      return a.url?.indexOf(window?.globalConfig?.client) >= 0
    })

杨思琦's avatar
杨思琦 committed
530
    // 切换集成站点
徐乐's avatar
徐乐 committed
531 532
    const checkIntegration = (val, loginAction, props) => {
      if (val.subType == '外链') {
徐乐's avatar
徐乐 committed
533
        if (val.paramValue == 'ticket') {
杨思琦's avatar
杨思琦 committed
534
          // 获取临时token
徐乐's avatar
徐乐 committed
535 536 537
          appService.getTicketByToken({ token: window.globalConfig?.token }).then(res => {
            if (res.code === 0) {
              setVisible(false);
538
              const url = `${val.url + (val.url.indexOf('?') > 0 ? '&' : '?') + val.paramName}=${res.data}`;
徐乐's avatar
徐乐 committed
539 540 541 542 543 544 545 546 547 548 549 550
              window.open(url, "_blank");
            } else {
              setVisible(false);
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          });
        } else {
          setVisible(false);
551
          const url = `${val.url + (val.url.indexOf('?') > 0 ? '&' : '?') + val.paramName}=${window.globalConfig?.token}`;
徐乐's avatar
徐乐 committed
552 553
          window.open(url, "_blank");
        }
徐乐's avatar
徐乐 committed
554
      } else {
555 556 557
        if (window.qiankunIsCache) {
          store.set('event:refreshCurrentMenu', {
            dropCache: true,
杨思琦's avatar
杨思琦 committed
558
            action: 'closeAllTabs'
559 560
          })
        }
杨思琦's avatar
杨思琦 committed
561
        const cli = val.url?.indexOf('client=') >= 0 ? val.url.split('client=')[1] : '';
徐乐's avatar
徐乐 committed
562 563 564 565 566 567 568 569 570 571
        Cookies.set('client', cli, {
          expires: 86400000 / (24 * 60 * 60 * 1000),
          path: '/',
        });
        sessionStorage.setItem('client', cli);
        const currentProduct = `__global__recent_productIndex__micro_${window.location.hostname}_${window.globalConfig?.client ?? 'city'}`;
        sessionStorage.removeItem(currentProduct);
        const currentProductNew = `__global__recent_productIndex__micro_${window.location.hostname}_${cli || 'city'}`;
        sessionStorage.setItem(currentProductNew, 0);

徐乐's avatar
徐乐 committed
572 573 574 575 576
        setIntegrationLoading(true);
        const config = props.global;
        config.uiwidgets = [];
        config.widgets = [];
        config.allWidgets = [];
杨思琦's avatar
杨思琦 committed
577
        window.qiankunStarted = false;
徐乐's avatar
徐乐 committed
578 579 580
        if (cli) {
          config.client = cli;
        }
徐乐's avatar
徐乐 committed
581
        loginAction && loginAction.getUserInfoAndConfig('', true, val.type);
徐乐's avatar
徐乐 committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        // props.history.push(`/?client=${cli}`);
        // props.updateCurrentIndex(0);
        // defaultApp();
      }
    }

    return (
      <>
        <Popover
          placement="bottomLeft"
          trigger="click"
          visible={visible}
          content={
            <div className={layoutStyles.integrationList}>
              {
                <Loading loading={integrationLoading} />
              }
              {
                inData && inData.map((val) => (
                  <p onClick={() => checkIntegration(val, loginAction, props)}>{val.name}</p>
                ))
              }
            </div>
          }
          arrowPointAtCenter
          overlayClassName={classNames(layoutStyles.stationsWrapper, layoutStyles.stationsTop2)}
          onVisibleChange={visible => setVisible(visible)}
        >
          {inData.length > 1 ? (
            <div className={layoutStyles.toggleSite}>
              <img src={require('../assets/basic/site.png')} className={layoutStyles.site} />
              <span className={layoutStyles.name}>{choiceOne?.name ?? ''}</span>
              <ArrowIcon
                className={layoutStyles.arrow}
                style={{
                  transform: !visible ? `rotate(0deg)` : `rotate(180deg)`,
                }}
              />
            </div>
          ) : null}
        </Popover>
      </>
    )
  }

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
  // 菜单比对方法
  const querySkipUrl = (data, url) => {
    let res = null;
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < data.length; i++) {
      if (url.indexOf(data[i].url) > -1) {
        res = data[i];
        return data[i];
      }
      if (data[i].widgets && data[i].widgets.length > 0) {
        res = querySkipUrl(data[i].widgets, url);
      }
      if (res) break;
    }
    return res;
  };

  // 功能访问记录
  const menuJumpLogs = data => {
    const { pathname = '' } = data;
    const pathList = querySkipUrl(window?.globalConfig?.widgets || [], pathname);
    if (pathname && pathList) {
      appService.pvLogs({
        origin: window.location.origin,
        client: window?.globalConfig.client,
        site: window?.globalConfig?.userInfo?.site || '',
        widgetUrl: pathList?.url || '',
        widgetRoute: pathList?.widgetId || '',
        widgetName: pathList?.label || '',
        isHomepage: 'false',
        userName: window?.globalConfig?.userInfo?.fullName || '',
      });
    }
  };

662
  return (
yzl's avatar
yzl committed
663 664 665 666 667 668
    <SecurityLayout {...props}>
      <BasicLayout
        title={props.global.title}
        route={props.route}
        location={location}
        navTheme={props.global?.variableTheme?.navTheme ?? 'dark'}
669
        homepage={props.global?.homepage ?? ''}
杨思琦's avatar
杨思琦 committed
670
        redirect={props.global?.redirect ?? ''}
671
        mode="MDI"
yzl's avatar
yzl committed
672 673 674
        fixedHeader
        headerHeight={52}
        routeConfig={routeConfig}
杨思琦's avatar
杨思琦 committed
675
        isCache={window?.qiankunIsCache}
yzl's avatar
yzl committed
676 677 678 679 680 681
        matchPath={matchPath}
        actionRef={actionRef}
        menu={{
          loading: menuLoading,
          // onLoadingChange: (loading) => setMenuLoading(loading)
        }}
682
        hideFeedback={props.global.hideFeedback}
yzl's avatar
yzl committed
683
        logo={logo}
684
        topMenuActiveKey={Number(sessionStorage.getItem(currentProduct)) || 0}
yzl's avatar
yzl committed
685
        rightContentRender={() => <RightContent />}
686 687 688 689 690 691
        onPageChange={data => {
          try {
            menuJumpLogs(data);
          } catch (err) {
            // console.log(err);
          }
yzl's avatar
yzl committed
692 693 694 695 696 697 698 699 700 701 702
          // if(!props.global.token) {
          //   history.push('/user/login')
          // }
        }}
        onMenuHeaderClick={onMenuHeaderClick}
        onTopMenuHeaderClick={onTopMenuHeaderClick}
        menuProps={{
          popupClassName: 'testpop',
          popupOffset: [0, 15],
        }}
        headerSiteRender={() =>
徐乐's avatar
徐乐 committed
703
          window?.globalConfig?.isIntegration >= 1
徐乐's avatar
徐乐 committed
704 705 706 707 708 709 710 711 712 713 714 715
            ?
            renderIntegration(integrationData, loginAction, props)
            :
            renderSite({
              data: cityData,
              config: props.global,
              loading: siteLoading,
              setLoading: setSiteLoading,
              action: siteAction,
              actionRef,
              setMenuLoading,
            })
yzl's avatar
yzl committed
716 717 718
        }
        menuItemRender={(item, dom) => (
          <a
719
            onClick={event => {
yzl's avatar
yzl committed
720
              event.preventDefault();
721
              window.history.pushState(null, '', `/civbase${item.path}`);
722
            }}
邓晓峰's avatar
邓晓峰 committed
723
          >
yzl's avatar
yzl committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
            {dom}
          </a>
        )}
      >
        <Suspense fallback={<></>}>
          {/* {window.location.pathname.startsWith('/civbase/civ_3d') ? ( */}
          {/*  <KeepAlive> */}
          {/*    <CesiumMap /> */}
          {/*  </KeepAlive> */}
          {/* ) : window.location.pathname.startsWith('/civbase/civ_webgis') ? ( */}
          {/*  mapMode === 'AMap' ? ( */}
          {/*    <AMap /> */}
          {/*  ) : ( */}
          {/*    <ArcgisMap options={{ type: 'ArcgisMap' }} /> */}
          {/*  ) */}
          {/* ) : null} */}
杨思琦's avatar
杨思琦 committed
740
          {/* <AliveScope> */}
741 742 743 744 745 746 747
          {window.location.pathname.startsWith('/civbase/civ_3d/map') || isHaveMap() ? (
            <KeepAlive when={true}>
              <CesiumMap />
            </KeepAlive>
          ) : (
            window.location.pathname.startsWith('/civbase/civ_webgis') && null
          )}
杨思琦's avatar
杨思琦 committed
748
          {/* </AliveScope> */}
yzl's avatar
yzl committed
749 750
        </Suspense>

751
        <div id="micro-container" className="subapp-container">
yzl's avatar
yzl committed
752 753
          {props.children}
        </div>
杨思琦's avatar
杨思琦 committed
754 755
        {subLoading && <Loading loading={subLoading} />}
        {initWebContent && <Loading loading={initWebContent} />}
yzl's avatar
yzl committed
756 757
      </BasicLayout>
    </SecurityLayout>
758
  );
759
};
760

761 762 763 764
const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  menu: state.getIn(['global', 'menu']),
  flatMenu: state.getIn(['global', 'flatMenu']),
徐乐's avatar
徐乐 committed
765
  instance: state.getIn(['global', 'instance']),
邓晓峰's avatar
邓晓峰 committed
766
  currentMenuIndex: state.getIn(['global', 'currentMenuIndex']),
767 768 769 770 771 772 773 774 775 776 777 778 779
});
const mapDispatchToProps = dispatch => ({
  updageSetting(setting) {
    dispatch(actionCreators.updageSetting(setting));
  },
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
  logout() {
    dispatch(actionCreators.logout());
780
  },
781 782 783 784
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
邓晓峰's avatar
邓晓峰 committed
785
)(Layout);