var taskMsgGrids = {};

var touchInfo = {
  downY: 0,
  isDrag: false,
  isOk: false,
  type: 0
};

function TaskMsgGrid() {
  this.id = null;
  this.jQueryObj = null;
  this.dataPage = null;
  this.dataList = null;
  this.dataMember = null;
  this.templateRowHtml = null;
  this.allowPaging = false;
  this.getDataService = null;
  this.beforeBind = null;
  this.afterBind = null;
  this.beforeAddRow = null;
  this.afterAddRow = null;
  this.curPage = 1;
  this.pageSize = 20;
  this.disablePullUp = false;
  this.disablePullDown = false;
  this.onLoadData = null;
  this.onBindData = null;

  var thisGrid = this;

  this.init = function (obj) {
    this.jQueryObj = obj;
    this.dataList = [];
    if (this.jQueryObj.attr("allowPaging") == "true") this.allowPaging = true;
    if (this.jQueryObj.attr("beforeBind")) this.beforeBind = this.jQueryObj.attr("beforeBind");
    if (this.jQueryObj.attr("afterBind")) this.afterBind = this.jQueryObj.attr("afterBind");
    if (this.jQueryObj.attr("beforeAddRow")) this.beforeAddRow = this.jQueryObj.attr("beforeAddRow");
    if (this.jQueryObj.attr("afterAddRow")) this.afterAddRow = this.jQueryObj.attr("afterAddRow");
    if (this.jQueryObj.attr("pageSize")) this.pageSize = parseInt(this.jQueryObj.attr("pageSize"));
    if (this.jQueryObj.attr("disablePullUp")) this.disablePullUp = this.jQueryObj.attr("disablePullUp");
    if (this.jQueryObj.attr("disablePullDown")) this.disablePullDown = this.jQueryObj.attr("disablePullDown");
    if (this.jQueryObj.attr("onLoadData")) this.onLoadData = this.jQueryObj.attr("onLoadData");
    if (this.jQueryObj.attr("onBindData")) this.onBindData = this.jQueryObj.attr("onBindData");
    this.dataMember = this.jQueryObj.attr("dataMember");
    this.templateRowHtml = this.jQueryObj.find(".TaskMsgGridRow").get(0).outerHTML.replace("TaskMsgGridRow", "TaskMsgGridRowDiv");
    this.jQueryObj.find(".TaskMsgGridRow").remove();

    var strScroller = $("<div class=\"TaskMsgGridScroller\"></div>");
    var divpullDown = "<div class=\"pullDown\"></div>";
    var divData = "<div class=\"TaskMsgGridData\"></div>";
    var divbottomBar = $("<div class=\"bottomBar\">点击获取数据</div>").click(function () {
      thisGrid.loadData(thisGrid.curPage + 1);
    });
    var divpullUp = "<div class=\"pullUp\"><div id=\"loading\"><span></span><span></span><span></span><span></span><span></span></div></div>";
    strScroller.append(divpullDown);
    strScroller.append(divData);
    strScroller.append(divbottomBar);
    strScroller.append(divpullUp);
    if (this.jQueryObj.find("TaskMsgGridFooter").length > 0) {
      $(strScroller).insertBefore(this.jQueryObj.find("TaskMsgGridFooter"));
    } else {
      this.jQueryObj.append(strScroller);
    }
    if (this.allowPaging) {
      document.ontouchstart = function (event) {
        if (thisGrid.disablePullDown && thisGrid.disablePullUp) return;
        var e = event || window.event;
        var headerHeight = 0;
        if (thisGrid.jQueryObj.find(".TaskMsgGridHeader").length > 0)
          headerHeight = thisGrid.jQueryObj.find(".TaskMsgGridHeader").get(0).clientHeight;
        var footerHeight = 0;
        if (thisGrid.jQueryObj.find(".TaskMsgGridFooter").length > 0)
          footerHeight = thisGrid.jQueryObj.find(".TaskMsgGridFooter").get(0).clientHeight;
        if (thisGrid.jQueryObj.get(0).scrollTop == 0) {
          if (thisGrid.disablePullDown) return;
          touchInfo.type = 1;
          thisGrid.jQueryObj.find(".pullDown").html("");
        } else if (thisGrid.jQueryObj.get(0).scrollTop ==
          headerHeight + thisGrid.jQueryObj.find(".TaskMsgGridScroller").get(0).clientHeight +
          footerHeight - thisGrid.jQueryObj.get(0).clientHeight - 61) {
          if (thisGrid.disablePullUp) return;
          touchInfo.type = 2;
          thisGrid.jQueryObj.find(".pullUp").html("");
        } else {
          return;
        }
        touchInfo.downY = e.touches[0].clientY;
        touchInfo.isDrag = true;
      };

      document.ontouchmove = function (event) {
        if (touchInfo.isDrag) {
          var e = event || window.event;
          var h = e.touches[0].clientY - touchInfo.downY;
          if (touchInfo.type == 1) {
            if (h > 0) {
              if (h > 61) {
                h = 61;
                thisGrid.jQueryObj.find(".pullDown").html("正在加载数据...");
                touchInfo.isOk = true;
              } else {
                touchInfo.isOk = false;
              }
              thisGrid.jQueryObj.find(".pullDown").css("margin-top", "-" + (61 - h) + "px");
            } else {
              touchInfo.isOk = false;
            }
          } else if (touchInfo.type == 2) {
            if (h < 0) {
              var headerHeight = 0;
              if (thisGrid.jQueryObj.find(".TaskMsgGridHeader").length > 0)
                headerHeight = thisGrid.jQueryObj.find(".TaskMsgGridHeader").get(0).clientHeight;
              var footerHeight = 0;
              if (thisGrid.jQueryObj.find(".TaskMsgGridFooter").length > 0)
                footerHeight = thisGrid.jQueryObj.find(".TaskMsgGridFooter").get(0).clientHeight;
              if (h < -60) {
                h = -60;
                thisGrid.jQueryObj.find(".pullUp").css("line-height", "60px");
                thisGrid.jQueryObj.find(".pullUp").html("正在加载数据...");
                touchInfo.isOk = true;
              } else {
                touchInfo.isOk = false;
              }
              thisGrid.jQueryObj.find(".pullUp").css("height", (-h) + "px");
              thisGrid.jQueryObj.get(0).scrollTop =
                headerHeight + thisGrid.jQueryObj.find(".TaskMsgGridScroller").get(0).clientHeight +
                footerHeight - thisGrid.jQueryObj.get(0).clientHeight - 61;
            } else {
              touchInfo.isOk = false;
            }
          }
        }
      };

      document.ontouchend = function () {
        if (touchInfo.isDrag) {
          if (touchInfo.type == 1) {
            if (touchInfo.isOk) {
              thisGrid.loadData(1);
            } else {
              thisGrid.jQueryObj.find(".pullDown").html("");
              thisGrid.jQueryObj.find(".pullDown").css("margin-top", "-61px");
            }
          } else if (touchInfo.type == 2) {
            if (touchInfo.isOk) {
              thisGrid.loadData(thisGrid.curPage + 1);
            } else {
              thisGrid.jQueryObj.find(".pullUp").html("");
              thisGrid.jQueryObj.find(".pullUp").css("height", "0");
              thisGrid.jQueryObj.find(".pullUp").css("line-height", "0");
            }
          }
          touchInfo.downY = 0;
          touchInfo.isDrag = false;
          touchInfo.isOk = false;
          touchInfo.type = 0;
        }
      };
    }
    if (this.jQueryObj.attr("getDataService")) {
      this.getDataService = this.jQueryObj.attr("getDataService");
      this.loading();
      this.loadData(1);
    }
  };

  this.loadData = function (toPage) {
    //this.jQueryObj.find('.TaskMsgGridData').addClass('TaskMsgGridDataLoading');
    var t = toPage;
    if (!t || t < 1) t = 1;
    var service = new TaskMsgService(this.getDataService);
    var args = {};
    if (this.allowPaging) {
      if ("undefined" != typeof RDASServiceHandlerPath) {
        args[this.id + "-toPage"] = t;
        args[this.id + "-pageSize"] = this.pageSize;
        if (this.jQueryObj.attr("sortItem")) args[this.id + "-sortItem"] = this.jQueryObj.attr("sortItem");
        if (this.jQueryObj.attr("sortName")) args[this.id + "-sortName"] = this.jQueryObj.attr("sortName");
        if (this.jQueryObj.attr("sortOrder")) args[this.id + "-sortOrder"] = this.jQueryObj.attr("sortOrder");
      } else {
        args["toPage"] = t;
        args["pageSize"] = this.pageSize;
      }
    }

    service.request(args, function (req, res) {
      if (thisGrid.onLoadData) eval(thisGrid.onLoadData + "(req, res)");
      if (thisGrid.beforeBind) eval(thisGrid.beforeBind + "(res)");
      thisGrid.dataBind(res);
      if (thisGrid.onBindData) eval(thisGrid.onBindData + "(req, res)");
      if (thisGrid.afterBind) eval(thisGrid.afterBind + "(res)");
      //thisGrid.jQueryObj.find('.TaskMsgGridData').removeClass('TaskMsgGridDataLoading');
    });
  };

  this.loading = function () {
    thisGrid.jQueryObj.find(".TaskMsgGridData").empty();
    thisGrid.jQueryObj.find(".TaskMsgGridData").css("background-image", "URL('" + TaskMsgClientAPIDir + "images/nodata_z.png')");
  };

  this.empty = function () {
    thisGrid.jQueryObj.find(".TaskMsgGridData").empty();
    thisGrid.jQueryObj.find(".TaskMsgGridData").css("background-image", "URL('" + TaskMsgClientAPIDir + "images/nodata_m.png')");
  };

  this.dataBind = function (res) {
    var dataObj = res[thisGrid.dataMember];
    var rows = null;
    if (thisGrid.allowPaging) {
      if (thisGrid.jQueryObj.find(".pullDown").html() != "") {
        thisGrid.jQueryObj.find(".pullDown").html("");
        thisGrid.jQueryObj.find(".pullDown").css("margin-top", "-61px");
      }
      if (thisGrid.jQueryObj.find(".pullUp").html() != "") {
        thisGrid.jQueryObj.find(".pullUp").html("");
        thisGrid.jQueryObj.find(".pullUp").css("height", "0");
        thisGrid.jQueryObj.find(".pullUp").css("line-height", "0");
      }
      if ("undefined" != typeof RDASServiceHandlerPath) {
        thisGrid.dataPage = {};
        thisGrid.dataPage.rows = dataObj;
        thisGrid.dataPage.toPage = parseInt(res[this.id + "-toPage"]);
        thisGrid.dataPage.pageCount = parseInt(res[this.id + "-pageCount"]);
        thisGrid.dataPage.rowsCount = parseInt(res[this.id + "-rowCount"]);
        rows = dataObj;
      } else {
        thisGrid.dataPage = dataObj;
        if (!thisGrid.dataPage) {
          thisGrid.dataPage = {};
          thisGrid.dataPage.rows = [];
          thisGrid.dataPage.toPage = 1;
          thisGrid.dataPage.pageCount = 0;
          thisGrid.dataPage.rowsCount = 0;
        }
        rows = thisGrid.dataPage.rows;
      }

      //如果是最后一页，则不再翻页
      if (thisGrid.curPage > 1 && thisGrid.curPage == thisGrid.dataPage.toPage &&
        thisGrid.curPage == thisGrid.dataPage.pageCount) {
        return;
      }
    } else {
      rows = dataObj;
    }
    if (!rows) return;
    if (!thisGrid.allowPaging || (thisGrid.allowPaging && thisGrid.dataPage.toPage == 1)) {
      thisGrid.jQueryObj.find(".TaskMsgGridData").empty();
      thisGrid.jQueryObj.find(".TaskMsgGridData").css("background-image", "URL('" + TaskMsgClientAPIDir + "images/nodata_z.png')");
      thisGrid.dataList = [];
    }
    if (thisGrid.allowPaging) thisGrid.curPage = thisGrid.dataPage.toPage;
    if (rows instanceof Array) {
      for (var i = 0; i < rows.length; i++) {
        thisGrid.addRow(rows[i]);
        thisGrid.dataList.push(rows[i]);
      }
    } else {
      for (var objId in rows) {
        thisGrid.addRow(rows[objId]);
        thisGrid.dataList.push(rows[objId]);
      }
    }

    if (thisGrid.dataList.length === 0) {
      thisGrid.jQueryObj.find(".TaskMsgGridData").css("background-image", "URL('" + TaskMsgClientAPIDir + "images/nodata_m.png')");
    } else {
      thisGrid.jQueryObj.find(".TaskMsgGridData").css("background-image", "");
    }

    if (thisGrid.allowPaging && thisGrid.dataPage.toPage != 1) {
      if ((thisGrid.jQueryObj.find(".TaskMsgGridScroller").get(0).clientHeight -
          thisGrid.jQueryObj.get(0).clientHeight - 61 -
          thisGrid.jQueryObj.get(0).scrollTop) > 60)
        thisGrid.jQueryObj.get(0).scrollTop += 60;
    }

    if (thisGrid.allowPaging) {
      thisGrid.jQueryObj.find(".bottomBar").show();
      if (thisGrid.dataPage.pageCount == 0) {
        thisGrid.jQueryObj.find(".bottomBar").hide();
        //thisGrid.jQueryObj.find(".bottomBar").html("暂时没有内容");
      } else if (thisGrid.dataPage.toPage == thisGrid.dataPage.pageCount) {
        thisGrid.jQueryObj.find(".bottomBar").html("（" + thisGrid.dataPage.rowsCount + "/" + thisGrid.dataPage.rowsCount + "）" +
          " 已获取全部");
      } else {
        thisGrid.jQueryObj.find(".bottomBar").html("（" + thisGrid.dataPage.toPage * 20 + "/" + thisGrid.dataPage.rowsCount + "）" +
          " 点击获取更多");
      }
    }
  };

  this.addRow = function (objData) {
    var strHtml = replaceDataField(objData, this.templateRowHtml);
    strHtml = exeExpress(strHtml);
    var row = $(strHtml);
    if (this.beforeAddRow) eval(this.beforeAddRow + "(row, objData)");
    this.jQueryObj.find(".TaskMsgGridData").append(row);
    row.show();
    if (this.afterAddRow) eval(this.afterAddRow + "(row, objData)");
  };
}

$(function () {
  $(".TaskMsgGrid").each(function (index) {
    var grid = new TaskMsgGrid();
    if ($(this).attr("id")) {
      grid.id = $(this).attr("id");
    } else {
      grid.id = "TaskMsgGrid_" + index;
    }
    taskMsgGrids[grid.id] = grid;
    grid.init($(this));
  });
});