"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var _controller = require("../controller.js");

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); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * 数据表格组件
 * @param {[type]} dataModel [description]
 */
var Grid = /*#__PURE__*/function (_VisibleComponent) {
  _inherits(Grid, _VisibleComponent);

  var _super = _createSuper(Grid);

  function Grid(__tfp, dataModel, parent) {
    var _this;

    _classCallCheck(this, Grid);

    _this = _super.call(this, __tfp, "Grid", dataModel, parent);

    _defineProperty(_assertThisInitialized(_this), "reloadData", function () {
      this.loadData(1);
    });

    _this.curPage = 0;
    _this.pageCount = 0;
    _this.rowsCount = 0;
    _this.dataList = [];
    return _this;
  } //属性


  _createClass(Grid, [{
    key: "loadDataService",
    get: function get() {
      return this.dataModel.loadDataService;
    },
    set: function set(value) {
      this.dataModel.loadDataService = value;
    } //属性

  }, {
    key: "dataBindingMember",
    get: function get() {
      return this.dataModel.dataBindingMember;
    },
    set: function set(value) {
      this.dataModel.dataBindingMember = value;
    } //属性

  }, {
    key: "dataBindingKey",
    get: function get() {
      return this.dataModel.dataBindingKey;
    },
    set: function set(value) {
      this.dataModel.dataBindingKey = value;
    } //属性

  }, {
    key: "delDataService",
    get: function get() {
      return this.dataModel.delDataService;
    },
    set: function set(value) {
      this.dataModel.delDataService = value;
    } //属性

  }, {
    key: "pageSize",
    get: function get() {
      return this.dataModel.pageSize;
    },
    set: function set(value) {
      this.dataModel.pageSize = value;
    }
  }, {
    key: "allowPaging",
    get: function get() {
      return this.dataModel.allowPaging;
    },
    set: function set(value) {
      this.dataModel.allowPaging = value ? true : false;

      if (this._jqObj) {
        var divFooter = this._jqObj.find(".tfp-grid-footer");

        if (value) {
          //允许翻页就必须显示页尾
          this.dataModel.showFooter = true;
          if (this._tfp.isDesigning && uiDesigner.curSelectedCptId == this.id) uiDesigner.setCurCptAttrSettingVal("showFooter", true);
          if (divFooter.length > 0) divFooter.remove();

          this._jqObj.append(this.getFooterHtml());
        } else {
          if (divFooter.length > 0) {
            divFooter.remove();

            this._jqObj.append(this.getFooterHtml());
          }
        }

        this.resetDataListPosition();
      }
    }
  }, {
    key: "showHeader",
    get: function get() {
      return this.dataModel.showHeader;
    },
    set: function set(value) {
      this.dataModel.showHeader = value ? true : false;

      if (this._jqObj) {
        if (value) {
          this._jqObj.find(".tfp-grid-header").show();
        } else {
          this._jqObj.find(".tfp-grid-header").hide();
        }

        this.resetDataListPosition();
      }
    }
  }, {
    key: "showFooter",
    get: function get() {
      return this.dataModel.showFooter;
    },
    set: function set(value) {
      this.dataModel.showFooter = value ? true : false;

      if (this._jqObj) {
        var divFooter = this._jqObj.find(".tfp-grid-footer");

        if (value) {
          if (divFooter.length > 0) divFooter.remove();

          this._jqObj.append(this.getFooterHtml());
        } else {
          //不显示页尾就不允许翻页
          this.dataModel.allowPaging = false;
          if (this._tfp.isDesigning && uiDesigner.curSelectedCptId == this.id) uiDesigner.setCurCptAttrSettingVal("allowPaging", false);
          divFooter.remove();
        }

        this.resetDataListPosition();
      }
    }
  }, {
    key: "showCheckbox",
    get: function get() {
      return this.dataModel.showCheckbox;
    },
    set: function set(value) {
      this.dataModel.showCheckbox = value ? true : false;
    }
  }, {
    key: "rowHeight",
    get: function get() {
      return this.dataModel.rowHeight;
    },
    set: function set(value) {
      this.dataModel.rowHeight = value;

      if (this._jqObj) {
        var divDataRow = this._jqObj.find(".tfp-grid-datarow");

        var rowHeight = value + "";
        if (!rowHeight) rowHeight = "40px";
        if (rowHeight.indexOf("px") < 0) rowHeight += "px";
        divDataRow.css("height", rowHeight);
        divDataRow.css("line-height", rowHeight);
        divDataRow.children("div").css("height", rowHeight);
      }
    }
  }, {
    key: "columns",
    get: function get() {
      return this.dataModel.columns;
    },
    set: function set(value) {
      this.dataModel.columns = value;

      if (this._jqObj) {
        var Render = this._tfp.renders[this.type];

        if (Render) {
          var render = new Render(this._tfp, this.dataModel, this.level);

          this._jqObj.html(render.getBodyHtml(false));
        }

        this.resetRowWith();
      }
    }
  }, {
    key: "getColWidth",
    value: function getColWidth(width) {
      if (!width) return "80px";
      if (width.indexOf("px") < 0 && width.indexOf("%") < 0) return width + "px";
      return width;
    }
  }, {
    key: "resetRowWith",
    value: function resetRowWith() {
      if (this._jqObj.length == 0) return;

      var divDataList = this._jqObj.find(".tfp-grid-datalist");

      if (divDataList.length == 0) return;

      var divDataRow = this._jqObj.find(".tfp-grid-datarow");

      if (divDataRow.length == 0) return;

      if (this.rowWith < divDataList.width() - 2) {
        divDataRow.css("width", "100%");
      } else {
        divDataRow.css("width", this.rowWith);
      }
    }
  }, {
    key: "resetDataListPosition",
    value: function resetDataListPosition() {
      var divDataList = this._jqObj.find(".tfp-grid-datalist");

      if (this.dataModel.showHeader) {
        divDataList.css("top", this._jqObj.find(".tfp-grid-header").height() + 1 + "px");
      } else {
        divDataList.css("top", "0");
      }

      var dataListBottom = 0;

      var divTotal = this._jqObj.find(".tfp-grid-total");

      if (divTotal.length > 0) dataListBottom += divTotal.height() + 1;

      var divFooter = this._jqObj.find(".tfp-grid-footer");

      if (divFooter.length > 0) dataListBottom += divFooter.height() + 1;
      divDataList.css("bottom", dataListBottom + "px");
    }
  }, {
    key: "getFooterHtml",
    value: function getFooterHtml() {
      var indent = this.getHtmlIndent();
      var html = "";

      if (this.showFooter) {
        if (this.allowPaging) {
          html += indent + "\t<div class=\"tfp-grid-footer\">\r\n" + indent + "\t\t<div class=\"tfp-grid-btn-first\">首页</div>&nbsp;&nbsp;\r\n" + indent + "\t\t<div class=\"tfp-grid-btn-prev\">上一页</div>&nbsp;&nbsp;\r\n" + indent + "\t\t<div class=\"tfp-grid-btn-next\">下一页</div>&nbsp;&nbsp;\r\n" + indent + "\t\t<div class=\"tfp-grid-btn-last\">尾页</div>&nbsp;&nbsp;\r\n" + indent + "\t\t第 <span class=\"tfp-grid-curpage\">0</span> 页/共 \r\n" + indent + "\t\t<span class=\"tfp-grid-pagecount\">0</span> 页,\r\n" + indent + "\t\t<span class=\"tfp-grid-rowcount\">0</span> 条记录&nbsp;&nbsp;\r\n";
          html += indent + "\t\t<select>";
          var pageSizeOptions = [20, 30, 50, 100];

          for (var i = 0; i < pageSizeOptions.length; i++) {
            var pageSize = pageSizeOptions[i];
            html += indent + "\t\t\t<option value=\"" + pageSize + "\"";
            if (this.pageSize == pageSize + "") html += " selected";
            html += ">" + pageSize + "</option>";
          }

          html += indent + "\t\t</select>\r\n" + indent + "\t</div>";
        } else {
          html += indent + "\t<div class=\"tfp-grid-footer\">共 " + "<span class=\"tfp-grid-rowcount\">0</span> 条记录</div>\r\n";
        }
      }

      return html;
    } //获得行模板

  }, {
    key: "getRowTemplate",
    value: function getRowTemplate() {
      if (!this.dataModel.columns) return;
      var html = "\t<div class=\"tfp-grid-datarow\" style=\"width:{data-row-width};";
      var rowHeight = null;

      if (this.dataModel.rowHeight) {
        rowHeight = this.dataModel.rowHeight.indexOf("px") < 0 ? this.dataModel.rowHeight + "px" : this.dataModel.rowHeight;
        html += "height: " + rowHeight + "; line-height: " + rowHeight + ";";
      }

      html += "\">\r\n";
      var rowWith = 0;

      if (this.dataModel.showCheckbox) {
        html += "\t\t<div class=\"tfp-grid-datarow-checkbox\"><input type=\"checkbox\"";

        if (this.dataModel.dataBindingKey) {
          if (this.dataModel.dataBindingKey.indexOf(",") < 0) {
            html += " value=\"{" + this.dataModel.dataBindingKey + "}\"";
          } else {
            var keys = this.dataModel.dataBindingKey.split(",");
            var keyVal = "";

            for (var i = 0; i < keys.length; i++) {
              if (i > 0) keyVal += "_";
              keyVal += "{" + keys[i] + "}";
            }

            html += " value=\"" + keyVal + "\"";
          }
        }

        html += " /></div>";
        rowWith += 30;
      }

      for (var i = 0; i < this.dataModel.columns.length; i++) {
        var col = this.dataModel.columns[i];
        html += "\t\t<div";
        if (col["class"]) html += " class=\"" + col["class"] + "\"";
        html += " style=\"";
        var colWidth = this.getColWidth(col.width);
        html += "width:" + colWidth + ";"; //TODO 列宽暂不支持百分比的精确计算，只是简单的把%替换掉了

        rowWith += parseInt(colWidth.replace("px", "").replace("%", ""));
        if (rowHeight) html += "height: " + rowHeight + ";";
        if (col.align) html += "text-align:" + col.align + ";";
        if (col.color) html += "color:" + col.color + ";";
        if (col.bgColor) html += "background-color:" + col.bgColor + ";";
        if (col.bold) html += "font-weight: bold;";
        if (col.fontSize) html += "font-size: " + col.fontSize + ";";
        if (col.onClick) html += "cursor: pointer;";
        if (col.style) html += col.style;
        html += "\"";

        if (col.onClick) {
          html += " onclick=\"" + col.onClick + "\"";
        }

        html += ">";
        if (col.format) html += col.format;
        html += "</div>\r\n";
      }

      html += "\t</div>\r\n";
      this.rowWith = rowWith;

      var divDataList = this._jqObj.find(".tfp-grid-datalist");

      if (rowWith < divDataList.width() - 2) {
        rowWith = "100%";
      } else {
        rowWith += "px";
      }

      html = html.replace("{data-row-width}", rowWith);
      return html;
    } //添加行

  }, {
    key: "addRow",
    value: function addRow(rowData) {
      if (!this.rowTemplate) this.rowTemplate = this.getRowTemplate();
      var rowHtml = "";

      try {
        rowHtml = tfp.replaceDataField(rowData, this.rowTemplate);
        rowHtml = tfp.exeExpress(rowHtml);
      } catch (e) {
        console.log(e);
      }

      this._jqObj.find(".tfp-grid-datalist").append(rowHtml);
    }
  }, {
    key: "deleteRow",
    value: function deleteRow(keyValue) {
      if (!this.dataModel.delDataService) {
        alert("请设置删除数据的服务！");
        return;
      }

      if (!this.dataModel.dataBindingKey) {
        alert("请设置数据主键字段名！");
        return;
      }

      if (confirm("确定删除？")) {
        var serviceCpt = this._tfp.components[this.dataModel.delDataService];
        var args = {};

        if (this.dataModel.dataBindingKey.indexOf(",") < 0) {
          args[this.dataModel.dataBindingKey] = keyValue;
        } else {
          var dataKeys = this.dataModel.dataBindingKey.split(",");

          for (var i = 0; i < dataKeys.length; i++) {
            if (arguments.length < i + 2) break;
            args[dataKeys[i]] = arguments[i + 1];
          }
        }

        var that = this;
        serviceCpt.request(args, function (req, res) {
          if (res.code != 0) {
            that._tfp.showMsg(res.message);

            return;
          }

          that.reloadData();
        });
      }
    }
  }, {
    key: "checkAll",
    value: function checkAll(cbk) {
      if (cbk.checked) {
        this._jqObj.find(".tfp-grid-datarow-checkbox").each(function () {
          $(this).find("input").get(0).checked = true;
        });
      } else {
        this._jqObj.find(".tfp-grid-datarow-checkbox").each(function () {
          $(this).find("input").get(0).checked = false;
        });
      }
    }
  }, {
    key: "getCheckedValues",
    value: function getCheckedValues() {
      var vals = "";

      this._jqObj.find(".tfp-grid-datarow-checkbox").each(function () {
        var cbk = $(this).find("input").get(0);

        if (cbk.checked) {
          if (vals != "") vals += ",";
          vals += cbk.value;
        }
      });

      return vals;
    }
  }, {
    key: "getCheckedRows",
    value: function getCheckedRows() {
      var rows = [];

      var cbks = this._jqObj.find(".tfp-grid-datarow-checkbox");

      for (var i = 0; i < cbks.length; i++) {
        var cbk = $(cbks[i]).find("input").get(0);

        if (cbk.checked) {
          rows.push(this.dataList[i]);
        }
      }

      return rows;
    } //设置翻页行

  }, {
    key: "setFooter",
    value: function setFooter() {
      var footerDiv = this._jqObj.find(".tfp-grid-footer");

      if (this.allowPaging) {
        footerDiv.find(".tfp-grid-curpage").text(this.curPage);
        footerDiv.find(".tfp-grid-pagecount").text(this.pageCount);
        footerDiv.find(".tfp-grid-rowcount").text(this.rowsCount);
      } else {
        footerDiv.find(".tfp-grid-rowcount").text(this.dataList.length);
      }
    }
  }, {
    key: "changePageSize",
    value: function changePageSize(slt) {
      if (!this.dataModel.loadDataService || !this.dataModel.dataBindingMember) return;
      this.pageSize = slt.value;
      this.loadData(this.curPage);
    }
  }, {
    key: "gotoPage",
    value: function gotoPage(toPage) {
      this.loadData(toPage);
    }
  }, {
    key: "bindData",
    value: function bindData(data) {
      if (!data || !Array.isArray(data)) return;
      this.dataList = data;

      var divDataList = this._jqObj.find(".tfp-grid-datalist");

      divDataList.empty(); //生成行模板

      if (!this.rowTemplate) this.rowTemplate = this.getRowTemplate();

      if (this.dataList instanceof Array) {
        for (var i = 0; i < this.dataList.length; i++) {
          this.addRow(this.dataList[i]);
        }
      } else {
        this.dataList = [];
      } //if(this.showSumer) this.setSumer();


      this.setFooter();
    }
  }, {
    key: "loadData",
    value: function loadData(toPage) {
      if (!this.dataModel.loadDataService) {
        alert("请为[" + this.id + "]设置加载数据服务！");
        return;
      }

      var serviceCpt = this._tfp.get(this.dataModel.loadDataService);

      if (!serviceCpt) {
        alert("ID为[" + this.dataModel.loadDataService + "]的组件不存在！");
        return;
      }

      if (!this.dataModel.dataBindingMember) {
        alert("请为[" + this.id + "]设置数据绑定成员！");
        return;
      }

      var args = {};

      if (this.allowPaging) {
        args = {
          pageSize: this.pageSize,
          toPage: toPage ? toPage : 1
        };
      }

      var that = this; //与服务组件建立绑定

      if (!serviceCpt.bindCpts) serviceCpt.bindCpts = [];
      if (!serviceCpt.bindCpts.contains(this.id)) serviceCpt.bindCpts.push(this.id);
      serviceCpt.status = 0;
      serviceCpt.request(args, function (req, res) {
        var data = res[that.dataModel.dataBindingMember];
        if (!data) return;

        if (that.allowPaging) {
          that.curPage = data.toPage;
          that.rowsCount = data.rowsCount;
          that.pageCount = data.pageCount;
          that.pageSize = data.pageSize;
          that.bindData(data.rows);
        } else {
          that.bindData(data);
        }
      });
    }
  }, {
    key: "initRuntime",
    value: function initRuntime() {
      var that = this;

      var divDataList = this._jqObj.find(".tfp-grid-datalist");

      divDataList.scroll(function () {
        var divHeader = that._jqObj.find(".tfp-grid-header");

        if (divHeader.length > 0) {
          divHeader.get(0).scrollLeft = divDataList.get(0).scrollLeft;
        }

        var divTotalRow = that._jqObj.find(".tfp-grid-total");

        if (divTotalRow.length > 0) {
          divTotalRow.get(0).scrollLeft = divDataList.get(0).scrollLeft;
        }
      });

      if (this.allowPaging) {
        var divFooter = this._jqObj.find(".tfp-grid-footer");

        divFooter.find(".tfp-grid-btn-first").click(function () {
          that.gotoPage(1);
        });
        divFooter.find(".tfp-grid-btn-prev").click(function () {
          var prevPage = that.curPage - 1;
          if (prevPage < 1) prevPage = 1;
          that.gotoPage(prevPage);
        });
        divFooter.find(".tfp-grid-btn-next").click(function () {
          var nextPage = that.curPage + 1;
          if (nextPage > that.pageCount) nextPage = that.pageCount;
          that.gotoPage(nextPage);
        });
        divFooter.find(".tfp-grid-btn-last").click(function () {
          that.gotoPage(that.pageCount);
        });
        divFooter.find("select").change(function () {
          that.changePageSize($(this).get(0));
        });
      }

      $(window).resize(function () {
        that.resetRowWith();
      });
      this.resetRowWith();
      this.loadData(1);
    }
  }]);

  return Grid;
}(_controller.VisibleComponent);

exports["default"] = Grid;