"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _jsBase = require("js-base64");

var _jsCookie = _interopRequireDefault(require("js-cookie"));

var _sha = _interopRequireDefault(require("sha1"));

var _SlideVerify = _interopRequireDefault(require("../../../components/SlideVerify"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _readOnlyError(name) { throw new Error("\"" + name + "\" is read-only"); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var Login =
/*#__PURE__*/
function () {
  function Login(props) {
    _classCallCheck(this, Login);

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

  _createClass(Login, [{
    key: "init",
    value: function init() {
      var _this2 = this;

      this.loginFailed = false;
      this.guid = Math.round(Math.random() * 10000 + Date.now()).toString(16);
      this.redirect_state = _jsCookie["default"].get('redirect_state');

      var token = this.globalConfig.initToken || _jsCookie["default"].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(function (response) {
          if (response && !response.errMsg) {
            _this2.globalConfig.userInfo = {};

            if (response.Groups && response.Groups instanceof Array && response.Groups.length) {
              _this2.globalConfig.userInfo.Groups = response.Groups;
            }

            _this2.globalConfig.userInfo = Object.assign({}, response, _this2.globalConfig.userInfo);
            _this2.updateConfig && _this2.updateConfig(_this2.globalConfig);

            _this2.getUserInfoAndConfig();
          }
        });
      }
    }
  }, {
    key: "writeLogs",
    value: function 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"](function (error) {
          console.log(error);
        });
      }
    }
  }, {
    key: "getIndustry",
    value: function getIndustry(flag, token, _getIndustry) {
      var _this3 = this;

      this.globalConfig.userInfo.Industries = new Array();

      if (this.globalConfig.userInfo.Groups && this.globalConfig.userInfo.Groups.length) {
        this.globalConfig.userInfo.Groups.forEach(function (group) {
          if (group.industry && _this3.globalConfig.userInfo.Industries.indexOf(group.industry) < 0) _this3.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);
    }
  }, {
    key: "getWebConfig",
    value: function getWebConfig(token, getIndustry) {
      var _this4 = this;

      Http.getWebSiteConfig({
        client: this.globalConfig.client,
        token: token,
        'request.preventCache': Date.now()
      }).then(function (response) {

        if (response && response.length > 0) {
          _this4.globalConfig = Object.assign(_this4.globalConfig, response.shift(), {
            theme: _this4.globalConfig.theme,
            menu: _this4.globalConfig.menu,
            style: _this4.globalConfig.style
          });
          _this4.updateConfig && _this4.updateConfig(_this4.globalConfig);

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

            if (!!_this4.globalConfig.isShared) {
              _this4.globalConfig.mode = 'single';
              _this4.globalConfig.style = 'sandbox';
              _this4.globalConfig.uiwidgets = [_this4.globalConfig.shareWidget];
              _this4.globalConfig.widgets = [];
            } // this.events.removeAllListeners('loginSuccess')
            // this.events.removeAllListeners('toggleIndustry')
            // window.share.event = this.events;


            if (_this4.globalConfig.userInfo.site && _this4.globalConfig.userInfo.site.length > 0) {
              Http.getWebSiteConfig({
                client: _this4.globalConfig.client,
                token: token,
                'request.preventCache': Date.now()
              }).then(function (response) {

                if (response && response.length > 0) {
                  var mainConf = response.shift();
                  if (mainConf.homepage) _this4.globalConfig.homepage = mainConf.homepage;
                  if (mainConf.bannerLogo) _this4.globalConfig.bannerLogo = mainConf.bannerLogo;
                  if (mainConf.logo) _this4.globalConfig.logo = mainConf.logo;
                  if (mainConf.mdi) _this4.globalConfig.mdi = mainConf.mdi;
                  if (mainConf.menu) _this4.globalConfig.menu = mainConf.menu;
                  if (mainConf.shortcutIcon) _this4.globalConfig.shortcutIcon = mainConf.shortcutIcon;
                }

                _this4.updateConfig && _this4.updateConfig(_this4.globalConfig);
                getIndustry ? _this4.events.emit('toggleIndustry') : _this4.events.emit('loginSuccess');
                window.share.event = _this4.events;
              });
            } else {
              //loginSuccess
              _this4.updateConfig && _this4.updateConfig(_this4.globalConfig);
              getIndustry ? _this4.events.emit('toggleIndustry') : _this4.events.emit('loginSuccess');
              window.share.event = _this4.events;
            }
          });
        } else {
          if (_this4.goLogin()) {
            return false;
          }

          _this4.handleLoginError();

          console.log('获取网络配置失败');
        }
      })["catch"](function (error) {
        console.log(error);

        _this4.handleLoginError();

        console.log('获取网络配置失败');
      });
    }
  }, {
    key: "getProjectItems",
    value: function getProjectItems() {
      var MAX_BOTTOM = 0;
      var isScale = false;
      var widgetIndex = -1;
      this.globalConfig.uiwidgets.map(function (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;
      });
      var layers = this.globalConfig.mapsettings.layers;

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

      var 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({});
    }
  }, {
    key: "handleLoginError",
    value: function handleLoginError() {
      _jsCookie["default"].set(this.globalConfig.client, '', {
        path: '/'
      });

      _jsCookie["default"].set('token', '', {
        path: '/'
      });

      _jsCookie["default"].set('site', '', {
        path: '/'
      });

      _jsCookie["default"].set('loginMode', '', {
        path: '/'
      });

      _jsCookie["default"].set('redirect_state', '', {
        path: '/'
      });

      this.loginFailed = true;
    }
  }, {
    key: "goLogin",
    value: function goLogin() {

      if (this.globalConfig.style === 'ios' && this.globalConfig.loginTemplate === 'IOSCloud.html') {
        window.location.href = window.location.origin + '/#login';
        return true;
      } else {
        return false;
      }
    }
  }, {
    key: "isRememberPWD",
    value: function isRememberPWD(status) {
      this.isRememberPWD = status;
    }
  }, {
    key: "getLocalSiteBytoken",
    value: function getLocalSiteBytoken(tk) {
      var sStr = localStorage.getItem('loginSite'),
          s = null;

      if (sStr) {
        var sObj = JSON.parse(sStr);

        if (sObj && sObj[tk]) {
          s = sObj[tk];
        }
      }

      return s;
    }
  }, {
    key: "loginByDD",
    value: function loginByDD() {
      var 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);
      var obj = DDLogin({
        id: 'login_container',
        "goto": encodeURIComponent(gotoUrl),
        style: 'border:none;background-color:#FFFFFF;',
        width: '365',
        height: '400'
      });

      var handleMessage = function handleMessage(event) {
        var origin = event.origin;
        console.log('origin', event.origin);

        if (origin == 'https://login.dingtalk.com') {
          //判断是否来自ddLogin扫码事件。
          var loginTmpCode = event.data;
          var 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);
      }
    }
  }, {
    key: "ddLoginIn",
    value: function ddLoginIn(code) {
      var _this5 = this;

      Http.getOA({
        query: {
          TmpAuthCode: code
        },
        cacheBust: true
      }).then(function (response) {
        if (response && response.data && response.data.getMe) {
          var tk = response.data.getMe[0].token;
          _this5.globalConfig.token = tk;
          var url = window.location.href; //获取当前页面的url

          if (url.indexOf('&code') != -1) {
            //判断是否存在参数
            url = (_readOnlyError("url"), url.replace(/(\&code|#)[^'"]*/, '')); //去除参数

            window.history.pushState({}, 0, url);
          }

          _this5.isSignIn = true;

          _this5.getUserInfoAndConfig();
        } else {
          _this5.handleLoginError(); // msgUtils.fault("登录失败，请检查用户名或密码");
          // msgUtils.fault("登录失败，" + error.message);


          _this5.hasTry = true; //已经输错过密码
        }
      });
    }
  }, {
    key: "otherLoginIn",
    value: function otherLoginIn(usr, pwd) {
      var _this6 = this;

      var uesrName = (0, _jsBase.decode)(usr.substring(0, usr.length - 3)),
          password = (0, _jsBase.decode)(pwd.substring(0, pwd.length - 3));
      Http.generateToken({
        query: {
          f: 'json',
          expiration: this.globalConfig.expiration,
          //token过期时间(单位：秒)
          client: 'referer',
          username: uesrName,
          password: (0, _sha["default"])(password).toUpperCase(),
          referer: this.globalConfig.client,
          skipMenuTest: 1
        },
        cacheBust: true
      }).then(function (response) {
        if (response && response.data && response.data.token) {
          var tk = response.data.token; // token一天不过期

          _this6.globalConfig.token = tk;
          request(userInfoUrl, {
            query: {
              token: tk,
              subOID: 'subOID',
              site: _this6.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; //已经输错过密码
        }
      });
    }
  }, {
    key: "getUserInfoAndConfig",
    value: function getUserInfoAndConfig(failCallback, flag, industry) {
      var _this7 = this;

      var token = this.globalConfig.token;

      var site = _jsCookie["default"].get('site');

      var _industrySite = null;

      if (industry) {
        var userInfo = this.globalConfig.userInfo && this.globalConfig.userInfo.Groups && this.globalConfig.userInfo.Groups instanceof Array ? this.globalConfig.userInfo.Groups.find(function (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((0, _jsBase.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(function (response) {
          try {
            if (response && !response.errMsg) {
              _this7.globalConfig.userInfo = Object.assign({}, response, _this7.globalConfig.userInfo); // Cookies.set('site', this.globalConfig.userInfo.site);

              _this7.writeLogs();

              _this7.getIndustry(flag, token, industry);
            } else {
              if (_this7.goLogin()) {
                return false;
              }

              _this.handleLoginError(failCallback);
            }

            _this7.updateConfig && _this7.updateConfig(_this7.globalConfig);
          } catch (error) {
            if (_this7.goLogin()) {
              return false;
            }

            _this7.handleLoginError(failCallback);

            console.log(error);
          }
        })["catch"](function (error) {
          if (_this7.goLogin()) {
            return false;
          }

          _this7.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);
        }
      }
    }
  }, {
    key: "login",
    value: function login(usr, pwd, userPhone, isRememberPWD) {
      var _this8 = this;

      this.events.removeAllListeners('loginError');
      var self = this;
      Http.generateToken({
        f: 'json',
        expiration: this.globalConfig.expiration,
        //token过期时间(单位：秒)
        client: 'referer',
        username: usr,
        password: (0, _sha["default"])(pwd).toUpperCase(),
        referer: this.globalConfig.client,
        skipMenuTest: 1,
        userPhone: userPhone,
        'request.preventCache': Date.now()
      }).then(function (response) {
        if (response && response.token) {
          var token = response.token;

          _jsCookie["default"].set('token', token);

          var exp = 86400000;
          _this8.globalConfig.token = token;

          if (isRememberPWD) {
            _jsCookie["default"].set(_this8.globalConfig.client, token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/'
            });

            _jsCookie["default"].set('token', token, {
              expires: exp / (24 * 60 * 60 * 1000),
              path: '/'
            });
          }

          _this8.isSignIn = true;
          _this8.updateConfig && _this8.updateConfig(_this8.globalConfig);

          _this8.getUserInfoAndConfig();
        } else {
          self.hasTry = true;
          self.events.emit('loginError', response);
          console.log('登录失败', response.message);
        }
      })["catch"](function (error) {
        self.hasTry = true;
        self.handleLoginError();
        self.events.emit('loginError', error.message);
        console.log('登录失败', error.message);
      });
    }
  }, {
    key: "loginHandler",
    value: function loginHandler(user, pwd, userPhone, isRememberPWD, ref) {
      var _this9 = this;

      if (user && pwd) {
        if (this.loginFailed && this.captchaObj) {
          this.captchaObj.verify();
        } else {
          if (this.hasTry) {
            this.slideVerify(ref, function () {
              _this9.login(user, pwd, userPhone, isRememberPWD);
            });
          } else {
            this.login(user, pwd, userPhone, isRememberPWD);
          }
        }
      }
    }
  }, {
    key: "slideVerify",
    value: function slideVerify(ref, _onSuccess, onFail, onRefresh) {
      this.events.emit('loginVisible', true);
      var slideVerify = new _SlideVerify["default"]();
      slideVerify.render({
        container: ref.current,
        onSuccess: function onSuccess() {
          _onSuccess && _onSuccess();
        }
      });
    }
  }]);

  return Login;
}();

var _default = Login;
exports["default"] = _default;