import { decode } from 'js-base64';
import Cookies from 'js-cookie';
import sha1 from 'sha1';

import SlideVerify from '../../../components/SlideVerify';

class Login {
  constructor(props) {
    this.events = window.share.event;
    this.globalConfig = props.global;
    this.updateConfig = props.updateConfig;
    this.createContext = props.createContext;
    this.history = props.history;
    this.hasTry = false
   // 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');
    if (!!token) {
      this.globalConfig.token = token;
      Http.getUserInfo({
        token: this.globalConfig.token,
        subOID: 'subOID',
        site: this.getLocalSiteBytoken(token),
        'request.preventCache': Date.now(),
      }).then(response => {
        if (response && !response.errMsg) {
          this.globalConfig.userInfo = {};
          if (
            response.Groups &&
            response.Groups instanceof Array &&
            response.Groups.length
          ) {
            this.globalConfig.userInfo.Groups = response.Groups;
          }
          this.globalConfig.userInfo = Object.assign(
            {},
            response,
            this.globalConfig.userInfo,
          );
          this.updateConfig && this.updateConfig(this.globalConfig);
          this.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) {
      Http.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 => {
        console.log(error);
      });
    }
  }

  getIndustry(flag, token, getIndustry) {
    this.globalConfig.userInfo.Industries = new Array();
    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.history.push('/industry');
      return false;
    }
    this.getWebConfig(token, getIndustry);
  }

  getWebConfig(token, getIndustry) {
    Http.getWebSiteConfig({
      client: this.globalConfig.client,
      token: token,
      'request.preventCache': Date.now(),
    })
      .then(response => {
        if (response && response.length > 0) {
          this.globalConfig = Object.assign(
            this.globalConfig,
            response.shift(),
            {
              theme: this.globalConfig.theme,
              menu: this.globalConfig.menu,
              style: this.globalConfig.style,
            },
          );

          this.updateConfig && this.updateConfig(this.globalConfig);

          this.getProjectItems().then(res => {
            window.subSysCfg = {};
            response.forEach(item => {
              window.subSysCfg[item.client] = item;
            });

            if (!!this.globalConfig.isShared) {
              this.globalConfig.mode = 'single';
              this.globalConfig.style = 'sandbox';
              this.globalConfig.uiwidgets = [this.globalConfig.shareWidget];
              this.globalConfig.widgets = [];
            }
            // this.events.removeAllListeners('loginSuccess')
            // this.events.removeAllListeners('toggleIndustry')
            // window.share.event = this.events;
            if (
              this.globalConfig.userInfo.site &&
              this.globalConfig.userInfo.site.length > 0
            ) {
              Http.getWebSiteConfig({
                client: this.globalConfig.client,
                token: token,
                'request.preventCache': Date.now(),
              }).then(response => {
                if (response && response.length > 0) {
                  var mainConf = response.shift();
                  if (mainConf.homepage)
                    this.globalConfig.homepage = mainConf.homepage;
                  if (mainConf.bannerLogo)
                    this.globalConfig.bannerLogo = mainConf.bannerLogo;
                  if (mainConf.logo) this.globalConfig.logo = mainConf.logo;
                  if (mainConf.mdi) this.globalConfig.mdi = mainConf.mdi;
                  if (mainConf.menu) this.globalConfig.menu = mainConf.menu;
                  if (mainConf.shortcutIcon)
                    this.globalConfig.shortcutIcon = mainConf.shortcutIcon;
                }
                this.updateConfig && this.updateConfig(this.globalConfig);
                
                getIndustry ? this.events.emit('toggleIndustry'):this.events.emit('loginSuccess');

                window.share.event = this.events;
              });
            } else {
              //loginSuccess
              this.updateConfig && this.updateConfig(this.globalConfig);
              getIndustry ? this.events.emit('toggleIndustry'):this.events.emit('loginSuccess');

              window.share.event = this.events;
            }
          });
        } else {
          if (this.goLogin()) {
            return false;
          }
          this.handleLoginError();
          console.log('获取网络配置失败');
        }
      })
      .catch(error => {
        console.log(error);
        this.handleLoginError();
        console.log('获取网络配置失败');
      });
  }

  getProjectItems() {
    let MAX_BOTTOM = 0;
    let isScale = false;
    let widgetIndex = -1;
    this.globalConfig.uiwidgets.map((item, index) => {
      if (parseInt(item['bottom']) > MAX_BOTTOM) {
        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.layers;
    if (layers.length === 0) {
      widgetIndex != -1 && this.globalConfig.uiwidgets.splice(widgetIndex, 1);
      return Promise.resolve({});
    }

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

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

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

  getLocalSiteBytoken(tk) {
    let sStr = localStorage.getItem('loginSite'),
      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);
    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.origin;
      console.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) {
    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;
        const url = window.location.href; //获取当前页面的url
        if (url.indexOf('&code') != -1) {
          //判断是否存在参数
          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; //已经输错过密码
      }
    });
  }

  otherLoginIn(usr, pwd) {
    const uesrName = decode(usr.substring(0, usr.length - 3)),
      password = decode(pwd.substring(0, pwd.length - 3));
    Http.generateToken({
      query: {
        f: 'json',
        expiration: this.globalConfig.expiration, //token过期时间(单位：秒)
        client: 'referer',
        username: uesrName,
        password: sha1(password).toUpperCase(),
        referer: this.globalConfig.client,
        skipMenuTest: 1,
      },
      cacheBust: true,
    }).then(response => {
      if (response && response.data && response.data.token) {
        const tk = response.data.token; // token一天不过期
        this.globalConfig.token = tk;
        request(userInfoUrl, {
          query: {
            token: tk,
            subOID: 'subOID',
            site: this.getLocalSiteBytoken(tk),
          },
          cacheBust: true,
          ignoreSite: true,
        }).then(function(response) {
          if (response && response.data && response.data.errMsg) {
            this.globalConfig.userInfo = {};
            if (
              response.data.Groups &&
              response.data.Groups instanceof Array &&
              response.data.Groups.length
            ) {
              this.globalConfig.userInfo.Groups = response.data.Groups;
            }
            this.getUserInfoAndConfig();
          }
        });
      } else {
        _this.handleLoginError();
        // msgUtils.fault("登录失败，请检查用户名或密码");
        msgUtils.fault('登录失败，' + error.message);

        _this.hasTry = true; //已经输错过密码
      }
    });
  }
  getUserInfoAndConfig(failCallback, flag, industry) {
    const token = this.globalConfig.token;
    const site = Cookies.get('site');
    let _industrySite = null;
    if (industry) {
      let userInfo =
        this.globalConfig.userInfo &&
        this.globalConfig.userInfo.Groups &&
        this.globalConfig.userInfo.Groups instanceof Array
          ? this.globalConfig.userInfo.Groups.find(enter => {
              return enter.industry === industry;
            })
          : null;

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

    this.updateConfig && this.updateConfig(this.globalConfig);

    if (this.isSignIn || !!industry) {
      Http.getUserInfo({
        token: token,
        subOID: 'subOID',
        industry: industry,
        site: _industrySite ? _industrySite : this.getLocalSiteBytoken(token),
        'request.preventCache': Date.now(),
      })
        .then(response => {
          try {
            if (response && !response.errMsg) {
              this.globalConfig.userInfo = Object.assign(
                {},
                response,
                this.globalConfig.userInfo,
              );
              // Cookies.set('site', this.globalConfig.userInfo.site);
              this.writeLogs();
              this.getIndustry(flag, token, industry);
            } else {
              if (this.goLogin()) {
                return false;
              }
              _this.handleLoginError(failCallback);
            }
            this.updateConfig && this.updateConfig(this.globalConfig);
          } catch (error) {
            if (this.goLogin()) {
              return false;
            }
            this.handleLoginError(failCallback);
            console.log(error);
          }
        })
        .catch(error => {
          if (this.goLogin()) {
            return false;
          }
          this.handleLoginError(failCallback);
          console.log(error);
        });
    } else {
      try {
        this.writeLogs();
        this.getIndustry(flag, token);
      } catch (error) {
        if (this.goLogin()) {
          return false;
        }
        this.handleLoginError(failCallback);
        console.log(error);
      }
    }
  }

  login(usr, pwd, userPhone, isRememberPWD) {
    this.events.removeAllListeners('loginError')
    const self = this;
    Http.generateToken({
      f: 'json',
      expiration: this.globalConfig.expiration, //token过期时间(单位：秒)
      client: 'referer',
      username: usr,
      password: sha1(pwd).toUpperCase(),
      referer: this.globalConfig.client,
      skipMenuTest: 1,
      userPhone: userPhone,
      'request.preventCache': Date.now(),
    })
      .then(response => {
        if (response && response.token) {
          const token = response.token;
          Cookies.set('token', token);
          const exp = 86400000;
          this.globalConfig.token = token;
          if (isRememberPWD) {
            Cookies.set(this.globalConfig.client, token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/',
            });

            Cookies.set('token', token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/',
            });
          }
          this.isSignIn = true;
          this.updateConfig && this.updateConfig(this.globalConfig);
          this.getUserInfoAndConfig();
        } else {
          self.hasTry = true;
          self.events.emit('loginError',response)
          console.log('登录失败', response.message);
        }
      })
      .catch(error => {
        self.hasTry = true;
        self.handleLoginError();
        self.events.emit('loginError',error.message)
        console.log('登录失败', error.message);
        
      });
  }

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

  slideVerify(ref, onSuccess, onFail, onRefresh) {
    this.events.emit('loginVisible', true)
    const slideVerify = new SlideVerify()
    slideVerify.render({
      container: ref.current,
      onSuccess: () => {
        onSuccess && onSuccess()
      }
    })
  }
}

export default Login;
