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 { appService } from '../api';
import CitySelector from '../components/CitySelector';
import Login from '../pages/user/login/login';
import styles from './UserLayout.less';
import { initMicroApps } from '@/micro';


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() {
    const { loginName } = this.globalConfig.userInfo;
    const self = this;
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line no-undef
      appService
        .getAllGroupsInfoForUser({
          loginName,
          'request.preventCache': new Date().getTime(),
          ignoreSite: true,
        })
        .then(res => {
          if (res && res.say.errMsg === '' && res.say.statusCode === ERR_OK) {
            const result = res.getMe;
            let city = self.weatherCity;
            let arr = [];
            self.globalConfig.userInfo.groupType = '';
            self.globalConfig.userInfo.Groups = res.getMe;
            // 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,
                        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,
                      siteCityList: self.siteCityList,
                      citySelector: self.citySelector,
                      currentStationName: self.currentStationName,
                      weathers: {},
                    });
                  }
                })
                .catch(error => {
                  resolve({
                    stations,
                    currentStationName: self.currentStationName,
                    weathers: {},
                    siteCityList: self.siteCityList,
                    citySelector: self.citySelector,
                  });
                });
            } else {
              resolve({
                stations,
                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) {
    const date = new Date();
    date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
    // date = date.toGMTString();
    Cookies.set('token', token, {
      expires: date,
      path: '/',
    });

    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);
      // eslint-disable-next-line no-unused-expressions
      self.props.updateCurrentIndex && self.props.updateCurrentIndex(0);

      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,
      });

      // 重新加载订阅消息铃铛
      window.share && window.share.event && window.share.event.emit('reloadNotice');


      // window.history.replaceState(
      //   '',
      //   '',
      //   `/${self.globalConfig.homepage}`,
      // );
      self.getCityStationsForUser().then(res => {
        window.share.event.emit('updateSite', res);
      });
      self.props &&
        self.props.updateCollapsed &&
        self.props.updateCollapsed(false);

      self.props &&
        self.props.updateComplexConfig &&
        self.props.updateComplexConfig({});
      self.props.history && self.props.history.push(self.globalConfig.homepage ? `/${self.globalConfig.homepage}` : `/?client=${self.globalConfig.client}`);
      // window.location.reload();
      window.share.event.emit('triggerMicro', this.props.global);
    });
    login.init();
  }

  changeGroup(event, item) {
    event.persist();
    const site = item ? item.site : event.target.dataset.site;
    const { loginName } = this.globalConfig.userInfo;
    this.setLoading(true);
    // eslint-disable-next-line no-undef
    appService
      .generateTokenQuick({
        loginName,
        ignoreSite: true,
      })
      .then(res => {
        // eslint-disable-next-line no-debugger
        const { token } = res;
        if (token) {
          this.beforeChangeCheck(token, site);
        }
      })
      .catch(error => {
        this.setLoading(false);
        message.warning('切换企业失败');
      });
  }

  beforeChangeCheck(token, site) {
    // eslint-disable-next-line no-undef
    appService
      .getUserInfo({
        token,
        subOID: 'subOID',
        site,
        ignoreSite: true,
      })
      .then(res => {
        if (res && !res.errMsg) {
          this.writeCookie(token, site);
        } else {
          message.warning('企业切换失败，请联系管理员排查问题！');
          this.setLoading(false);
        }
      })
      .catch(e => {
        message.warning('企业切换失败，请联系管理员排查问题！');
        this.setLoading(false);
      });
  }

  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) {
      // eslint-disable-next-line no-undef
      appService
        .generateTokenQuick({
          loginName: self.globalConfig.userInfo.loginName,
          ignoreSite: true,
        })
        .then(res => {
          const { token } = res;
          if (token) {
            self.beforeChangeCheck(token, item.site);
          }
        })
        .catch(error => {
          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;
