import {VisibleComponent} from "../controller.js";

/**
 * 数据表格组件
 * @param {[type]} dataModel [description]
 */
export default class Grid extends VisibleComponent {

  constructor(__tfp, dataModel, parent) {
    super(__tfp, "Grid", dataModel, parent);

    this.pageSize = 20;
    this.curPage = 0;
    this.pageCount = 0;
    this.rowsCount = 0;
    this.dataList = [];

    if(__tfp.isDesigning) {
      if(!this.dataModel.components || this.dataModel.components.length==0) {
        this.dataModel.components = [{
          id: this.id+"_DataRow",
          type: "GridDataRow",
          styles: {
            "position": "absolute",
            "top": "0",
            "left": "10px",
            "right": "10px",
            "height": "60px",
            "border": "1px solid #cccccc",
            "border-radius": "10px"
          }
        }];
      }
    }
  }

  //属性
  get loadDataService() { return this.dataModel.loadDataService }
  set loadDataService(value) {this.dataModel.loadDataService = value}

  get dataBindingMember() { return this.dataModel.dataBindingMember }
  set dataBindingMember(value) {this.dataModel.dataBindingMember = value}

  get dataBindingKey() { return this.dataModel.dataBindingKey }
  set dataBindingKey(value) {this.dataModel.dataBindingKey = value}

  get showSearchBox() { return this.dataModel.showSearchBox }
  set showSearchBox(value) {
    this.dataModel.showSearchBox = value ? true : false;
    if(this._jqObj) {
      if(this.dataModel.showSearchBox) {
        if(this._jqObj.find(".tfp-grid-searchbox").length>0) {
          this._jqObj.find(".tfp-grid-searchbox").show();
        } else {
          $(this.getSearchBoxHtml()).insertBefore(this._jqObj.find(".tfp-grid-datalist"));
        }
        this._jqObj.find(".tfp-grid-datalist").css("top", "50px");
      } else {
        this._jqObj.find(".tfp-grid-searchbox").hide();
        this._jqObj.find(".tfp-grid-datalist").css("top", "0");
      }
    }
  }

  get allowPaging() { return this.dataModel.allowPaging }
  set allowPaging(value) { 
    this.dataModel.allowPaging = value ? true : false;
    if(this._jqObj) {
      if(this.dataModel.allowPaging) {
        if(this._jqObj.find(".tfp-grid-footer").length>0) {
          this._jqObj.find(".tfp-grid-footer").show();
        } else {
          $(this.getFooterHtml()).insertAfter(this._jqObj.find(".tfp-grid-datalist"));
        }
        this._jqObj.find(".tfp-grid-datalist").css("bottom", "50px");
      } else {
        this._jqObj.find(".tfp-grid-footer").hide();
        this._jqObj.find(".tfp-grid-footer").css("bottom", "0");
      }
    }
  }

  get containerEl() { 
    return this._jqObj.find(".tfp-grid-datalist").get(0);
  }

  deleteCptId(cptHtml) {
    let start = cptHtml.indexOf("id=\"");
    if(start<0) return cptHtml;
    let end = cptHtml.indexOf("\"", start+4);
    if(end<0) return cptHtml;
    cptHtml = cptHtml.substr(0, start)+cptHtml.substr(end+2);
    return this.deleteCptId(cptHtml);
  }

  setCptDataFormat(cdm) {
    //let cpt = this._tfp.get(cdm.id);
    if(cdm.dataBindingFormat) {
      cdm.value = cdm.dataBindingFormat;
    }
    if(cdm.components && cdm.components.length>0) {
      for(var i=0;i<cdm.components.length;i++) {
        this.setCptDataFormat(cdm.components[i]);
      }
    }
  }

  getSearchBoxHtml() {
    var html = "";
    if(this.showSearchBox) {
      var indent = this.getHtmlIndent();
      let imgUrl = this._tfp.rootPath+"/src/components/grid/images/search.png";
      let readonly = "";
      if(this._tfp.isDesigning) readonly = " readonly";
      html += indent+"\t<div class=\"tfp-grid-searchbox\">"
        +"<img src=\""+imgUrl+"\" /><input type=\"text\""+readonly+">"
        +"<label>搜索</label></div>\r\n";
    }
    return html;
  }

  getFooterHtml() {
    var html = "";
    if(this.allowPaging) {
      var indent = this.getHtmlIndent();
      html += indent+"\t<div class=\"tfp-grid-footer\">\r\n";
      html += indent+"\t\t<div style=\"border:0;\"></div>\r\n";
      html += indent+"\t\t<div>首页</div>\r\n";
      html += indent+"\t\t<div>上一页</div>\r\n";
      html += indent+"\t\t<div>下一页</div>\r\n";
      html += indent+"\t\t<div>尾页</div>\r\n";
      html += indent+"\t</div>\r\n";
    }
    return html;
  }
 
  bindData(data) {
    if(!data || !Array.isArray(data)) return;
    this.dataList = data;
    let templateRow = this._jqObj.find(".tfp-griddatarow-template");
    let dataRowHtmlTemplate = templateRow.get(0).outerHTML;
    let rowHeight = templateRow.height();
    dataRowHtmlTemplate = dataRowHtmlTemplate.replace("tfp-griddatarow-template", "tfp-griddatarow");
    let top = 0;
    this._jqObj.find(".tfp-griddatarow").remove();
    let cdmRow = this.dataModel.components[0];
    let dataListDiv = this._jqObj.find(".tfp-grid-datalist");
    for(var i=0;i<data.length;i++) {
      let rowData = data[i];
      if(cdmRow.beforeBindingData) {
        let eventFucName = tfp.getCptEventFuncName(cdmRow.beforeBindingData);
        rowData = eval(eventFucName+"(rowData)");
      }
      let dataRowHtml = dataRowHtmlTemplate;
      top = i*(rowHeight+10);
      try {
        dataRowHtml = this._tfp.replaceDataField(rowData, dataRowHtml);
        dataRowHtml = this._tfp.exeExpress(dataRowHtml);
      } catch(e) {
        console.log(e);
        return;
      }
      dataListDiv.append(dataRowHtml);
      let newRow = dataListDiv.find(".tfp-griddatarow").last();
      newRow.css("top", top+"px");
      if(cdmRow.afterBindingData) {
        let eventFucName = tfp.getCptEventFuncName(cdmRow.afterBindingData);
        eval(eventFucName+"(newRow, rowData)");
      }
    }
    dataListDiv.get(0).scrollTop = 0;
    if(this.allowPaging) this._jqObj.find(".tfp-grid-footer").find("div").eq(0).html(this.curPage+"/"+this.pageCount);
  }

  loadData(toPage) {
    if(!this.dataModel.loadDataService) {
      alert("请为["+this.id+"]设置加载数据服务！");
      return;
    }
    let 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
      };
    }

    if(this.showSearchBox) {
      let keyword = this._jqObj.find(".tfp-grid-searchbox").find("input").val();
      if(keyword.trim()!="") args.keyword = keyword;
    }

    let that = this;
    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);
      }
    });
  }

  initRuntime() {
    let that = this;
    this._jqObj.find(".tfp-grid-searchbox").find("label").click(function() {
      that.loadData(1);
    });

    if(this.allowPaging) {
      let footerDivs = this._jqObj.find(".tfp-grid-footer").find("div");
      let that = this;
      footerDivs.eq(1).click(function() {
        that.loadData(1);
      });
      footerDivs.eq(2).click(function() {
        let prevPage = that.curPage - 1;
        if(prevPage<1) prevPage = 1;
        that.loadData(prevPage);
      });
      footerDivs.eq(3).click(function() {
        let nextPage = that.curPage + 1;
        if(nextPage>that.pageCount) nextPage = that.pageCount;
        that.loadData(nextPage);
      });
      footerDivs.eq(4).click(function() {
        that.loadData(that.pageCount);
      });
    }

    this.loadData(1);
  }
}