/**
 * Created by baoyinghai on 3/7/17.
 */
/* eslint-disable */
/*******   login utils **************/
var PRE = 'sso'; // 网关上下文

/* eslint-disable */
function analyseResponse(e, success, fail) {                    //如果为ie浏览器则页面加载完成后立即执行
  /*跳转到指定登录成功页面，index.jsp
   var f = document.getElementById("login");
   f.submit(); */
  var tag = e.target.contentWindow.document.body.innerHTML; //e.target.contentWindow.document.getElementsByTagName('pre');
  if (tag) {
    try {
      var json = JSON.parse(tag);
      if (json.msgContent || json.errMsg || json.message || json.code === 'version upgrade') {
        // error
        fail && fail(json.msgContent || json.errMsg || json.message);
        console.error(json.msgContent || json.errMsg || json.message);
      } else {
        if (json.isSuperAdmin) {
          // TODO: admin login
          window.location = 'http://sso.izirong.com/';
        } else {
          // save to local storage
          if (localStorage) {
            localStorage.userName=json.userName;
          }
          success && success(json);
        }
      }
    } catch(error) {
      fail && fail(error);
      console.error(error);
    }
  } else {
    fail && fail('操作失败');
  }
}

function createIframe(ele) {
  document.getElementsByTagName("head")[0].appendChild(ele);   //将iframe标签嵌入到head中
}

function removeIframe(ele) {
  document.getElementsByTagName("head")[0].removeChild(ele);   //将iframe移除
}

function getHref() {
  var url = location.href;
  return url.split('/',3).join('/');
}

function doSubmit(url, callback) {
  var scr = document.createElement("iframe");      //创建iframe
  scr.src = url;   //将报表验证用户名密码的地址指向此iframe
  var onLoad = function(e) {
    callback(e);
    removeIframe(scr);
  };
  if (scr.attachEvent){
    scr.attachEvent("onload", onLoad);
  } else {
    scr.onload = onLoad;
  }
  createIframe(scr);
}

/*********************/

window.__logoutHandler = function(successHandler, failHandler) {
  var url = getHref() + '/' + PRE + "/Api/TenantUser/logout";
  doSubmit(url, function(e) {
    analyseResponse(e, function() {
      window.location = getHref();
      successHandler();
    }, failHandler);
  });
};

/* eslint-disable */
var initLogin = function () {
  function addClass(obj, cls){
    var obj_class = obj.className,
      blank = (obj_class != '') ? ' ' : '';
    var added = obj_class + blank + cls;
    obj.className = added;
  }

  /* eslint-disable */
  function removeClass(obj, cls){
    var obj_class = ' '+obj.className+' ';
    obj_class = obj_class.replace(/(\s+)/gi, ' ');
    var removed = obj_class.replace(' '+cls+' ', ' ');
    var removed = removed.replace(/(^\s+)|(\s+$)/g, '');
    obj.className = removed;
  }

  var rootDiv = document.getElementById('root');
  var loginFormDiv = document.getElementById('mxLogin');
  if (rootDiv) rootDiv.style.display = 'none';
  if (loginFormDiv) loginFormDiv.style.display = '';

  /* eslint-disable */
  function initStyle() {
    var username = document.getElementsByName('username')[0];
    var pwd = document.getElementsByName('password')[0];
    var inputs = [username, pwd];
    inputs.forEach(function(item) {
      item.onfocus = function(e) {
        addClass(e.currentTarget.parentNode, 'active');
      };
      item.onblur = function(e) {
        removeClass(e.currentTarget.parentNode, 'active');
      }
    });
  }

  /* eslint-disable */
  (function() {
    //init style
    initStyle();
    var sub = document.getElementsByClassName('loginBtn')[0];

    function keyDownCallback(e) {
      if (e.keyCode === 13) {
        sub.click();
        window.returnValue = false;
      }
    }

    // initAction
    function removeLoading() {
      console.log('加载结束, 可以移除loading!');
    }
    function startLoading() {
      console.log('开始loading!');
    }

    var errorHandle = (function() {
      var ele = document.getElementsByClassName('error')[0];
      return function(errDesc) {
        ele.innerHTML = errDesc;
        window.addEventListener('keydown', keyDownCallback);
      }
    })();


    if (!sub) return;
    sub.onclick = function(e) {
      window.removeEventListener('keydown', keyDownCallback);
      // TODO: check
      var username = document.getElementsByName('username')[0];
      if (!username.value) {
        errorHandle('用户名不能为空!');
        return ;
      }
      var pwd = document.getElementsByName('password')[0];
      if (!pwd.value) {
        errorHandle('密码不能为空!');
        return ;
      }
      // TODO: 加密
      // doSubmit(username.value, btoa(pwd.value));
      var subBtn = e.target;
      subBtn.text = '正在登录...';
      var url = getHref() + '/' + PRE + "/Pub/TenantUser/login?userName=" + username.value + "&password=" + pwd.value;
      doSubmit(url, function(e) {
        analyseResponse(e, function() {
          // success
          // window.__successHandler && window.__successHandler();
          // 如果__successHandler为空, 则调用场景不符合  需要自己定义成功后的路由跳转;

          function loginCallBack() {
            if (rootDiv) rootDiv.style.display = 'inline';
            if (loginFormDiv) loginFormDiv.style.display = 'none';
            delete window.__showLogin;
            subBtn.text = '登录';
          }

          if (window.__initApp) {
            new Promise((resolve, reject) => {
              if (window.__initPage) {
                resolve(window.__initPage().then(() => delete window.__initPage))
              } else {
                resolve();
              }
            }).then(() => {
              return window.__initApp().then(() => loginCallBack());
            }).catch((err) => {
              errorHandle(JSON.stringify(err));
            });
          } else {
            window.__loginCallBack = loginCallBack;
          }
        }, function(error) {
          console.error(error);
          errorHandle(error);
          subBtn.text = '登录';
        });
      });
    };
    window.addEventListener('keydown', keyDownCallback);
  })();
};

if (window.__showLogin) {
  if (location.pathname !== '/') {
    location.href = '/';
  } else {
    initLogin();
  }
} else {
  var rootDiv = document.getElementById('root');
  if (rootDiv) rootDiv.style.display = 'inline';
  var loginFormDiv = document.getElementById('mxLogin');
  if (loginFormDiv) loginFormDiv.style.display = 'none';
}
