import 'kit_logger';

import { message } from 'antd';
import { decode, encode } from 'js-base64';
import Cookies from 'js-cookie';
import sha1 from 'sha1';

import { appService } from '@/api';
import {
  SERVICE_APP_LOGIN_MODE,
  SERVICE_INTERFACE_SUCCESS_CODE,
  WX_REDIRECT_URI,
} from '@/constants';
import { SlideVerify } from '@wisdom-utils/components';

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

  init() {
    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;
    const { loginName } = this.globalConfig;
    const { password } = this.globalConfig;
    const loginMode = Cookies.get('loginMode') || null;
    if (loginMode && loginMode === 'iotWechat') ddCode = null;

    const self = this;
    // self.qrcodeLogin(self.globalConfig.qrcodeData.code);
    if (token) {
      self.getToweb(token);
      // eslint-disable-next-line no-empty
    } else if (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
    appService
      .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.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();
        }
      });
  }

  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 => {});
    }
  }

  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
    appService
      .getWebSiteConfig({
        client: self.globalConfig.client,
        token,
        'request.preventCache': Date.now(),
      })
      .then(response => {
        const result =
          response && response.code === SERVICE_INTERFACE_SUCCESS_CODE
            ? Array.isArray(response.data)
              ? response.data
              : []
            : response;
        if (result && result.length > 0) {
          self.globalConfig = Object.assign(self.globalConfig, result.shift(), {
            theme: self.globalConfig.theme,
            menu: self.globalConfig.menu,
            style: self.globalConfig.style,
          });

          self.updateConfig && self.updateConfig(self.globalConfig);

          self.getProjectItems().then(() => {
            window.subSysCfg = {};
            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.site &&
              self.globalConfig.userInfo.site.length > 0
            ) {
              // eslint-disable-next-line no-undef,no-underscore-dangle
              appService
                .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();
                    if (mainConf.homepage)
                      self.globalConfig.homepage = 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;
                  }
                  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('获取网络配置失败');
        }
      })
      .catch(error => {
        // Logger.log(error);
        this.handleLoginError();
        // Logger.log('获取网络配置失败');
      });
  }

  getProjectItems() {
    let MAX_BOTTOM = 0;
    let isScale = false;
    let widgetIndex = -1;
    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({});
    }

    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(this.globalConfig);
    return Promise.resolve({});
  }

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

  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
    Http.getOA({
      query: {
        TmpAuthCode: code,
      },
      cacheBust: true,
    }).then(response => {
      if (response && response.data && response.data.getMe) {
        const tk = response.data.getMe[0].token;
        this.globalConfig.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);
        }
        this.isSignIn = true;
        this.getUserInfoAndConfig();
      } else {
        this.handleLoginError();
        // msgUtils.fault("登录失败，请检查用户名或密码");
        // msgUtils.fault("登录失败，" + error.message);
        this.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 => {
        console.log('sceen wx', response);
        if (response.token) {
          self.globalConfig.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: uesrName,
        password: sha1(password).toUpperCase(),
        referer: this.globalConfig.client,
        skipMenuTest: 1,
      })
      .then(response => {
        if (response && response.token) {
          const tk = response.token;
          this.globalConfig.token = tk;
          // eslint-disable-next-line no-undef,no-debugger
          appService
            .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 => {
              if (response && response.errMsg) {
                this.globalConfig.userInfo = {};
                if (
                  response.data.Groups &&
                  response.data.Groups instanceof Array &&
                  response.data.Groups.length
                ) {
                  this.globalConfig.userInfo.Groups = response.data.Groups;
                }
                self.updateConfig && self.updateConfig(self.globalConfig);
                self.getUserInfoAndConfig();
              }
            });
        } else {
          self.handleLoginError();
          message.error('登录失败');
          this.hasTry = true;
        }
      })
      .catch(error => {
        self.handleLoginError();
        message.error('登录失败');
        this.hasTry = true;
      });
  }

  getUserInfoAndConfig(failCallback, flag, industry) {
    // const { token } = this.globalConfig;
    const token = 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
      appService.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,
              );
              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);
      }
      if (isRememberPWD) {
        Cookies.set(self.globalConfig.client, token, {
          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.events.removeAllListeners('loginError');
    const self = this;
    if(window.globalConfig && window.globalConfig.hasGateWay) {
      usr = userPhone ? userPhone: usr;
      appService.authorizationToken({
        loginName: usr,
        password: pwd ? sha1(pwd).toUpperCase(): '',
        type: mode
      }).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: 300,
            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 ? sha1(pwd).toUpperCase() : '',
          referer: this.globalConfig.client,
          skipMenuTest: 1,
          userPhone,
          'request.preventCache': Date.now(),
          ignoreSite: true,
        },
      )
        .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;
