/***************************************************************************************
 * 为JavaScript默认对象添加扩展方法
***************************************************************************************/

/**
 * 将日期格式化为字符串
 * @param  {[type]} style [description]
 * @return {[type]}       [description]
 */
Date.prototype.format = function(style) {
  var y = this.getFullYear();
  var M = "0" + (this.getMonth() + 1);
  M = M.substring(M.length - 2);
  var d = "0" + this.getDate();
  d = d.substring(d.length - 2);
  var h = "0" + this.getHours();
  h = h.substring(h.length - 2);
  var m = "0" + this.getMinutes();
  m = m.substring(m.length - 2);
  var s = "0" + this.getSeconds();
  s = s.substring(s.length - 2);
  return style.replace('yyyy', y).replace('yy', (y+'').substring(2)).replace('MM', M).replace('dd', d).replace('hh', h).replace('mm', m).replace('ss', s).replace('S', this.getMilliseconds());
};

/**
 * 为日期增加指定的值
 * @param  {[type]} style [description]
 * @return {[type]}       [description]
 */
Date.prototype.add = function(strInterval, Number) {
  var dtTmp = this;
  switch (strInterval) {
    case 's' :return new Date(Date.parse(dtTmp) + (1000 * Number));
    case 'n' :return new Date(Date.parse(dtTmp) + (60000 * Number));
    case 'h' :return new Date(Date.parse(dtTmp) + (3600000 * Number));
    case 'd' :return new Date(Date.parse(dtTmp) + (86400000 * Number));
    case 'w' :return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
    case 'q' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number*3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    case 'm' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    case 'y' :return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
  }
};

/**
 * 计算两个日期之间的间隔
 * @param  {[type]} endTime  [description]
 * @param  {[type]} diffType [description]
 * @return {[type]}          [description]
 */
Date.prototype.diff = function (endTime, diffType) {
  //将计算间隔类性字符转换为小写
  diffType = diffType.toLowerCase();
  var sTime = new Date(this); //开始时间
  var eTime = new Date(endTime); //结束时间
  //作为除数的数字
  var divNum = 1;
  switch (diffType) {
    case "second":
      divNum = 1000;
      break;
    case "minute":
      divNum = 1000 * 60;
      break;
    case "hour":
      divNum = 1000 * 3600;
      break;
    case "day":
      divNum = 1000 * 3600 * 24;
      break;
    default:
      break;
  }
  return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
};

/**
 * 日期对象转换为JSON值
 * @return {[type]} [description]
 */
Date.prototype.toJSON = function () {
  return this.format('yyyy-MM-dd hh:mm:ss');
};

/**
 * 判断字符串是否以指定的子字符串开头
 * @param  {[type]} prefix [description]
 * @return {[type]}        [description]
 */
String.prototype.startWith = String.prototype.startsWith = function (prefix) {
  return this.indexOf(prefix) === 0;
};

/**
 * 判断字符串是否以指定的子字符串结尾
 * @param  {[type]} suffix [description]
 * @return {[type]}        [description]
 */
String.prototype.endWith = String.prototype.endsWith = function (suffix) {
  return this.match(suffix + "$") == suffix;
};

//计算字符串长度(英文占1个字符，中文汉字占2个字符)
String.prototype.gblen = function() {
  var len = 0;
  for (var i=0; i<this.length; i++) {
    if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {
      len += 2;
    } else {
      len ++;
    }
  }
  return len;
};

/**
 * 全部替换
 * @param  {[type]} s1 [description]
 * @param  {[type]} s2 [description]
 * @return {[type]}    [description]
 */
String.prototype.replaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

/**
 * 删除字符串两端的空格
 * @return {[type]} [description]
 */
String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g,"");
};

/**
 * 将字符串转换为日期
 * @return {[type]} [description]
 */
String.prototype.toDate = function () {
  return new Date(this.replace(/-/g, '/'));
};

/**
 * 判断数组中是否存在指定的元素
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Array.prototype.contains = function (obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
        return true;
    }
  }
  return false;
};

/**
 * 删除数组中指定的元素
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Array.prototype.remove = Array.prototype.deleteMember = function (obj) {
  for(var i=0;i<this.length;i++) {
    if (this[i] === obj) {
        this.splice(i,1);
        return;
    }
  }
};

/**
 * 获得URL中的指定参数的值
 * @param  {[type]} argName [description]
 * @return {[type]}         [description]
 */
function getUrlArg(argName) {
  var url = window.location.href;
  var start = url.indexOf("?");
  if (start < 0) return null;
  var str = url.substr(start + 1);
  var strArr = str.split("&");
  for (var i = 0; i < strArr.length; i++) {
    let aname = strArr[i].substr(0, strArr[i].indexOf("="));
    if (aname == argName) return decodeURIComponent(strArr[i].substr(strArr[i].indexOf("=")+1));
  }
  return null;
};

/**
 * 获得样式中的像素值，将px字母删掉，转换为整数
 * @param  {[type]} value [description]
 * @return {[type]}       [description]
 */
getPixel = function (value) {
  return parseInt((new String(value)).replace("px", ""));
};

/**
 * 任讯服务对象
 */
function TaskMsgService() {
  this.onError = null;      //处理错误的回调函数
  this.autoShowErr = true;  //是否自动显示错误提示
  this.srcElement = null;   //请求服务的源节点
  this.path = null;         //服务的路径
  this.onResponse = null;   //服务器端返回响应信息之后执行的回调函数

  /**
   * 显示错误信息
   * @param  {[type]} msg [description]
   * @return {[type]}     [description]
   */
  this.showError = function(msg) {
    if(this.autoShowErr) alert(msg);
    if(this.onError) this.onError(msg);
  };

  /**
   * 请求
   * @param  {[type]} args       [description]
   * @param  {[type]} onResponse [description]
   * @return {[type]}            [description]
   */
  this.request = function(args, onResponse) {
    if (!this.path) {
      this.showError("请提供服务路径！");
      return;
    }

    if(window.event) this.srcElement = window.event.srcElement;
    if(onResponse) this.onResponse = onResponse;

    if(!args) args = {};
    this.args = args;
    if(top.taskMsgAuthObj && top.taskMsgAuthObj.haveLoad) {
      top.taskMsgAuthObj.setAuthData(this);
    } else {
      if(getUrlArg("_auth_data")) this.args._auth_data = getUrlArg("_auth_data");
      if(getUrlArg("_auth_org")) this.args._auth_org = getUrlArg("_auth_org");
      if(getUrlArg("_auth_ts")) this.args._auth_ts = getUrlArg("_auth_ts");
    }
    if(!args.sessionId) {
      let sessionId = getUrlArg("sessionId");
      if(!sessionId) sessionId = localStorage.getItem("TaskMsgSessionId");
      if(sessionId) args.sessionId = sessionId;
    }
    this.sendRequest();
  };

  /**
   * 获取请求对象
   * @return {[type]}         [description]
   */
  this.getHttpRequest = function() {
    var httpRequest;
    if (window.XMLHttpRequest) {
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      if (!httpRequest) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    if (!httpRequest) {
      alert("您的浏览器不支持Ajax，无法执行该操作！");
      return null;
    }
    return httpRequest;
  }

  /**
   * 发送请求
   * @return {[type]} [description]
   */
  this.sendRequest = function() {
    this.args.service = this.path;

    var httpRequest = this.getHttpRequest();
    try {
      var that = this;
      httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState == 4) {
          if (httpRequest.status == 200) {
            var response = JSON.parse(httpRequest.responseText);
            if (response.code === 0) {
              if (that.onResponse) {
                if(that.srcElement) that.args.srcElement = that.srcElement;
                if(typeof that.onResponse == "function") {
                  that.onResponse(that.args, response);
                } else {
                  if(that.onResponse.indexOf(".")<0 && that.onResponse.indexOf(" ")<0
                    && that.onResponse.indexOf("=")<0 && that.onResponse.indexOf("(")<0
                    && that.onResponse.indexOf(")")<0) {
                    eval(that.onResponse+"(that.args, response)");
                  } else {
                    eval(that.onResponse);
                  }
                }
              }
            } else {
              if(response.code == 501) {
                top.location = "/";
                return;
              }
              that.showError(response.message);
            }
          } else if (httpRequest.status == 404) {
            that.showError("请求的服务不存在！");
          } else {
            if(httpRequest.status!==0)
              that.showError("向服务器发送请求时发生意外错误！\r\n错误代码：" + httpRequest.status);
          }
        }
      };

      var serverPath = location.toString();
      serverPath = serverPath.substr(0, serverPath.indexOf("/", 8)+1);
      httpRequest.open("POST", serverPath+"Service", true);
      httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      httpRequest.send(JSON.stringify(this.args));
    } catch (e) {
      this.showError("向服务器发送请求时发生意外错误！\r\n错误描述：" + e.message);
    }
  };
}