index.js 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
/* eslint-disable prettier/prettier */

import React, { useEffect, useState, useCallback, useRef } from 'react';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { actionCreators } from '@/containers/App/store';
import { store } from '@wisdom-utils/utils';
import LoginAction from '@/pages/user/login/login';
import Cookies from 'js-cookie';
10
import { notification, Tooltip, message } from 'antd';
11 12 13 14 15
import homeIcon from '@/assets/bootPage/集成登录.png';
import { appService } from '@/api';
import axios from 'axios';
import { defaultApp } from '@/micro';
import { useHistory } from '@wisdom-utils/runtime';
16
import LoadPage from '@/components/LoadPage';
17
import { getUserInfo, getWebSiteConfig } from '@/api/service/base';
18
import { goToPath, searchUrl } from '@/utils/utils';
19
import styles from './index.less';
20 21 22 23 24 25 26 27 28
const tipStyleMap = {
  左下: {
    justifyContent: 'flex-start',
  },
  // 中下:{},
  右下: {
    justifyContent: 'flex-end',
  },
};
29
const IntegratedSwitch = props => {
30 31 32
  const integratedConfig = props.integratedConfig?.toObject
    ? props.integratedConfig.toObject()
    : props.integratedConfig || {};
33 34 35
  const timer = useRef(null);
  const timer3 = useRef(null);
  const progressRef = useRef(0);
36 37 38 39
  const history = useHistory();
  const [loginAction, setAction] = useState(() => new LoginAction(props));
  const [dataList, setDataList] = useState([]);
  const [client, setClient] = useState('');
40
  const clientRef = useRef(props.global.client);
41
  const clientInfo = useRef({}); // 跳转子站信息
42

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  const [jumpLoading, setJumpLoading] = useState(false);
  const [progressValue, setProgressValue] = useState(0);
  const jumpProgressEnd = () => {
    setProgressValue(100);
    timer.current && clearInterval(timer.current);
    timer.current = null;
  };
  const jumpProgressStart = () => {
    if (timer.current) {
      clearInterval(timer.current);
      timer.current = null;
    }
    progressRef.current = 0;
    setProgressValue(0);
    timer.current = setInterval(() => {
      if (progressRef.current < 97.5) {
        progressRef.current += 2.5;
        setProgressValue(progressRef.current);
      } else {
        setProgressValue(99);
        timer.current && clearInterval(timer.current);
        timer.current = null;
      }
    }, 100);
  };
  // 定时消除 loading
  const startTiming = (time = 2) => {
    if (timer3.current) {
      clearInterval(timer3.current);
      timer3.current = null;
    }
    timer3.current = setTimeout(() => {
      setJumpLoading(false);
      timer.current && clearInterval(timer.current);
      timer.current = null;
    }, time * 1000);
  };
  const handError = err => {
    if (err) {
      message.error(err);
    }

    setJumpLoading(false);
    jumpProgressEnd();
  };
88
  useEffect(() => {
89
    // if (!window?.globalConfig?.userInfo?.OID || (!(window?.globalConfig?.isIntegration > 1) && window?.globalConfig?.Industry !== '集成登录')) return setDataList([]);
90
    if (!window?.globalConfig?.userInfo?.OID || !(window?.globalConfig?.isIntegration >= 1)) return setDataList([]);
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    let list = localStorage.getItem('integrationData'); //
    list = list ? JSON.parse(list) : [];
    if (Array.isArray(list) && list?.length) {
      setDataList(list || []);
    } else {
      appService
        .GetIntegrationConfig({
          type: '集成登录',
          userId: window?.globalConfig?.userInfo?.OID ?? null,
          isEnable: true,
          client:
            localStorage.getItem('integrationClient') ||
            sessionStorage.getItem('client') ||
            props?.global?.client ||
            '',
        })
        .then(res => {
108 109 110 111 112 113 114 115
          let arr = res?.data || [];
          arr = arr.map(item => {
            if (item.subType === '内链' && !item.client && item.url) {
              item.client = item.url?.indexOf('client=') >= 0 ? item.url.split('client=')[1] : '';
            }
            return item;
          });
          setDataList(arr);
116 117 118 119 120
        })
        .catch(err => {
          setDataList([]);
        });
    }
121 122 123 124 125
  }, []);

  // 子站跳转
  // eslint-disable-next-line no-shadow
  const handlePage = useCallback((item, loginAction) => {
126 127 128 129
    if (window.clientInfo) {
      window.clientInfo = null;
    }

130
    if (item.subType === '外链') {
131 132 133
      setJumpLoading(true);
      jumpProgressStart();
      startTiming(5);
134
      // 营收
135 136 137 138
      if (item.paramValue === 'ticket') {
        // 获取临时token
        appService.getTicketByToken({ token: window.globalConfig?.token }).then(res => {
          if (res.code === 0) {
139
            const url = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramValue}=${res.data}`;
李纪文's avatar
李纪文 committed
140 141 142 143 144
            if (item?.openOpt === '当前页打开') {
              history.push('/thirdParty', { linkUrl: url });
            } else {
              window.open(url, '_blank');
            }
145
          } else {
146 147
            setJumpLoading(false);
            jumpProgressEnd();
148 149 150 151 152 153 154 155
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        });
      } else {
156 157 158
        const url = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramName}=${
          window.globalConfig?.token
        }`;
李纪文's avatar
李纪文 committed
159 160 161 162 163
        if (item?.openOpt === '当前页打开') {
          history.push('/thirdParty', { linkUrl: url });
        } else {
          window.open(url, '_blank');
        }
164 165
      }
    } else if (item.subType === '内链') {
166
      const { pathname } = window.location;
167
      const cli = item.client;
168
      if (item.client === props.global.client && pathname.indexOf('/civbase/thirdParty') === -1) {
169
        if (item.url) {
周宏民's avatar
周宏民 committed
170
          goToPath(item.url);
171 172 173
          return;
        }
      }
174 175 176 177 178 179 180 181 182 183
      const token = props.global?.token || Cookies.get('token');
      getWebSiteConfig({
        identity: token,
        client: cli,
      }).then(res => {
        if (!res?.data?.[0]?.widgets?.length) {
          message.error({
            duration: 3,
            content: '您没有该板块权限,请联系管理员',
          });
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
          return;
        }
        setJumpLoading(true);
        jumpProgressStart();
        startTiming(5);
        if (window.qiankunIsCache) {
          store.set('event:dropCache');
        }

        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);
204

205 206
        setClient(cli);
        clientRef.current = cli;
207
        window.clientInfo = item;
208 209 210 211 212 213 214 215 216 217 218 219
        const config = props.global;
        config.uiwidgets = [];
        config.widgets = [];
        config.allWidgets = [];
        window.qiankunStarted = false;
        if (cli) {
          config.client = cli;
        }

        // props.instance && props.instance.updateConfig(config);
        loginAction && loginAction.getUserInfoAndConfig('', true, item.type);
      });
220
    } else {
221 222 223
      setJumpLoading(true);
      jumpProgressStart();
      startTiming(5);
224 225 226 227 228 229 230 231 232 233
      let { url } = item;
      if (url?.indexOf('{userId}') >= 0) {
        url = url.replace('{userId}', window.globalConfig?.userInfo?.OID);
      }
      axios({
        url,
        method: 'get',
        dataType: 'json',
      }).then(res => {
        if (res?.data?.code === 0) {
李纪文's avatar
李纪文 committed
234 235 236 237 238
          if (item?.openOpt === '当前页打开') {
            history.push('/thirdParty', { linkUrl: res.data?.data });
          } else {
            window.open(res.data?.data, '_blank');
          }
239 240 241
        } else {
          setJumpLoading(false);
          jumpProgressEnd();
242 243 244 245 246 247 248
        }
      });
    }
  });

  useEffect(() => {
    const handleToggleIndustry = event => {
249 250
      setJumpLoading(false);
      jumpProgressEnd();
251 252 253 254 255 256 257 258 259 260
      let url = '';
      const { pathname } = window.location;
      if (window.clientInfo?.url && window.clientInfo.subType === '内链') {
        if (pathname.indexOf('/civbase/thirdParty') === -1) {
          // 上一个也是站内跳转,则可直接用 BasicLayout 里的跳转
          return;
        }
        // 上个子站不是站外链接,可直接用跳转
        url = searchUrl(window.clientInfo.url);
      }
261
      history.push(`/?client=${clientRef.current || props.global.client || ''}`);
262
      props.updateCurrentIndex(0);
263
      defaultApp(url);
264
    };
265 266 267 268
    const handleError = () => {
      setJumpLoading(false);
      jumpProgressEnd();
    };
269
    loginAction.events.on('toggleIndustry', handleToggleIndustry);
270
    loginAction.events.on('loginError', handleError);
271 272
    return () => {
      loginAction.events.removeListener('toggleIndustry', handleToggleIndustry);
273
      loginAction && loginAction.events && loginAction.events.removeListener('loginError', handleError);
274 275 276
    };
  }, [loginAction.events, props]);

277 278 279 280 281 282 283
  return dataList.length > 1 && integratedConfig?.isShowTip !== '不显示' ? (
    <div
      className={styles.switchPage}
      style={{
        ...tipStyleMap[(integratedConfig?.tipAlign)],
      }}
    >
284 285 286 287 288 289 290
      {jumpLoading ? (
        <div className={styles.integrationJumpLoad} key="jumpLoading">
          <div style={{ width: '285px' }}>
            <LoadPage percent={progressValue / 100} text="页面加载中~" />
          </div>
        </div>
      ) : null}
291
      <ul className={classNames(styles.switchPageCase, styles.switchPageSmall)}>
292 293 294
        <li
          className={styles.switchPageLi}
          onClick={() => {
295 296 297
            const integrationClient = localStorage.getItem('integrationClient');
            sessionStorage.setItem('client', integrationClient);
            localStorage.removeItem('integrationClient');
298 299 300
            history.push('/industry');
          }}
        >
301 302
          <div className={styles.switchPageList}>
            <Tooltip placement="top" title="主页">
303
              <img src={homeIcon} alt="" />
304 305 306
            </Tooltip>
          </div>
        </li>
307 308 309 310 311 312 313 314 315 316 317 318
        {dataList.map(item => (
          <li className={styles.switchPageLi} key={item.name} onClick={event => handlePage(item, loginAction)}>
            <div className={styles.switchPageList}>
              <Tooltip placement="top" title={item.name}>
                <img
                  src={`${window.location.origin}/${item.icon ? item.icon : 'center/images/科技风/二供.png'}`}
                  alt=""
                />
              </Tooltip>
            </div>
          </li>
        ))}
319
      </ul>
320 321
    </div>
  ) : null;
322 323 324 325 326 327
};

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  instance: state.getIn(['global', 'instance']),
  client: state.getIn(['global', 'client']),
328
  integratedConfig: state.getIn(['global', 'integratedConfig']),
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
});
const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  createContext(data) {
    dispatch(actionCreators.createContext(data));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(IntegratedSwitch);