Site.js 21 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 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 67 68 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 106 107 108 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 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 201 202 203 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 229 230 231 232 233 234 235 236 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 269 270 271 272 273 274 275 276 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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 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 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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 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 436 437 438 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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 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 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
/* eslint-disable no-undef */
import React from 'react';

import { Anchor, message } from 'antd';
import classNames from 'classnames';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';

import { cityJson } from '@wisdom-utils/utils';
import { CitySelector } from '@wisdom-utils/components';
import { appService } from '../api';
import Login from '../pages/user/login/login';
import styles from './BasicLayout.less';
// import { initMicroApps } from '../micro'
// import actions from '../actions';
const { Link } = Anchor;

const ERR_OK = '0000';
class Site {
  constructor(props, callback) {
    this.weatherCity = null;
    this.globalConfig = props.global;
    this.updateConfig = props.updateConfig;
    this.props = props;
    this.init();
    this.setLoading = callback;
  }

  init(config) {
    // this.initWeatherCity();
  }

  setGlobalConfig(config) {
    this.globalConfig = config;
  }

  initWeatherCity() {
    try {
      if (navigator.onLine && this.globalConfig && this.globalConfig.userInfo && this.globalConfig.userInfo.site) {
        // eslint-disable-next-line no-undef
        appService.getCity().then(res => {
          // eslint-disable-next-line no-restricted-globals
          if (res && !isNaN(res.cid)) {
            const cityResult = JSON.parse(cityJson);
            const city = cityResult[res.cid];
            this.weatherCity = city || null;
          }
        });
      }
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error(e);
    }
  }

  getCityStationsForUser(response) {
    const self = this;
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line no-undef
      if (response) {
        const result = response || [];
        let city = self.weatherCity;
        let arr = [];
        self.globalConfig.userInfo.groupType = '';
        self.globalConfig.userInfo.Groups = result;
        // eslint-disable-next-line no-array-constructor
        self.globalConfig.userInfo.Industries = new Array();
        if (self.globalConfig.userInfo.Groups && self.globalConfig.userInfo.Groups.length) {
          self.globalConfig.userInfo.Groups.forEach(group => {
            if (group.industry && self.globalConfig.userInfo.Industries.indexOf(group.industry) < 0)
              self.globalConfig.userInfo.Industries.push(group.industry);
          });
        }
        if (
          self.globalConfig.userInfo &&
          self.globalConfig.userInfo.site &&
          self.globalConfig.userInfo.Groups &&
          self.globalConfig.userInfo.Groups.length
        ) {
          // eslint-disable-next-line no-underscore-dangle
          const _indestryItem = self.globalConfig.userInfo.Groups.find(
            // eslint-disable-next-line eqeqeq
            item => item.site === self.globalConfig.userInfo.site,
          );
          if (_indestryItem && _indestryItem.industry) {
            self.globalConfig.Industry = _indestryItem.industry;
          }
        }

        let allStation = [];
        let projectStation = [];
        self.showStations = [];
        if (self.globalConfig.Industry) {
          allStation = result.filter(item => item.industry === self.globalConfig.Industry);
          self.showStations = allStation.filter(item => item.promoteIndex && item.promoteIndex > 0);
          projectStation = allStation.filter(item => !item.promoteIndex);
        } else {
          allStation = result;
        }

        if (allStation.length) {
          let allChoice = false;
          allStation.forEach(val => {
            if (val.promoteIndex === 0) {
              allChoice = true;
            }
          });
          if (!allChoice) {
            // me.$el.find('#changeCityWays').hide();
            // me.$el.find('.LMBcityBox').hide();
            // me.$el.find('div.cities').css('min-width', 'initial');
            // me.$el.find('.focusStations').addClass('LMBcolumnList');
          }
          if (allStation.length > 120) {
            // $(me.el).find("div.cities div.cityContent").css("height", '335px');
          }
          // eslint-disable-next-line no-underscore-dangle
          let _enterprise = null;
          if (self.globalConfig.userInfo.site && self.globalConfig.userInfo.site.length) {
            _enterprise = allStation.filter(
              enterprise =>
                // eslint-disable-next-line eqeqeq
                enterprise.site === self.globalConfig.userInfo.site,
            );
          }
          if (_enterprise && _enterprise.length) {
            if (_enterprise[0].groupName.indexOf('演示' >= 0)) {
              arr[0] = _enterprise[0].groupName;
            } else {
              arr = _enterprise[0].city.split('/');
            }
            const tmp = _enterprise[0].city.split('/')[1];
            city = tmp.substr(0, tmp.length - 1);
            self.globalConfig.userInfo.groupType = _enterprise[0].groupType;
          } else {
            arr = allStation[0].city.split('/');
            const tmp = arr[1];
            city = tmp.substr(0, tmp.length - 1);
            self.globalConfig.userInfo.groupType = allStation[0].groupType;
          }
        }
        if (allStation.length > 0) {
          self.currentStationName = arr[arr.length - 1];
          self.citySelector = self.AvailableofRegionName(projectStation);
          self.siteCityList = self.buildCitySelectTemple(projectStation);
        }
        // 只有演示环境出现友好提示
        if (allStation.length === self.showStations.length) {
          self.isOnlyDisplay = true;
        } else {
          self.citySelector = self.AvailableofRegionName(projectStation);
          self.siteCityList = self.buildCitySelectTemple(projectStation);
        }

        // eslint-disable-next-line no-unused-expressions
        self.updateConfig && self.updateConfig(self.globalConfig);

        const stations = self.insertYSStation();

        // if (city) {
        //   // eslint-disable-next-line no-undef
        //   appService
        //     .getWeather({
        //       city,
        //       'request.preventCache': new Date().getTime(),
        //       ignoreSite: true,
        //     })
        //     // eslint-disable-next-line no-shadow
        //     .then(res => {
        //       if (res.say.statusCode === ERR_OK) {
        //         const firtValue = res.getMe[0];
        //         if (firtValue.cityName) {
        //           const text = firtValue.forcastFirst.split(' ')[1];
        //           const imgPath = firtValue.presentPictureFirst.replace('gif', 'svg');
        //           resolve({
        //             stations,
        //             allStation,
        //             weathers: {
        //               icon: `https://panda-water.cn/web4/assets/images/weather2/${imgPath}`,
        //               text: `${text}      ${firtValue.temperatureFirst}`,
        //             },
        //             siteCityList: self.siteCityList,
        //             citySelector: self.citySelector,
        //             currentStationName: self.currentStationName,
        //           });
        //         }
        //       } else {
        //         resolve({
        //           stations,
        //           allStation,
        //           siteCityList: self.siteCityList,
        //           citySelector: self.citySelector,
        //           currentStationName: self.currentStationName,
        //           weathers: {},
        //         });
        //       }
        //     })
        //     .catch(error => {
        //       resolve({
        //         stations,
        //         allStation,
        //         currentStationName: self.currentStationName,
        //         weathers: {},
        //         siteCityList: self.siteCityList,
        //         citySelector: self.citySelector,
        //       });
        //     });
        // } else {
        resolve({
          stations,
          allStation,
          currentStationName: self.currentStationName,
          weathers: {},
          siteCityList: self.siteCityList,
          citySelector: self.citySelector,
        });
        // }
      }
    });
  }

  insertYSStation() {
    const hot = ['HOT', '县', '市', 'New'];
    this.showStations.sort((a, b) => a.promoteIndex - b.promoteIndex);
    return this.showStations.map((item, index) => {
      let marginRight = 20;
      const style = {};
      switch (item.promoteTip) {
        case hot[3]:
        case hot[0]:
          marginRight = 40;
          break;
        case hot[1]:
        case hot[2]:
          marginRight = 30;
          break;
        default:
          marginRight = 20;
          break;
      }
      style.marginRight = marginRight;
      // eslint-disable-next-line no-param-reassign
      item.style = style;
      if (item.promoteTip && hot.includes(item.promoteTip)) {
        // eslint-disable-next-line no-param-reassign
        item.promoteTip = item.promoteTip;
      } else if (index === this.showStations.length) {
        // eslint-disable-next-line no-param-reassign
        item.style.marginRight = '-20px';
      }
      return item;
    });
  }

  getNumberofRegion(data, index) {
    const arr = [];
    const pNames = [];
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < data.length; i++) {
      const pName = data[i].city.split('/')[index];
      if (pNames.indexOf(pName) < 0) {
        pNames.push(pName);
      }
    }

    pNames.forEach(item => {
      arr[arr.length] = {
        proviceName: item,
        num: 0,
      };
    });

    // eslint-disable-next-line no-plusplus
    for (let j = 0; j < data.length; j++) {
      const itemJ = data[j];
      // eslint-disable-next-line camelcase
      const itemJ_pName = itemJ.city.split('/')[index];
      // eslint-disable-next-line no-plusplus
      for (let k = 0; k < arr.length; k++) {
        const itemK = arr[k];
        // eslint-disable-next-line camelcase
        if (itemJ_pName === itemK.proviceName) {
          // eslint-disable-next-line no-plusplus
          arr[k].num++;
        }
      }
    }
    return arr;
  }

  writeCookie(token, site, onChangeVisible, actionRef, accessToken, item) {
    const date = new Date();
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
    // date = date.toGMTString();
    // Cookies.set('token', token, {
    //   expires: date,
    //   path: '/',
    // });

    localStorage.setItem('access_token', accessToken);

    const encodeSite = encode(encodeURIComponent(site));
    Cookies.set('site', encodeSite, {
      expires: date,
      path: '/',
    });

    const loginSite = this.getLocalSites();
    loginSite[token] = site;
    localStorage.setItem('loginSite', JSON.stringify(loginSite));
    const self = this;
    // self.props.updateCurrentIndex && self.props.updateCurrentIndex(-1);
    const login = new Login(this.props, () => {
      self.setLoading(false);
      self.getCityStationsForUser().then(res => {
        window.share.event.emit('updateSite', res);
      });
      // eslint-disable-next-line no-unused-expressions
      self.props.updateCurrentIndex && self.props.updateCurrentIndex(0);
      // debugger
      // initMicroApps();
      // 切换站点后,重置掉三级菜单

      const homeType = self.globalConfig.homeType || 'civweb4';
      const homePath = self.globalConfig.homepage
        ? self.globalConfig.homepage.startsWith(homeType)
          ? self.globalConfig.homepage
          : `/${homeType}/${self.globalConfig.homepage}`
        : `/${homeType}`;
      window.share &&
        window.share.event &&
        window.share.event.emit('event:favitor', {
          name: '首页',
          path: homePath,
          icon: null,
        });

      actionRef && actionRef.current && actionRef.current.reload();

      // 重新加载订阅消息铃铛
      window.share && window.share.event && window.share.event.emit('reloadNotice');
      const config = self.globalConfig;
      const url = !config.home
        ? config.homepage === '' || _.isNull(config.homepage)
          ? `/civweb4`
          : `/${config.homepage.replace(/^\//, '')}`
        : `/${config.homepage.replace(/^\//, '')}`;
      self.props.history && self.props.history.push(url);
      self.props && self.props.updateCollapsed && self.props.updateCollapsed(false);
      window.share.event.emit('triggerMicro', this.props.global);
      window.share.event.emit('changeSiteVisible', { currentStationName: item.groupName, visible: false });
    });
    login.init();
  }

  changeGroup(event, item, onChangeVisible, actionRef) {
    event.persist();
    const site = item ? item.site : event.target.dataset.site;
    const { token } = this.globalConfig.userInfo;
    this.setLoading(true);
    if (token) {
      this.beforeChangeCheck(token, site, onChangeVisible, actionRef, item);
    } else {
      this.setLoading(false);
      message.warning('切换企业失败');
    }
  }

  beforeChangeCheck(token, site, onChangeVisible, actionRef, item) {
    const userParam = {
      token,
      subOID: 'subOID',
      site,
      ignoreSite: true,
    };
    const gateWayParam = {
      _site: site,
    };
    Promise.all([appService.getUserInfo(userParam), appService.getWateWayConfig(gateWayParam)])
      .then(results => {
        const res = results[0];
        const gatewayRes = results[1];
        if (res.code !== 0) {
          this.setLoading(false);
          message.error('获取用户信息失败');
        }
        const config = window?.globalConfig;
        config.uiwidgets = [];
        config.widgets = [];
        config.allWidgets = [];
        config.userInfo = window?.globalConfig?.transformUserInfo?.(res.data) ?? res.data;
        // 重置网关配置
        // eslint-disable-next-line prettier/prettier, no-undef
        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: token || '',
              type: 'token',
            })
            .then(tokenRes => {
              const accessToken = tokenRes.data?.access_token ?? null;
              config.access_token = accessToken;
              localStorage.setItem('access_token', accessToken);
              this.writeCookie(token, site, onChangeVisible, actionRef, accessToken, item);
            })
            .catch(err => {
              this.setLoading(false);
              config.access_token = null;
              this.writeCookie(token, site, onChangeVisible, actionRef, null, item);
            });
        } else {
          config.access_token = null;
          localStorage.setItem('access_token', null);
          this.writeCookie(token, site, onChangeVisible, actionRef, null, item);
        }
      })
      .catch(err => {
        this.setLoading(false);
        message.warning('企业切换失败,请联系管理员排查问题!');
      });
  }

  pySegSort(data) {
    if (!String.prototype.localeCompare) return null;
    let letters;
    const segs = []; // 存放数据
    const py = []; // 存放首字母
    const res = {};
    // eslint-disable-next-line prefer-const
    letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('');
    const ref = {
      A: {
        pName: ['安徽省'],
        data: [],
      },
      B: {
        pName: ['北京市'],
        data: [],
      },
      C: {
        pName: ['重庆市'],
        data: [],
      },
      F: {
        pName: ['福建省'],
        data: [],
      },
      G: {
        pName: ['甘肃省', '广东省', '广西壮族自治区', '贵州省'],
        data: [],
      },
      H: {
        pName: ['海南省', '河北省', '河南省', '黑龙江省', '湖北省', '湖南省'],
        data: [],
      },
      J: {
        pName: ['吉林省', '江苏省', '江西省'],
        data: [],
      },
      L: {
        pName: ['辽宁省'],
        data: [],
      },
      N: {
        pName: ['内蒙古自治区', '宁夏回族自治区'],
        data: [],
      },
      Q: {
        pName: ['青海省'],
        data: [],
      },
      S: {
        pName: ['山东省', '山西省', '陕西省', '上海市', '四川省'],
        data: [],
      },
      T: {
        pName: ['天津市'],
        data: [],
      },
      X: {
        pName: ['新疆维吾尔自治区', '西藏藏族自治区'],
        data: [],
      },
      Y: {
        pName: ['云南省'],
        data: [],
      },
      Z: {
        pName: ['浙江省'],
        data: [],
      },
    };
    // eslint-disable-next-line array-callback-return
    data.map(item => {
      const { proviceName } = item;
      // eslint-disable-next-line no-restricted-syntax
      for (const key in ref) {
        if (ref[key].pName.includes(proviceName)) {
          ref[key].data.push(item);
          break;
        }
      }
    });
    // eslint-disable-next-line array-callback-return
    letters.map(item => {
      if (ref[item] && ref[item].data.length) {
        py.push(item);
        segs.push({
          letter: item,
          data: ref[item].data,
        });
      }
    });
    res.segs = segs;
    res.py = py;
    return res;
  }

  handEnd = (event, item) => {
    event.persist();
    const self = this;
    if (item) {
      const { token } = self.globalConfig.userInfo;
      this.setLoading(true);
      if (token) {
        this.beforeChangeCheck(token, item.site);
      } else {
        this.setLoading(false);
        message.warning('切换企业失败');
      }
    }
  };

  AvailableofRegionName(data) {
    const options = {
      proviceOption: this.getNumberofRegion(data, 0),
      cityOption: this.getNumberofRegion(data, 1),
      siteOption: data,
    };
    return <CitySelector simple Clickable={options} handEnd={(event, item) => this.handEnd(event, item)} />;
  }

  buildCitySelectTemple(data) {
    const arr = [];
    const pNames = [];
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < data.length; i++) {
      const pName = data[i].city.split('/')[0];
      if (pNames.indexOf(pName) < 0) {
        pNames.push(pName);
      }
    }

    pNames.forEach((item, index) => {
      arr[arr.length] = {
        proviceName: item,
        stations: [],
      };
    });

    // eslint-disable-next-line no-plusplus
    for (let j = 0; j < data.length; j++) {
      const itemJ = data[j];
      // eslint-disable-next-line camelcase
      const itemJ_pName = itemJ.city.split('/')[0];
      // eslint-disable-next-line no-plusplus
      for (let k = 0; k < arr.length; k++) {
        const itemK = arr[k];
        // eslint-disable-next-line camelcase
        if (itemJ_pName === itemK.proviceName) {
          arr[k].stations[itemK.stations.length] = {
            stationID: itemJ.groupID,
            site: itemJ.site,
            cityName: itemJ.city,
            groupName: itemJ.groupName,
            isDeployed: itemJ.isDeployed,
          };
        }
      }
    }

    const cities = this.pySegSort(arr);

    const letters = [];

    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < cities.py.length; i++) {
      letters.push(
        <li key={cities.py[i][0]}>
          <Link
            className={styles.cityLetter}
            href={`#${cities.py[i][0]}`}
            dataHref={cities.py[i][0]}
            title={cities.py[i][0]}
          />
        </li>,
      );
    }
    const children = [];
    // eslint-disable-next-line no-plusplus
    for (let j = 0; j < cities.segs.length; j++) {
      const item = cities.segs[j];

      children.push(
        <div key={j}>
          <a className={styles.letter} href={`${item.letter}`} title={item.letter} id={item.letter}>
            {item.letter}
          </a>
          {item.data.map((k, i) => {
            const city = k;
            let pName = '';
            if (city.proviceName.indexOf('黑龙江' || '内蒙古') < 0) {
              pName = city.proviceName.substr(0, 2);
            } else {
              pName = city.proviceName.substr(0, 3);
            }
            return (
              <div className={styles.Provice} key={i}>
                <span className={styles.proviceName}>{pName}</span>
                <ul className={styles.city_list}>
                  {/* eslint-disable-next-line no-shadow */}
                  {city.stations.map((item, index) => (
                    <li key={item.cityName + index}>
                      <a
                        className={classNames(styles.city_select, !item.isDeployed ? styles.noData : '')}
                        title={item.cityName}
                        onClick={event => this.changeGroup(event, item)}
                      >
                        {item.groupName}
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>,
      );
    }
    return {
      letters,
      content: children,
    };
  }

  getLocalSites() {
    const localSite = localStorage.getItem('loginSite');
    let value = {};
    if (localSite) {
      value = JSON.parse(localSite);
    }
    return value;
  }
}

export default Site;