index.js 18.7 KB
Newer Older
周宏民's avatar
周宏民 committed
1 2 3 4 5 6 7 8 9
/* eslint-disable indent */
/* eslint-disable no-undef */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable global-require */
/*
 * @Title:
 * @Author: hongmye
 * @Date: 2023-12-26 18:34:42
 */
10
import { DoubleLeftOutlined, FullscreenExitOutlined, FullscreenOutlined, RightOutlined } from '@ant-design/icons';
周宏民's avatar
周宏民 committed
11
import exitImg from '@/assets/images/demonstration/退出.png';
12
import { Button, Spin, message, Progress } from 'antd';
周宏民's avatar
周宏民 committed
13 14 15 16 17 18 19 20 21
import React, { useMemo, useState, useEffect, useRef } from 'react';
import { cloneDeep, debounce } from 'lodash';
import Cookies from 'js-cookie';
import { encode } from 'js-base64';
import { appService } from '@/api';
import { actionCreators } from '@/containers/App/store';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { defaultApp } from '@/micro';
22 23
import Iframe from '@/components/Container/Iframe';
import moment from 'moment';
24
import LoadPage from '@/components/LoadPage';
25
import LoginAction from './components/login';
周宏民's avatar
周宏民 committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
import useFullScreen from './components/useFullScreen';
import styles from './index.less';
import LeftItem from './components/Left';
import VideoItem from './components/VideoItem';
import RightItem from './components/Right';
import BottomItem from './components/Bottom';
import { platformData } from './components/configData';
const boxWidth = 1920;
const boxHeight = 911;
const projectType = ['供水', '排水', '能源', '水利'];
const Demonstration = props => {
  const onLineUrl = window.globalConfig?.mainserver || 'https://panda-water.cn/';
  const showFullScreen = true;
  const videoRef = useRef(null);
  const [loginAction, setAction] = useState(() => new LoginAction(props));
41 42 43
  const progressRef = useRef(0);
  const timer = useRef(null);
  const [progressValue, setProgressValue] = useState(0);
周宏民's avatar
周宏民 committed
44 45 46
  const progressRef2 = useRef(0);
  const timer2 = useRef(null);
  const [progressValue2, setProgressValue2] = useState(0);
周宏民's avatar
周宏民 committed
47
  const [loading, setLoading] = useState(true);
48
  const [projectConfig, setProjectConfig] = useState({}); // 项目案例是否可免密跳转
49
  const [showContent, setShowContent] = useState(false);
周宏民's avatar
周宏民 committed
50 51 52 53 54 55
  const [jumpLoading, setJumpLoading] = useState(false);
  const [selectKey, setSelectKey] = useState('供水产品');
  const [boxSize, setBoxSize] = useState({
    scale: 1,
    boxHeight: 911,
  });
56
  const [linkUrl, setLinkUrl] = useState('');
周宏民's avatar
周宏民 committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  const [projectData, setProjectData] = useState([]);
  const [configData, setConfigData] = useState([]);
  const [productData, setProductData] = useState([]);
  const [ref, isFullscreen, handleFullScreen, handleExitFullScreen] = useFullScreen(false);
  // 退出
  const exit = () => {
    if (isFullscreen) {
      handleExitFullScreen && handleExitFullScreen();
    } else {
      handleFullScreen && handleFullScreen();
    }
  };

  // 切换方案视频
  const onChangeScheme = (item, index) => {
    if (videoRef.current) {
      videoRef.current.onSlideToLoop(index);
    }
  };
周宏民's avatar
周宏民 committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  const jumpProgressStart = () => {
    if (timer2.current) {
      clearInterval(timer2.current);
      timer2.current = null;
    }
    progressRef2.current = 0;
    setProgressValue2(0);
    timer2.current = setInterval(() => {
      if (progressRef2.current < 95) {
        progressRef2.current += 5;
        setProgressValue2(progressRef2.current);
      } else {
        setProgressValue2(99);
        timer2.current && clearInterval(timer2.current);
        timer2.current = null;
      }
    }, 300);
  };
  const jumpProgressEnd = () => {
    setProgressValue2(100);
    timer2.current && clearInterval(timer2.current);
    timer2.current = null;
  };
周宏民's avatar
周宏民 committed
99 100
  const failCallback = err => {
    setJumpLoading(false);
周宏民's avatar
周宏民 committed
101
    jumpProgressEnd();
周宏民's avatar
周宏民 committed
102
  };
周宏民's avatar
周宏民 committed
103

周宏民's avatar
周宏民 committed
104 105 106 107 108 109 110 111 112
  // 方案跳转
  const handlePage = (event, type, row) => {
    const config = props.global;
    const industries = config.userInfo?.Industries || [];
    if (!industries.includes(type)) {
      message.error(`该用户未配置${row.title}`);
      return;
    }
    setJumpLoading(true);
周宏民's avatar
周宏民 committed
113
    jumpProgressStart();
周宏民's avatar
周宏民 committed
114 115 116 117 118 119 120 121 122
    config.uiwidgets = [];
    config.widgets = [];
    config.allWidgets = [];
    props.instance && props.instance.updateConfig(config);
    loginAction && loginAction.getUserInfoAndConfig(failCallback, true, type);
  };
  const updateConfig = (config, data) => {
    props.updateConfig && props.updateConfig(config);
    const newLoginAction = new LoginAction({ ...props, global: config });
123
    newLoginAction && newLoginAction.getUserInfoAndConfig(failCallback, true, data.industry, data.site);
周宏民's avatar
周宏民 committed
124 125 126 127 128 129
  };

  // 新产品跳转
  const handToProduct = data => {
    if (!data.site) return message.warning('该用户没有权限!');
    setJumpLoading(true);
周宏民's avatar
周宏民 committed
130
    jumpProgressStart();
周宏民's avatar
周宏民 committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    const userParam = {
      token: props.global.token,
      subOID: 'subOID',
      site: data.site,
      ignoreSite: true,
    };
    const gateWayParam = {
      _site: data.site,
    };
    Promise.all([appService.getUserInfo(userParam), appService.getWateWayConfig(gateWayParam)])
      .then(results => {
        const res = results[0];
        const gatewayRes = results[1];
        if (res.code !== 0) {
          setJumpLoading(false);
周宏民's avatar
周宏民 committed
146
          jumpProgressEnd();
周宏民's avatar
周宏民 committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
          message.error('获取用户信息失败');
        }
        // 重置一些环境配置
        const config = { ...props.global };
        config.uiwidgets = [];
        config.widgets = [];
        config.allWidgets = [];
        config.userInfo = window?.globalConfig?.transformUserInfo?.(res.data) ?? res.data;

        // 默认有个上次记住的登入企业,存在印象。这里把cookie和localStorage中的都重新设置一下
        const date = new Date();
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
        const encodeSite = encode(encodeURIComponent(data.site));
        localStorage.setItem('loginSite', JSON.stringify({ [config.token]: data.site }));
        Cookies.set('site', encodeSite, {
          expires: date,
          path: '/',
        });
        props.updateConfig && props.updateConfig(config);
        // 重置网关配置

        const hasGateWay =
          !gatewayRes || !gatewayRes.data
            ? false
            : _.isString(gatewayRes.data)
            ? JSON.parse(gatewayRes.data)
            : typeof gatewayRes.data === 'boolean'
            ? gatewayRes.data
            : false;
        config.hasGateWay = hasGateWay;
        config.apiGatewayDomain = `${window.location.origin}${hasGateWay ? '/PandaCore/GateWay' : ''}`;
        if (hasGateWay) {
          appService
            .authorizationToken({
              loginName: config.userInfo?.loginName || '',
              type: 'WorkNo',
            })
            .then(tokenRes => {
              if (res.code === 0) {
                config.access_token = tokenRes.data?.access_token ?? '';
                localStorage.setItem('access_token', config.access_token);
              }
              updateConfig(config, data);
            })
            .catch(err => {
              updateConfig(config, data);
            });
        } else {
          config.access_token = null;
          localStorage.setItem('access_token', config.access_token);
          updateConfig(config, data);
        }
      })
      .catch(err => {
周宏民's avatar
周宏民 committed
201 202
        setJumpLoading(false);
        jumpProgressEnd();
周宏民's avatar
周宏民 committed
203 204 205 206 207 208
        message.error('获取用户信息失败');
      });
  };

  const handToPage = url => {
    if (!url) return message.warning('该环境未配置,请联系管理员');
209
    if (!url.includes('https')) return;
210
    setLinkUrl(url);
周宏民's avatar
周宏民 committed
211 212 213 214
  };

  const handToPlatform = col => {
    if (col['数值'] && col['数值'].includes('http')) {
215
      return handToPage(col['数值']);
周宏民's avatar
周宏民 committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    }
    handToProduct(col);
  };

  const renderCenter = useMemo(() => {
    let list = [...platformData];
    list = list.map(l => {
      const item = configData.find(c => c['名称'] === l.title);
      return { ...l, ...item };
    });
    return list.map(col => {
      if (col.isCenter) {
        return (
          <div className={styles.center_title} style={{ flex: col.flex }} type={col.title}>
            <div>{col.title}</div>
          </div>
        );
      }
234
      const isJump = col.site || (col['数值'] && col['数值'].includes('https'));
周宏民's avatar
周宏民 committed
235
      return (
236
        <div
237
          onClick={() => isJump && handToPlatform(col)}
238 239 240 241 242 243 244 245 246
          className={styles.center_col}
          style={{ flex: col.flex }}
          type={col.title}
          isJump={isJump ? 'yes' : 'no'}
        >
          <img src={require(`@/assets/images/demonstration/${col.icon}`)} alt="" />
          {col.title}
          <RightOutlined />
        </div>
周宏民's avatar
周宏民 committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
      );
    });
  }, [configData]);
  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;
      }
      n = Number(n.toFixed(4));
      setBoxSize({
        scale: n,
        boxHeight: bHeight,
      });
    }
  };
269 270
  const getProjectConfig = () => {
    if (!props.global?.userInfo?.loginName) return;
271 272 273 274 275 276 277 278 279 280 281 282
    const params = {
      ignoreSite: true,
      accountName: '项目案例临时账号管理',
      isAll: true,
      queryWheres: [
        {
          field: '是否禁用',
          type: '不等于',
          value: '是',
        },
      ],
    };
283 284
    const oid = props.global.userInfo?.cloudStationOID || props.global.userInfo?.OID;
    if (oid) {
285 286 287
      params.queryWheres.push({
        field: '账号',
        type: '等于',
288
        value: oid.toString(),
289
      });
290 291
    } else {
      return;
292
    }
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    appService.getAccountPageList(params).then(res => {
      let data = res?.data?.list || [];
      data = data.map(d => {
        const obj = {
          ID: d.id,
        };
        if (Array.isArray(d.webRow)) {
          d.webRow.forEach(w => {
            obj[w.fieldName] = w.fieldValue;
          });
        }
        return obj;
      });
      const obj = {};
      data.forEach(d => {
        if (!d['项目平台名称']) return;
        if (!d['开始时间']) return false;
        if (!d['结束时间'] && moment().isAfter(d['开始时间'])) {
          const arr = d['项目平台名称'].split(',');
          arr.forEach(a => {
            obj[a] = true;
          });
316

317 318 319 320 321 322 323 324
          return;
        }
        if (moment().isBetween(d['开始时间'], d['结束时间'])) {
          const arr = d['项目平台名称'].split(',');
          arr.forEach(a => {
            obj[a] = true;
          });
        }
325
      });
326 327
      setProjectConfig(obj);
    });
328
  };
周宏民's avatar
周宏民 committed
329 330 331 332 333 334
  const getData = () => {
    setLoading(true);
    const req1 = appService.getAccountPageList({
      ignoreSite: true,
      accountName: '项目案例配置表',
      isAll: true,
335
      sortFields: '顺序',
336
      direction: 'asc',
周宏民's avatar
周宏民 committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
      queryWheres: [
        {
          field: '演示案例',
          type: '等于',
          value: '是',
        },
      ],
    });
    const req2 = appService.getAccountPageList({
      accountName: '首页配置台账',
      isAll: true,
      ignoreSite: true,
    });
    const req3 = appService.getAccountPageList({
      ignoreSite: true,
      accountName: '新产品配置',
      isAll: true,
354
      sortFields: '顺序',
周宏民's avatar
周宏民 committed
355 356 357 358 359 360 361 362 363 364 365
      direction: 'asc',
      queryWheres: [
        {
          field: '是否显示',
          type: '等于',
          value: '是',
        },
      ],
    });
    Promise.all([req1, req2, req3]).then(result => {
      const dataStr1 = result[0]?.data?.jsonData || '';
366 367
      const data1 = dataStr1 ? JSON.parse(dataStr1) : [];
      // data1 = data1.filter(d => projectType.includes(d['所属行业']));
周宏民's avatar
周宏民 committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      const dataStr2 = result[1]?.data?.jsonData || '';
      let data2 = dataStr2 ? JSON.parse(dataStr2) : [];
      const dataStr3 = result[2]?.data?.jsonData || '';
      let data3 = dataStr3 ? JSON.parse(dataStr3) : [];
      const groups = props.global?.userInfo?.Groups || [];

      data3 = data3.map(d => {
        const item = groups.find(g => g.site === d.site);
        if (item) {
          return { ...d, ...item };
        }
        delete d.site;
        return d;
      });
      data2 = data2.map(d => {
        const item = groups.find(g => g.site === d['数值']);
        if (item) {
          return { ...d, ...item };
        }
        return d;
      });
      setProjectData(data1);
      setConfigData(data2);
      setProductData(data3);

      setLoading(false);
    });
  };
396 397 398
  const onendLoading = () => {
    jumpProgressEnd();
  };
399
  const handError = err => {
400 401 402
    if (err) {
      message.error(err);
    }
403
    setJumpLoading(false);
周宏民's avatar
周宏民 committed
404
    jumpProgressEnd();
405
  };
406 407 408
  useEffect(() => {
    if (loading && !timer.current) {
      timer.current = setInterval(() => {
409 410
        if (progressRef.current < 95) {
          progressRef.current += 5;
411 412 413 414 415 416
          setProgressValue(progressRef.current);
        } else {
          setProgressValue(99);
          timer.current && clearInterval(timer.current);
          timer.current = null;
        }
417
      }, 50);
418 419 420 421 422 423 424 425 426 427
    }
    if (!loading) {
      setProgressValue(100);
      timer.current && clearInterval(timer.current);
      timer.current = null;
      setTimeout(() => {
        setShowContent(true);
      }, 0);
    }
  }, [loading]);
周宏民's avatar
周宏民 committed
428 429 430 431 432 433 434 435 436 437 438
  useEffect(() => {
    const handleToggleIndustry = event => {
      props.history && props.history.push(`/?client=${props.global.client}`);
      props.updateCurrentIndex(0);
      defaultApp();
    };
    window.share.event.on('toggleIndustry', handleToggleIndustry);
    return () => {
      window.share.event.removeListener('toggleIndustry', handleToggleIndustry);
    };
  }, [props]);
439 440
  useEffect(() => {
    window.share.event.on('loginError', handError);
441 442
    // 结束跳转loading
    window.share.event.on('onendLoading', onendLoading);
443 444
    return () => {
      window.share.event.removeListener('loginError', handError);
445
      window.share.event.removeListener('onendLoading', onendLoading);
446 447
    };
  }, [jumpLoading]);
周宏民's avatar
周宏民 committed
448 449
  useEffect(() => {
    getData();
450
    getProjectConfig();
周宏民's avatar
周宏民 committed
451 452 453 454
    window.addEventListener('resize', debounce(onResize, 300));
    onResize();
    return () => {
      window.removeEventListener('resize', onResize);
周宏民's avatar
周宏民 committed
455 456
      timer2.current && clearInterval(timer2.current);
      timer2.current = null;
周宏民's avatar
周宏民 committed
457 458 459 460 461 462
    };
  }, []);
  return (
    <div className={classNames(styles.demonstration)} ref={ref}>
      {jumpLoading ? (
        <div className={styles.demonstrationLoad}>
463 464 465
          <div style={{ width: '285px' }}>
            <LoadPage percent={progressValue2 / 100} text="加载中~" />
          </div>
周宏民's avatar
周宏民 committed
466 467
        </div>
      ) : null}
468

469 470
      {loading || progressValue !== 100 ? (
        <div className={styles.loadingWrap}>
471 472 473
          <div style={{ width: '285px' }}>
            <LoadPage percent={progressValue / 100} text="加载中~" />
          </div>
474 475
        </div>
      ) : null}
周宏民's avatar
周宏民 committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
      {showFullScreen ? (
        <div className={styles.CV_exit} onClick={exit}>
          <Button type="text" style={{ color: '#fff', fontSize: '24px' }}>
            {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </Button>
        </div>
      ) : null}
      <div
        className={styles.demonstrationWrap}
        style={{
          width: boxWidth,
          height: boxSize.boxHeight,
          transform: `scale(${boxSize.scale}) translate(-50%,-50%)`,
        }}
      >
        <div className={styles.top}>
          <div className={styles.top_l}>
            <div className={styles.top_l_btn} onClick={() => props.setPattern && props.setPattern(false)}>
              <img src={exitImg} alt="" /> 退出演示模式 <RightOutlined />
            </div>
          </div>
          <div className={styles.top_c}>
            <div className={styles.top_c_title}>熊猫智慧水务一体化解决方案</div>
          </div>
          <div className={styles.top_r}>
            <div className={styles.top_r_text}>- 引领中国智慧水务 -</div>
          </div>
        </div>
504 505

        {showContent ? (
周宏民's avatar
周宏民 committed
506 507 508 509 510 511 512 513 514 515 516 517
          <>
            <div className={classNames(styles.row, 'animate__fadeInDown', 'animate__animated', 'duration-500ms')}>
              <div className={styles.row_l}>
                <LeftItem
                  setSelectKey={setSelectKey}
                  selectKey={selectKey}
                  onChangeScheme={onChangeScheme}
                  handlePage={handlePage}
                  industries={props.global?.userInfo?.Industries || []}
                />
              </div>
              <div className={styles.row_c}>
518
                <VideoItem ref={videoRef} selectKey={selectKey} setSelectKey={setSelectKey} showContent={showContent} />
周宏民's avatar
周宏民 committed
519 520
              </div>
              <div className={styles.row_r}>
521 522 523 524 525 526
                <RightItem
                  listData={productData}
                  handlePage={handlePage}
                  handToPage={handToPage}
                  handToProduct={handToProduct}
                />
周宏民's avatar
周宏民 committed
527 528 529 530 531 532 533 534 535 536 537
              </div>
            </div>
            <div className={classNames(styles.center_wrap, 'animate__fadeIn', 'animate__animated', 'duration-500ms')}>
              <div className={styles.center_tip} />
              <div className={styles.center}>{renderCenter}</div>
            </div>
            <div className={classNames(styles.bottom, 'animate__fadeInUp', 'animate__animated', 'duration-500ms')}>
              <BottomItem
                listData={projectData}
                configData={configData}
                onLineUrl={onLineUrl}
538
                projectConfig={projectConfig}
周宏民's avatar
周宏民 committed
539 540 541 542 543 544 545 546
                handToPage={handToPage}
                handlePage={handlePage}
                industries={props.global?.userInfo?.Industries || []}
              />
            </div>
          </>
        ) : null}
      </div>
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

      {linkUrl ? (
        <>
          <div className={classNames(styles.iframeExit, 'animate__animated')} onClick={() => setLinkUrl('')}>
            <DoubleLeftOutlined />
            &nbsp;&nbsp; 返回
            <div className={styles.iframeExitIcon}>
              <DoubleLeftOutlined />
            </div>
          </div>
          <div className={classNames('animate__fadeIn', 'animate__animated', 'duration-500ms')}>
            <Iframe linkUrl={linkUrl} />
          </div>
        </>
      ) : null}
周宏民's avatar
周宏民 committed
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    </div>
  );
};

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  instance: state.getIn(['global', 'instance']),
});
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,
)(Demonstration);