import 'kit_logger';
import { params } from '@wisdom-utils/utils/lib/helpers';
import { message } from 'antd';
import { decode, encode } from 'js-base64';
import Cookies from 'js-cookie';
import sha1 from 'sha1';

import { SlideVerify } from '@wisdom-utils/components';
import { appService, noticeService } from '@/api';
import { getUserInfo, getWebSiteConfig } from '@/api/service/base';
import {
  SERVICE_APP_LOGIN_MODE,
  SERVICE_INTERFACE_SUCCESS_CODE,
  WX_REDIRECT_URI,
} from '@/constants';
import store from '@/stores';
import {
  DEFAULT_MQTT_PATH,
  DEFAULT_TCP_IP,
  DEFAULT_TCP_PORT,
  DEFAULT_PARSE_LEVEL,
} from '@wisdom-utils/components/lib/AppLayout/notifier/constants';

// eslint-disable-next-line no-undef
const Logger = logger('login');
const getGlobalConfig = () =>
  store.getState().toJS().global?.globalConfig ?? {};
class Login {
  constructor(props, callback, isInit) {
    this.events = window.share.event;
    this.globalConfig = props.global;
    // this.updateConfig = props.updateConfig;
    this.updateConfig = config => {
      props.updateConfig(config);
      this.globalConfig = getGlobalConfig();
    };
    this.createContext = props.createContext;
    this.history = props.history;
    this.callback = callback;
    this.hasTry = false;
    this.logout = props.logout;
    if (isInit) {
      this.init();
    }
    //
  }

  init() {
    const self = this;
    this.loginFailed = false;
    this.guid = Math.round(Math.random() * 10000 + Date.now()).toString(16);
    this.redirect_state = Cookies.get('redirect_state');
    const token = this.globalConfig.initToken || Cookies.get('token');
    let { ddCode } = this.globalConfig;
    let { loginName } = this.globalConfig;
    let { password } = this.globalConfig;
    loginName = params.getParams('loginName')
      ? params.getParams('loginName')
      : loginName;
    const redirect = params.getParams('redirect');
    const generateType = params.getParams('generateType');
    if (redirect) {
      this.globalConfig.homepage = redirect;
      // this.globalConfig.layout = 'blank';
    }
    if (generateType) {
      this.globalConfig.generateType = generateType;
    }

    self.updateConfig && self.updateConfig(self.globalConfig);
    password = params.getParams('password')
      ? params.getParams('password')
      : password;
    const loginMode = Cookies.get('loginMode') || null;
    if (loginMode && loginMode === 'iotWechat') ddCode = null;
    // self.qrcodeLogin(self.globalConfig.qrcodeData.code);
    if (token) {
      self.getToweb(token);
      // eslint-disable-next-line no-empty
    } else if (ddCode && loginMode === 'dingding') {
      self.ddLoginIn(ddCode);
    } else if (ddCode && loginMode === 'qywx') {
      // 云平台和信息化都有企业微信，得区分(接口定义里面做了判断)
      self.qywxLoginIn(ddCode);
    } else if (!!loginName && !!password) {
      self.otherLoginIn(loginName, password);
    } else if (
      self.globalConfig.qrcodeData &&
      (self.globalConfig.qrcodeData.state &&
        self.globalConfig.qrcodeData.state === this.redirect_state) &&
      self.globalConfig.qrcodeData.code !== ''
    ) {
      self.qrcodeLogin(self.globalConfig.qrcodeData.code);
    } else if (
      !!self.globalConfig.isSingleLogin &&
      !!self.globalConfig.singleLoginCode
    ) {
      //
    } else if (self.goLogin()) {
      return false;
    }
  }

  getToweb(token) {
    this.globalConfig.token = token;
    const self = this;
    // eslint-disable-next-line no-undef

    getUserInfo({
      token: this.globalConfig.token,
      subOID: 'subOID',
      site: this.getLocalSiteBytoken(token),
      'request.preventCache': Date.now(),
      ignoreSite: true,
    }).then(response => {
      if (response && !response.errMsg) {
        self.globalConfig.userInfo = {};
        
        if(response.hasOwnProperty('data')) {
          self.globalConfig.userInfo = {
            // ... self.globalConfig.userInfo,
            ...response.data
          }
        } else {
          if (
            response.Groups &&
            response.Groups instanceof Array &&
            response.Groups.length
          ) {
            self.globalConfig.userInfo.Groups = response.Groups;
          }
          self.globalConfig.userInfo = Object.assign(
            {},
            response,
            self.globalConfig.userInfo,
          );
        }
        
        self.updateConfig && self.updateConfig(self.globalConfig);
        self.getUserInfoAndConfig();
      } else {
        self.logout && self.logout();
        if (
          self.globalConfig.style === 'ios' &&
          self.globalConfig.loginTemplate === 'IOSCloud.html'
        ) {
          window.location.href = `${window.location.origin}`;
          return false;
        }
        window.location.reload();
      }
    });
  }

  writeLogs() {
    if (this.globalConfig.userInfo.UserImge === '') {
      // _config.userInfo.UserImge = __webpack_public_path__ + "assets/images/icon/熊猫新2.png";
      this.globalConfig.userInfo.UserImge =
        'https://panda-water.cn/web4/assets/images/icon/熊猫新2.png';
    }

    if (this.globalConfig.userInfo.site) {
      // eslint-disable-next-line no-undef
      appService
        .writeLogs({
          origin: window.location.origin,
          client: this.globalConfig.client,
          site:
            this.globalConfig.userInfo && this.globalConfig.userInfo.site
              ? this.globalConfig.userInfo.site
              : '',
          loginName:
            this.globalConfig.userInfo && this.globalConfig.userInfo.fullName
              ? this.globalConfig.userInfo.fullName
              : '',
        })
        .catch(error => {});
    }

    if (window.location.host === 'panda-water.com') {
      appService
        .loginLogs({
          origin: window.location.origin,
          client: this.globalConfig.client,
          site:
            this.globalConfig.userInfo && this.globalConfig.userInfo.site
              ? this.globalConfig.userInfo.site
              : '',
          loginName:
            this.globalConfig.userInfo && this.globalConfig.userInfo.fullName
              ? this.globalConfig.userInfo.fullName
              : '',
        })
        .catch(error => {});
    }
  }

  getIndustry(flag, token, getIndustry) {
    this.globalConfig.userInfo.Industries = [];
    if (
      this.globalConfig.userInfo.Groups &&
      this.globalConfig.userInfo.Groups.length
    ) {
      this.globalConfig.userInfo.Groups.forEach(group => {
        if (
          group.industry &&
          this.globalConfig.userInfo.Industries.indexOf(group.industry) < 0
        ) {
          this.globalConfig.userInfo.Industries.push(group.industry);
        }
      });
    }

    if (
      !flag &&
      this.isSignIn &&
      this.globalConfig.userInfo.Industries.length &&
      this.globalConfig.userInfo.Industries.length > 1
    ) {
      this.createContext(this);
      // console.log('云平台');
      this.updateConfig && this.updateConfig(this.globalConfig);
      this.history.push('/industry');
      return false;
    }
    this.getWebConfig(token, getIndustry);
  }

  getWebConfig(token, getIndustry) {
    const self = this;
    // eslint-disable-next-line no-undef

    // 获取网站配置的同时，预先获取到mqtt配置，注册进子应用
    Promise.all([
      noticeService.getMqttSiteCode({ 'request.preventCache': Date.now() }),
      getWebSiteConfig({
        client: self.globalConfig.client,
        token,
        'request.preventCache': Date.now(),
      }),
    ])
      .then(results => {
        const res = results[0] ?? {};
        if (res && res.say.statusCode === '0000') {
          const mqttConfig = {
            mqtt_mess: {},
            mqtt_path: DEFAULT_MQTT_PATH,
            nginxStart: false,
            mqtt_IsSSL: true,
          };
          if (Array.isArray(res.getMe) && res.getMe.length > 0) {
            if (res.getMe[0]) {
              const data = res.getMe[0];
              mqttConfig.mqtt_IsSSL = data.IsSSL ? data.IsSSL : false;
              mqttConfig.mqtt_mess.site_code =
                data.SiteCode || self.globalConfig.userInfo.site;
              mqttConfig.mqtt_mess.TcpIP = data.TcpIP;
              mqttConfig.mqtt_mess.TcpPort = data.TcpPort
                ? parseInt(data.TcpPort)
                : 8083;
              mqttConfig.mqtt_mess.MessageLevel = data.MessageLevel
                ? data.MessageLevel
                : DEFAULT_PARSE_LEVEL;

              if (data.NginxStart) {
                mqttConfig.NginxStart = data.NginxStart;
                mqttConfig.mqtt_mess.TcpIP = window.location.hostname;
                mqttConfig.mqtt_mess.TcpPort = parseInt(window.location.port);
                mqttConfig.mqtt_path = '/ws/';
              } else {
                mqttConfig.nginxStart = data.NginxStart;
              }
            } else {
              mqttConfig.mqtt_mess.TcpIP = DEFAULT_TCP_IP;
              mqttConfig.mqtt_mess.TcpPort = DEFAULT_TCP_PORT;
              mqttConfig.mqtt_IsSSL = `${mqttConfig.mqtt_mess.TcpIP}:${
                mqttConfig.mqtt_mess.TcpPort
              }`;
            }
            mqttConfig.mqtt_iotIP = `${mqttConfig.mqtt_mess.TcpIP}:${
              mqttConfig.mqtt_mess.TcpPort
            }`;

            self.globalConfig = Object.assign(self.globalConfig, {
              ...mqttConfig,
            });
          }
        } else {
          Logger.info('获取mqtt服务器参数失败');
        }
        return results;
      })
      .then(results => {
        const response = results[1] ?? {};
        const result =
          response && response.code === SERVICE_INTERFACE_SUCCESS_CODE
            ? Array.isArray(response.data)
              ? response.data
              : []
            : response;
        if (result && result.length > 0) {
          const config = result.shift();
          const homeType = config.productType || 'civweb4';
          // 产品类型和首页路径同时有才行
          const homepage = params.getParams('redirect')
            ? params.getParams('redirect')
            : homeType && config.homepage
            ? `${homeType}/${params.getParams('redirect') || config.homepage}`
            : '';
          
          self.globalConfig = Object.assign(self.globalConfig, config, {
            theme: self.globalConfig.theme,
            menu: self.globalConfig.menu,
            style: self.globalConfig.style,
            homepage: homepage || '',
            // mapsettings: config.mapsettings
          });

          // eslint-disable-next-line no-prototype-builtins
          if (self.globalConfig.hasOwnProperty('webConfig')) {
            self.globalConfig = Object.assign(self.globalConfig, {
              // ...self.globalConfig,
              ...self.globalConfig.webConfig.basicConfig,
              ...self.globalConfig.webConfig.optionalConfig,
            });
          }

          self.updateConfig && self.updateConfig(self.globalConfig);
          self.getProjectItems().then(res => {
            window.subSysCfg = {};
            self.globalConfig = Object.assign(self.globalConfig, {
              mapsettings: res,
            });
            result.forEach(item => {
              window.subSysCfg[item.client] = item;
            });

            if (self.globalConfig.isShared) {
              self.globalConfig.mode = 'single';
              self.globalConfig.style = 'sandbox';
              self.globalConfig.uiwidgets = [self.globalConfig.shareWidget];
              self.globalConfig.widgets = [];
            }
            // this.events.removeAllListeners('loginSuccess')
            // this.events.removeAllListeners('toggleIndustry')
            // window.share.event = this.events;
            if (
              self.globalConfig.userInfo &&
              self.globalConfig.userInfo.site &&
              self.globalConfig.userInfo.site.length > 0
            ) {
              // eslint-disable-next-line no-undef,no-underscore-dangle

              getWebSiteConfig(
                {
                  client: self.globalConfig.client,
                  token,
                  ignoreSite: true,
                  'request.preventCache': Date.now(),
                },
                // eslint-disable-next-line no-shadow
              )
                // eslint-disable-next-line no-shadow
                .then(response => {
                  const resultData =
                    response && response.code === SERVICE_INTERFACE_SUCCESS_CODE
                      ? Array.isArray(response.data)
                        ? response.data
                        : []
                      : response;
                  if (resultData && resultData.length > 0) {
                    const mainConf = resultData.shift();
                    const mainType = mainConf.productType || 'civweb4';
                    if (mainConf.homepage)
                      self.globalConfig.homepage = `${mainType}/${
                        mainConf.homepage
                      }`;
                    if (mainConf.bannerLogo)
                      self.globalConfig.bannerLogo = mainConf.bannerLogo;
                    if (mainConf.logo) self.globalConfig.logo = mainConf.logo;
                    if (mainConf.mdi) self.globalConfig.mdi = mainConf.mdi;
                    if (mainConf.menu) self.globalConfig.menu = mainConf.menu;
                    if (mainConf.shortcutIcon)
                      self.globalConfig.shortcutIcon = mainConf.shortcutIcon;
                    // if (mainConf.productType)
                    //   self.globalConfig.productType = mainConf.productType;
                  }
                  self.updateConfig && self.updateConfig(self.globalConfig);
                  // console.log("===loginSuccess===")
                  getIndustry
                    ? self.events.emit('toggleIndustry')
                    : self.events.emit('loginSuccess');
                  window.share.event = self.events;
                  self.callback && self.callback();
                });
            } else {
              // loginSuccess

              self.updateConfig && self.updateConfig(self.globalConfig);
              // console.log("===loginSuccess===")
              getIndustry
                ? self.events.emit('toggleIndustry')
                : self.events.emit('loginSuccess');
              window.share.event = self.events;
              self.callback && self.callback();
            }
          });
        } else {
          if (this.goLogin()) {
            return false;
          }
          this.handleLoginError();
          // Logger.log('获取网络配置失败');
          console.log('获取网络配置失败');
        }
      })
      .catch(error => {
        console.log(error);
        // Logger.log(error);
        this.handleLoginError();
        // Logger.log('获取网络配置失败');
      });
  }

  getProjectItems() {
    let MAX_BOTTOM = 0;
    let isScale = false;
    let widgetIndex = -1;
    this.globalConfig.uiwidgets &&
      this.globalConfig.uiwidgets.map((item, index) => {
        // eslint-disable-next-line radix
        if (parseInt(item.bottom) > MAX_BOTTOM) {
          // eslint-disable-next-line radix
          MAX_BOTTOM = parseInt(item.bottom);
        }
        if (!isScale && item.url.toLowerCase().indexOf('widgets/zoom') > -1)
          isScale = true;
        if (
          widgetIndex === -1 &&
          item.url.indexOf('ToggleProject/ToggleProject') > -1
        )
          widgetIndex = index;
      });

    const { layers = [] } = this.globalConfig.mapsettings || {};
    if (layers.length === 0) {
      widgetIndex !== -1 && this.globalConfig.uiwidgets.splice(widgetIndex, 1);
      return Promise.resolve(this.globalConfig.mapsettings);
    }

    const layer = layers[0];

    if (!layer.id) {
      layer.layerType = 'dynamic';
    } else {
      layer.layerType = 'PipenetLayer';
    }

    if (layers.length > 1 && widgetIndex === -1) {
      this.globalConfig.uiwidgets.push({
        bottom: isScale ? MAX_BOTTOM + 70 : MAX_BOTTOM + 35,
        config: '',
        label: '方案切换',
        right: 15,
        url: 'product/webgisPanda/ToggleProject/ToggleProject',
      });
    }
    if (layer.areaName) {
      this.globalConfig.mapsettings.areasettings.areaName = layer.areaName;
    }

    if (layer.backgroundColor) {
      this.globalConfig.mapsettings.areasettings.backgroundColor =
        layer.backgroundColor;
    }

    if (layer.boundColor) {
      this.globalConfig.mapsettings.areasettings.boundColor = layer.boundColor;
    }

    if (layer.boundWidth) {
      this.globalConfig.mapsettings.areasettings.boundWidth = layer.boundWidth;
    }

    // eslint-disable-next-line radix
    if (Number.isInteger(parseInt(layer.backgroundOpacity))) {
      this.globalConfig.mapsettings.areasettings.backgroundOpacity =
        layer.backgroundOpacity;
    }
    if (layer.extent)
      this.globalConfig.mapsettings.areasettings.extent = layer.extent;
    if (layer.basemaps && layer.basemaps.length > 0) {
      this.globalConfig.mapsettings.basemaps = layer.basemaps;
    }

    // this.updateConfig && this.updateConfig(Object.assign({}, this.globalConfig, {
    //   mapsettings: this.globalConfig.mapsettings
    // }));
    // console.log("mapsettings", this.globalConfig.mapsettings)
    return Promise.resolve(this.globalConfig.mapsettings);
  }

  handleLoginError(callback) {
    Cookies.set(this.globalConfig.client, '', {
      path: '/',
    });

    Cookies.set('token', '', {
      path: '/',
    });
    Cookies.set('site', '', {
      path: '/',
    });
    Cookies.set('loginMode', '', {
      path: '/',
    });
    Cookies.set('redirect_state', '', {
      path: '/',
    });
    this.loginFailed = true;
    callback && callback();
  }

  goLogin() {
    if (
      this.globalConfig.style === 'ios' &&
      this.globalConfig.loginTemplate === 'IOSCloud.html'
    ) {
      window.location.href = `${window.location.origin}/#login`;
      return true;
    }
    return false;
  }

  isRememberPWD(status) {
    this.isRememberPWD = status;
  }

  getLocalSiteBytoken(tk) {
    const sStr = localStorage.getItem('loginSite');
    let s = null;
    if (sStr) {
      const sObj = JSON.parse(sStr);
      if (sObj && sObj[tk]) {
        s = sObj[tk];
      }
    }
    return s;
  }

  // 企业微信登录
  loginByWx() {
    window.WwLogin({
      id: 'wxlogin_container',
      appid: 'wxec56ca668e7f9155',
      agentid: '1000083',
      redirect_uri: encodeURIComponent(window.location.href),
      href: 'https://mis.panda-water.cn/web4/styles/wx.css',
    });
  }

  qywxLoginIn(code) {
    // eslint-disable-next-line no-undef
    const self = this;
    appService
      .getInfo({
        code,
        cacheBust: true,
      })
      .then(response => {
        if (response && response.getMe && response.getMe.length) {
          const tk = response.getMe[0].Token;
          self.globalConfig.token = tk;
          Cookies.set('token', tk);
          let url = window.location.href; // 获取当前页面的url
          if (url.indexOf('&code') !== -1) {
            // 判断是否存在参数
            // eslint-disable-next-line no-useless-escape
            url = url.replace(/(\&code|#)[^'"]*/, ''); // 去除参数
            window.history.pushState({}, 0, url);
          }
          self.isSignIn = true;
          self.getUserInfoAndConfig();
        } else {
          self.handleLoginError();
          message.error("登录失败，用户信息错误");
          self.hasTry = true; // 已经输错过密码
        }
      });
  }

  loginByDD() {
    const gotoUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoakne99srqra6hldv2&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${encodeURIComponent(
      window.location.href,
    )}`;
    // eslint-disable-next-line no-undef
    const obj = DDLogin({
      id: 'login_container',
      goto: encodeURIComponent(gotoUrl),
      style: 'border:none;background-color:#FFFFFF;',
      width: '365',
      height: '400',
    });

    const handleMessage = function(event) {
      const { origin } = event;
      // Logger.log('origin', event.origin);
      if (origin === 'https://login.dingtalk.com') {
        // 判断是否来自ddLogin扫码事件。
        const loginTmpCode = event.data;
        const redirectUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoakne99srqra6hldv2&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${encodeURIComponent(
          window.location.href,
        )}&loginTmpCode=${loginTmpCode}`;
        // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
        window.location.href = redirectUrl;
      }
    };
    if (typeof window.addEventListener !== 'undefined') {
      window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent !== 'undefined') {
      window.attachEvent('onmessage', handleMessage);
    }
  }

  ddLoginIn(code) {
    // eslint-disable-next-line no-undef
    const self = this;
    appService
      .getOA({
        TmpAuthCode: code,
        cacheBust: true,
      })
      .then(response => {
        if (response && response.getMe && response.getMe.length) {
          const tk = response.getMe[0].token;
          self.globalConfig.token = tk;
          Cookies.set('token', tk);
          let url = window.location.href; // 获取当前页面的url
          if (url.indexOf('&code') !== -1) {
            // 判断是否存在参数
            // eslint-disable-next-line no-useless-escape
            url = url.replace(/(\&code|#)[^'"]*/, ''); // 去除参数
            window.history.pushState({}, 0, url);
          }
          self.isSignIn = true;
          self.getUserInfoAndConfig();
        } else {
          self.handleLoginError();
          // msgUtils.fault("登录失败，请检查用户名或密码");
          // msgUtils.fault("登录失败，" + error.message);
          self.hasTry = true; // 已经输错过密码
        }
      });
  }

  qrcodeLogin(code) {
    const self = this;
    // eslint-disable-next-line no-undef
    appService
      .generatetokenByqrcode({
        f: 'json',
        expiration: self.globalConfig.expiration || 43200000,
        referer: self.globalConfig.client,
        skipMenuTest: 1,
        qrcode: code,
        cacheBust: true,
      })
      .then(response => {
        if (response.token) {
          self.globalConfig.token = response.token;
          Cookies.set('token', response.token);
          self.updateConfig && self.updateConfig(this.globalConfig);
          self.isSignIn = true;
          self.getUserInfoAndConfig();
          // Logger.log('===getUserInfoAndConfig===');
        } else {
          message.error(`登录失败,${response.message}`);
          self.events.emit('loginError', response);
          setTimeout(() => {
            self.handleLoginError(() => {
              window.location.href = WX_REDIRECT_URI;
            });
          }, 600);
        }
      })
      .catch(error => {
        // eslint-disable-next-line no-undef
        message.error(`登录失败,${error.message}`);
        // eslint-disable-next-line no-undef
        self.events.emit('loginError', error);
        setTimeout(() => {
          self.handleLoginError(() => {
            window.location.href = WX_REDIRECT_URI;
          });
        }, 600);
      });
  }

  otherLoginIn(usr, pwd) {
    // const uesrName = decode(usr.substring(0, usr.length - 3));
    // const password = decode(pwd.substring(0, pwd.length - 3));
    const self = this;
    // eslint-disable-next-line no-undef
    appService
      .generateToken({
        f: 'json',
        expiration: this.globalConfig.expiration, // token过期时间(单位：秒)
        client: 'referer',
        username: usr,
        password: params.getParams('generateType')
          ? pwd
          : sha1(pwd).toUpperCase(),
        referer: this.globalConfig.client,
        skipMenuTest: 1,
        generateType: params.getParams('generateType') || '',
      })
      .then(response => {
        // self.globalConfig.layout = 'blank';
        if (response && response.token) {
          const tk = response.token;
          self.globalConfig.token = tk;
          // eslint-disable-next-line no-undef,no-debugger

          getUserInfo(
            {
              token: tk,
              subOID: 'subOID',
              site: this.getLocalSiteBytoken(tk),
              ignoreSite: true,
            },
            // eslint-disable-next-line no-shadow
          )
            // eslint-disable-next-line no-shadow
            .then(response => {
              try {
                if (response && !response.errMsg) {
                  self.globalConfig.userInfo = Object.assign({}, response);
                  if (response.hasOwnProperty('data')) {
                    self.globalConfig.userInfo = {
                      // ... self.globalConfig.userInfo,
                      ...response.data,
                    };
                  }
                  const date = new Date();
                  date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
                  // date = date.toGMTString();
                  const encodeSite = encode(encodeURIComponent(response.site));
                  Cookies.set('site', encodeSite, {
                    expires: date,
                    path: '/',
                  });
                  Cookies.set('token', tk, {
                    expires: date,
                    path: '/',
                  });

                  // self.globalConfig.Industry = industry;
                  self.isSignIn = true;
                  self.updateConfig && self.updateConfig(self.globalConfig);
                  const loginSite = {};
                  loginSite[tk] = response.site;
                  // Cookie.set()
                  localStorage.setItem('loginSite', JSON.stringify(loginSite));
                  self.writeLogs();
                  self.getIndustry(false, tk);
                } else {
                  message.error(response.errMsg);
                  if (self.goLogin()) {
                    return false;
                  }
                  // self.handleLoginError(failCallback);
                }
                self.updateConfig && self.updateConfig(self.globalConfig);
              } catch (error) {
                console.log(error);
                if (self.goLogin()) {
                  return false;
                }
                // self.handleLoginError(failCallback);
              }
            });
        } else {
          self.handleLoginError();
          message.error('登录失败');
          this.hasTry = true;
        }
      })
      .catch(error => {
        self.handleLoginError();
        message.error('登录失败');
        this.hasTry = true;
      });
  }

  getUserInfoAndConfig(failCallback, flag, industry) {
    const { token: tk } = this.globalConfig;
    const token = tk || Cookies.get('token');
    const site = Cookies.get('site');
    const self = this;
    /* eslint-disable */
    let _industrySite = null;
    if (industry) {

      const userInfo =
        self.globalConfig.userInfo &&
        self.globalConfig.userInfo.Groups &&
        self.globalConfig.userInfo.Groups instanceof Array
          ? self.globalConfig.userInfo.Groups.find(
              enter => enter.industry === industry,
            )
          : null;

      if (userInfo) {
        self.globalConfig.userInfo = {
          site: userInfo.site ? userInfo.site : null,
          Groups: self.globalConfig.userInfo.Groups,
        };
        _industrySite = userInfo.site ? userInfo.site : null;
        // self.globalConfig.Industry = industry
        self.updateConfig && self.updateConfig(self.globalConfig);
      }
    } else if (!!site && self.isSignIn) {
      self.globalConfig.userInfo = {
        site: decodeURIComponent(decode(site)),
        Groups:
          self.globalConfig.userInfo &&
          self.globalConfig.userInfo.Groups &&
          self.globalConfig.userInfo.Groups instanceof Array
            ? self.globalConfig.userInfo.Groups
            : null,
      };
      self.updateConfig && self.updateConfig(self.globalConfig);
    }

    if (self.isSignIn || !!industry) {
      // eslint-disable-next-line no-undef
      getUserInfo(
        {
          token,
          subOID: 'subOID',
          industry,
          site: _industrySite || this.getLocalSiteBytoken(token),
          ignoreSite: true,
          'request.preventCache': Date.now(),
          // self.globalConfig.userInfo.site ? self.globalConfig.userInfo.site: this.getLocalSiteBytoken(token),
          // industrySite ? _industrySite : this.getLocalSiteBytoken(token),
        },
      )
        .then(response => {
          try {
            if (response && !response.errMsg) {
              self.globalConfig.userInfo = Object.assign(
                {},
                response,
                // self.globalConfig.userInfo,
              );
              if(response.hasOwnProperty('data')) {
                self.globalConfig.userInfo = {
                  // ... self.globalConfig.userInfo,
                  ...response.data
                }
              }
              const date = new Date();
              date.setTime(date.getTime() + 24 * 60 * 60 * 1000);
              // date = date.toGMTString();
              const encodeSite = encode(encodeURIComponent(response.site));
              Cookies.set('site', encodeSite, {
                expires: date,
                path: '/',
              });
              self.globalConfig.Industry = industry;
              self.updateConfig && self.updateConfig(self.globalConfig);
              const loginSite = {};
              loginSite[token] = response.site;
              // Cookie.set()
              localStorage.setItem('loginSite', JSON.stringify(loginSite));
              self.writeLogs();
              self.getIndustry(flag, token, industry);
            } else {
              message.error(response.errMsg);
              if (self.goLogin()) {
                return false;
              }
              self.handleLoginError(failCallback);
            }
            self.updateConfig && self.updateConfig(self.globalConfig);
          } catch (error) {
            if (self.goLogin()) {
              return false;
            }
            self.handleLoginError(failCallback);
          }
        })
        .catch(error => {
          if (self.goLogin()) {
            return false;
          }
          self.handleLoginError(failCallback);
        });
    } else {
      try {
        self.writeLogs();
        self.getIndustry(flag, token);
      } catch (error) {
        if (self.goLogin()) {
          return false;
        }
        self.handleLoginError(failCallback);
      }
    }
  }

  transformLoginHander(response, isRememberPWD) {
    const self = this;
    const token = response && ( response.token ? response.token: ( response.access_token !== null && response.user_token !== null) ? response.user_token: '');
    if (token) {
      Cookies.set('token', token);
      const exp = 86400000;
      self.globalConfig.token = token;
      if(response.access_token!== "") {
        self.globalConfig.access_token = response.access_token;
        localStorage.setItem('access_token', response.access_token);
        Cookies.set('client', self.globalConfig.client, {
          expires: exp / (24 * 60 * 60 * 1000),
          path: '/',
        })
      }
      if (isRememberPWD) {
        Cookies.set('client', self.globalConfig.client, {
          expires: exp / (24 * 60 * 60 * 1000),
          path: '/',
        });

        Cookies.set('token', token, {
          expires: exp / (24 * 60 * 60 * 1000),
          path: '/',
        });
      }
      self.isSignIn = true;
      self.updateConfig && self.updateConfig(self.globalConfig);
      self.getUserInfoAndConfig();
    } else {
      self.hasTry = true;
      self.events.emit('loginError', response);
      message.error(response.error.message);
      self.callback && self.callback(false);
    }
  }

  login(usr, pwd, userPhone, isRememberPWD, mode = SERVICE_APP_LOGIN_MODE.password) {
    this.globalConfig = getGlobalConfig();
    const self = this;
    if(window.globalConfig && window.globalConfig.hasGateWay) {
      usr = userPhone ? userPhone: usr;
      appService.authorizationToken({
        loginName: usr,
        password: pwd ? (params.getParams('generateType') ? pwd : sha1(pwd).toUpperCase()) : '',
        type: mode,
        generateType: params.getParams('generateType') || ''
      }).then(res => {

        if(res.code === 0) {
          const data = res.data;
          self.updateConfig && self.updateConfig(Object.assign({}, self.globalConfig, {
            access_token: data.access_token,
            token: data.user_token,
          }));
          return data
        } else {
          message.error({
            duration: 3,
            content: `授权失败:${res.msg}`
         });
         self.events.emit('loginError', res.msg);
         return Promise.reject(res)
        }
      }).then((res) => {
        self.transformLoginHander(res, isRememberPWD)
      })
    } else {
      appService.generateToken(
        {
          f: 'json',
          expiration: this.globalConfig.expiration, // token过期时间(单位：秒)
          client: 'referer',
          username: usr,
          password: pwd ? (params.getParams('generateType') ? pwd : sha1(pwd).toUpperCase()) : '',
          referer: this.globalConfig.client,
          skipMenuTest: 1,
          userPhone,
          'request.preventCache': Date.now(),
          ignoreSite: true,
          loginName: usr,
          generateType: params.getParams('generateType') || ''
        },
      )
        .then(response => {
           self.transformLoginHander(response, isRememberPWD)
        })
        .catch(error => {

          self.hasTry = true;
          self.handleLoginError();
          self.events.emit('loginError', error.message);
          message.error('登录服务异常');
        });
    }


  }

  loginHandler(user, pwd, userPhone, isRememberPWD, ref) {
    const self = this;
    if (user && pwd) {
      if (self.loginFailed && self.captchaObj) {
        self.captchaObj.verify();
      } else if (self.hasTry) {
        self.slideVerify(ref, () => {
          self.login(user, pwd, userPhone, isRememberPWD);
        });
      } else {
        self.login(user, pwd, userPhone, isRememberPWD);
      }
    }
  }

  phoneLoginFormHandler(userPhone, captcha) {
    this.login('', '', userPhone, '', SERVICE_APP_LOGIN_MODE.phone);
  }

  slideVerify(ref, onSuccess, onFail, onRefresh) {
    this.events.emit('loginVisible', true);

    if (this.renderVerify) {
      this.renderVerify.destroy();
    }
    this.renderVerify = new SlideVerify();
    this.renderVerify.render({
      container: ref.current,
      onSuccess: () => {
        onSuccess && onSuccess();
      },
    });
  }

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

export default Login;
