index.js 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* eslint-disable indent */
/*
 * @Title: 集成登录通用模板
 * @Author: hongmye
 * @Date: 2024-10-30 18:34:42
 */
import { appService } from '@/api';
import { connect } from 'react-redux';
import { actionCreators } from '@/containers/App/store';
import axios from 'axios';
11
import { getImageUrl, searchUrl } from '@/utils/utils';
12
import { getUserInfo, getWebSiteConfig } from '@/api/service/base';
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { message, Button } from 'antd';
import classNames from 'classnames';
import { debounce } from 'lodash';
import React, { useRef, useEffect, useState, useMemo, useCallback } from 'react';
import backImg from '@/assets/images/demonstration/返回.png';
import arrowLeftImg from '@/assets/images/demonstration/左箭头.png';
import LoadPage from '@/components/LoadPage';
import $ from 'jquery';
import { useHistory, useAliveController } from '@wisdom-utils/runtime';

import { store } from '@wisdom-utils/utils';
import Cookies from 'js-cookie';
import LoginAction from '@/pages/user/login/login';

import { defaultApp } from '@/micro';
import useFullScreen from '../demonstration/components/useFullScreen';
import styles from './index.less';
const boxWidth = 1920;
const boxHeight = 930;

const IntegrationNew = props => {
36 37 38 39
  const integratedConfig = props.integratedConfig?.toObject
    ? props.integratedConfig.toObject()
    : props.integratedConfig || {};

40 41 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
  const [ref, isFullscreen, handleFullScreen, handleExitFullScreen] = useFullScreen(false);
  const history = useHistory();
  const integrationClient = integratedConfig?.client || window?.globalConfig?.client || 'city'; // 集成登录client
  const timer2 = useRef(null);
  const timer3 = useRef(null);
  const timer4 = useRef(null);
  const clientRef = useRef(props.global.client);
  const progressRef2 = useRef(0);
  const loadingTime = integratedConfig?.loadingTime || 5;
  const [loginAction, setAction] = useState(() => new LoginAction(props));
  const [mClient, setMClient] = useState('');
  const { clear } = useAliveController();
  // 退出
  const exit = () => {
    if (isFullscreen) {
      handleExitFullScreen && handleExitFullScreen();
    } else {
      handleFullScreen && handleFullScreen();
    }
  };
  const [boxSize, setBoxSize] = useState({
    scale: 1,
    boxHeight: 930,
  });
  const [integrationData, setIntegrationData] = useState([]); // 所有子站
  const [linkUrl, setLinkUrl] = useState('');
  // 解决 切换 client 时,updateConfig时,页会刷新,loading会重置
67 68
  const [jumpLoading, setJumpLoading] = useState(false);
  const [progressValue2, setProgressValue2] = useState(0);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  const [showBackBtn, setShowBackBtn] = useState(true); // 是否显示iframe 返回按钮,三维平台用

  const jumpProgressStart = () => {
    if (timer2.current) {
      clearInterval(timer2.current);
      timer2.current = null;
    }
    progressRef2.current = 0;
    setProgressValue2(0);
    timer2.current = setInterval(() => {
      if (progressRef2.current < 97.5) {
        progressRef2.current += 2.5;
        setProgressValue2(progressRef2.current);
      } else {
        setProgressValue2(99);
        timer2.current && clearInterval(timer2.current);
        timer2.current = null;
      }
    }, 100);
  };
  const jumpProgressEnd = () => {
    setProgressValue2(100);
    timer2.current && clearInterval(timer2.current);
    timer2.current = null;
  };
  const getData = async () => {
    const token = props.global?.token || Cookies.get('token');
    const client = integratedConfig?.client || sessionStorage.getItem('client') || props?.global?.client || '';
    localStorage.setItem('integrationClient', client);
    appService
      .GetIntegrationConfig({
        type: '集成登录',
        userId: window.globalConfig.userInfo?.OID ?? null,
        isEnable: true,
        client,
      })
      .then(res1 => {
周宏民's avatar
周宏民 committed
106 107
        let list = res1.data || [];
        list = list.sort((a, b) => a.index - b.index);
108
        list.length && localStorage.setItem('integrationData', JSON.stringify(list));
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        setIntegrationData(list);
      });
  };
  const onResize = () => {
    if (ref?.current) {
      const { clientWidth, clientHeight } = ref.current;
      if (!boxWidth || !boxHeight) return;
      const xScale = clientWidth / boxWidth;
      const yScale = clientHeight / boxHeight;
      const poor = clientHeight / clientWidth - boxHeight / boxWidth;
      let n = Math.min(xScale, yScale);
      let bHeight = boxHeight;
      if (poor > 0.05) {
        bHeight = boxHeight + 30;
      }
      // 高度为偶数
      bHeight = parseInt(bHeight, 10);
      if (bHeight % 2 !== 0) {
        bHeight += 1;
      }
      n = Number(n.toFixed(4));
      setBoxSize({
        scale: n,
        boxHeight: bHeight,
      });
    }
  };
  const handError = err => {
    if (err) {
      message.error(err);
    }
    setLinkUrl('');
    setJumpLoading(false);
    jumpProgressEnd();
  };

  const startTiming = (time = 2) => {
    if (timer3.current) {
      clearInterval(timer3.current);
      timer3.current = null;
    }
    timer3.current = setTimeout(() => {
      setJumpLoading(false);
      timer2.current && clearInterval(timer2.current);
      timer2.current = null;
    }, time * 1000);
  };
  const toRevenue = async item => {
    setJumpLoading(true);
    jumpProgressStart();
    startTiming(6);
    try {
      const res = await appService.getTicketByToken({ token: window.globalConfig?.token });
      if (res.code === 0) {
        // 营收是api-bcs,直饮水是api-ddw
        // /api-ddw/sysUser/ssoGCK
        const apiPath = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramValue}=${res.data}`;
        if (item?.openOpt === '当前页打开') {
          props.history.push('/thirdParty', { linkUrl: apiPath });
        } else {
169 170
          setJumpLoading(false);
          jumpProgressEnd();
171 172 173 174 175 176 177 178 179 180 181 182 183 184
          window.open(apiPath, '_blank');
        }
      } else {
        res.msg && message.error(res.msg);
        setJumpLoading(false);
        jumpProgressEnd();
      }
    } catch (error) {
      message.error('跳转错误,请联系管理员');
      setJumpLoading(false);
      jumpProgressEnd();
    }
  };

185 186
  const toClient = async (item, loginA) => {
    const token = props.global?.token || Cookies.get('token');
187
    const cli = item.client;
188 189 190 191 192 193 194 195 196 197 198
    const res = await getWebSiteConfig({
      identity: token,
      client: cli,
    });
    if (!res?.data?.[0]?.widgets?.length) {
      message.error({
        duration: 3,
        content: '您没有该板块权限,请联系管理员',
      });
      return;
    }
199 200
    // 用全局存跳转信息,跳转过程页面会刷新
    window.clientInfo = item;
201 202 203
    if (window.qiankunIsCache) {
      store.set('event:dropCache');
    }
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    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);

    setMClient(cli);
    clientRef.current = cli;
    const config = props.global;
    config.uiwidgets = [];
    config.widgets = [];
    config.allWidgets = [];
    window.qiankunStarted = false;
    if (cli) {
      config.client = cli;
    }
    setJumpLoading(true);
    jumpProgressStart();
    startTiming(loadingTime);
229
    // window.jumpLoadingProgress = 99;
230 231 232 233

    // if (loginA.globalConfig?.size === 0 && window.globalConfig) {
    //   loginA.updateConfig(window.globalConfig);
    // }
234
    loginA && loginA.getUserInfoAndConfig('', true);
235 236 237 238 239 240 241 242 243
  };
  const onLink = (item, loginA) => {
    const token = props.global?.token || Cookies.get('token');
    if (!token) {
      history.push(`/user/login?client=${integrationClient}`, { reload: true });
      clear();
      props.logout();
      return;
    }
244
    const { url, client } = item;
245 246 247
    if (window.clientInfo) {
      window.clientInfo = null;
    }
248
    if (item.subType === '内链' && client) {
249 250 251
      toClient(item, loginA);
    } else {
      if (!url) return;
252 253 254 255 256 257 258
      if (url?.indexOf('{userId}') >= 0) {
        item.url = url.replace('{userId}', window.globalConfig?.userInfo?.OID);
      }
      let link = item.url;
      if (item.paramName) {
        link = `${item.url + (item.url.indexOf('?') > 0 ? '&' : '?') + item.paramName}=${window.globalConfig?.token}`;
      }
259 260 261 262 263
      if (item.subType === '外链') {
        if (item.paramValue === 'ticket') {
          toRevenue(item); // 去营收
          return;
        }
264 265 266 267 268 269
        if (item?.openOpt === '当前页打开') {
          props.history.push('/thirdParty', { linkUrl: url });
        } else {
          window.open(url, '_blank');
        }
        return;
270
      }
271 272 273 274 275 276 277 278 279 280 281 282 283
      axios({
        url: link,
        method: 'get',
        dataType: 'json',
      }).then(res => {
        if (res?.data?.code === 0) {
          if (item?.openOpt === '当前页打开') {
            props.history.push('/thirdParty', { linkUrl: res.data?.data });
          } else {
            window.open(res.data?.data, '_blank');
          }
        }
      });
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
    }
  };

  const renderItem = item => (
    <div
      onClick={() => onLink(item, loginAction)}
      className={styles.IY_item}
      key={item.name}
      type={item.name}
      style={{
        zIndex: linkUrl ? 0 : 10,
        background: item.backgroundImage ? `url(${getImageUrl(item.backgroundImage)}) center/100% 100% no-repeat` : '',
      }}
    >
      <div className={styles.IY_item_name}>{item.name}</div>
      <div className={styles.IY_item_name_sub}>{item.subTitle || ''}</div>
    </div>
  );
  const renderList = useMemo(() => {
    const rowMap = {
      1: [1],
      2: [2],
      3: [3],
      4: [4],
      5: [3, 2],
      6: [3, 3],
      7: [4, 3],
      8: [4, 8],
      9: [5, 4],
      10: [5, 5],
    };
315
    const arr = rowMap[integrationData.length] || rowMap[10];
316 317
    const temp = [];
    integrationData.forEach((i, index) => {
318
      if (index >= 10) return;
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
      if (index < arr[0]) {
        if (!temp[0]) temp[0] = [];
        temp[0].push(i);
      } else {
        if (!temp[1]) temp[1] = [];
        temp[1].push(i);
      }
    });
    return temp.map(row => {
      if (row && row.length) {
        return <div className={styles.IY_row}>{row.map(item => renderItem(item))}</div>;
      }
      return null;
    });
  }, [integrationData]);
  useEffect(() => {
    getData();
    window.addEventListener('resize', debounce(onResize, 300));
    onResize();
    return () => {
      window.removeEventListener('resize', onResize);
      timer2.current && clearInterval(timer2.current);
      timer2.current = null;
      timer3.current && clearInterval(timer3.current);
      timer3.current = null;
    };
  }, []);
  useEffect(() => {
    if (!linkUrl) {
      if (timer4.current) {
        clearTimeout(timer4.current);
        timer4.current = null;
      }
      timer4.current = setTimeout(() => {
        if ($('.CarouselRipples')?.ripples) {
          $('.CarouselRipples').ripples({
            resolution: 800,
            dropRadius: 20, // px
            perturbance: 2,
          });
        }
      }, 1000);
    }

    return () => {
      if (timer4.current) {
        clearTimeout(timer4.current);
        timer4.current = null;
      }
    };
  }, [linkUrl]);
  useEffect(() => {
    const handleToggleIndustry = event => {
      setJumpLoading(false);
      jumpProgressEnd();
      window.jumpLoadingProgress = 0;
375
      let url = '';
376
      if (window.clientInfo?.url && window.clientInfo.subType === '内链') {
377
        url = searchUrl(window.clientInfo.url);
378
        window.clientInfo = null;
379
      }
380 381 382
      props.history.push(`/?client=${clientRef.current || props.global.client}`);
      props.updateCurrentIndex && props.updateCurrentIndex(0);
      defaultApp(url);
383 384 385 386 387
    };

    const handleError = () => {
      setJumpLoading(false);
      jumpProgressEnd();
388
      window.jumpLoadingProgress = 0;
389
    };
390
    loginAction.events.on('loginSuccess', handleToggleIndustry);
391 392 393
    loginAction.events.on('loginError', handleError);

    return () => {
394
      loginAction && loginAction.events && loginAction.events.removeListener('loginSuccess', handleToggleIndustry);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      loginAction && loginAction.events && loginAction.events.removeListener('loginError', handleError);
    };
  }, [loginAction.events, props]);
  return (
    <div className={classNames(styles.integrationNew, 'integrationNew')} ref={ref}>
      {jumpLoading ? (
        <div className={styles.integrationJumpLoad} key="jumpLoading">
          <div style={{ width: '285px' }}>
            <LoadPage percent={progressValue2 / 100} text="页面加载中~" />
          </div>
        </div>
      ) : null}
      {!linkUrl ? (
        <div className={styles.integrationNew_exit} onClick={exit}>
          <Button type="text" style={{ color: '#fff', fontSize: '24px' }}>
            {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </Button>
        </div>
      ) : null}

      <div
        className={styles.integration_content}
        style={{
          width: boxWidth,
          height: boxSize.boxHeight,
          transform: `scale(${boxSize.scale}) translate(-50%,-50%)`,
          zIndex: linkUrl ? 0 : 10,
        }}
      >
        <div className={styles.integrationNew_title}>
          <div className={styles.integrationNew_icon}>
            <img
              src={
                props.global &&
                props.global.transformDevAssetsBaseURL &&
                props.global.transformDevAssetsBaseURL(integratedConfig?.logo || props.global.logo)
              }
              alt="logo"
            />
          </div>
          <div className={styles.integrationNew_title_text}>
436 437 438
            <span title={integratedConfig?.title || props.global.title || '智慧水务综合监控平台'}>
              {integratedConfig?.title || props.global.title || '智慧水务综合监控平台'}
            </span>
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
          </div>
        </div>
        {integratedConfig?.subtitle ? (
          <div className={styles.integrationNew_title_sub}>{integratedConfig.subtitle}</div>
        ) : null}

        <div className={styles.IY_list}>{renderList}</div>
      </div>
      {!linkUrl ? (
        <div
          className={classNames(styles.iframeBack, 'animate__animated', 'animate__fadeIn')}
          onClick={() => props.logout()}
        >
          <div className={styles.iframeBackLeft}>
            <img src={arrowLeftImg} alt="返回" />
          </div>
          <div className={styles.iframeBackIcon}>
            <img src={backImg} alt="返回" />
            退出
          </div>
        </div>
      ) : null}
      {linkUrl && showBackBtn ? (
        <div
          className={classNames(styles.iframeExit, 'animate__animated', 'animate__fadeIn')}
          onClick={() => setLinkUrl('')}
        >
          <div className={styles.iframeExitLeft}>
            <img src={arrowLeftImg} alt="返回" />
          </div>
          <div className={styles.iframeExitIcon}>
            <img src={backImg} alt="返回" />
            返回
          </div>
        </div>
      ) : null}
      {!linkUrl ? <div className={classNames(styles.CarouselRipples, 'CarouselRipples')} data-ripple="ripple" /> : null}
    </div>
  );
};
const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
481
  integratedConfig: state.getIn(['global', 'integratedConfig']),
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
});
const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  createContext(data) {
    dispatch(actionCreators.createContext(data));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
  logout() {
    dispatch(actionCreators.logout());
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(IntegrationNew);