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.curPage = 0;
    this.pageCount = 0;
    this.rowsCount = 0;
    this.dataList = [];
  }

  //属性
  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 delDataService() { return this.dataModel.delDataService }
  set delDataService(value) {this.dataModel.delDataService = value }

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

  get allowPaging() { return this.dataModel.allowPaging }
  set allowPaging(value) { 
    this.dataModel.allowPaging = value ? true : false;
    if(this._jqObj) {
      let 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();
    }
  }

  get showHeader() { return this.dataModel.showHeader }
  set showHeader(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();
    }
  }

  get showFooter() { return this.dataModel.showFooter }
  set showFooter(value) { 
    this.dataModel.showFooter = value ? true : false;
    if(this._jqObj) {
      let 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();
    }
  }

  get showCheckbox() { return this.dataModel.showCheckbox }
  set showCheckbox(value) { 
    this.dataModel.showCheckbox = value ? true : false;
  }

  get rowHeight() { return this.dataModel.rowHeight }
  set rowHeight(value) { 
    this.dataModel.rowHeight = value;
    if(this._jqObj) {
      let divDataRow = this._jqObj.find(".tfp-grid-datarow");
      let 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);
    }
  }

  get columns() { return this.dataModel.columns }
  set columns(value) { 
    this.dataModel.columns = value;
    if(this._jqObj) {
      let Render = this._tfp.renders[this.type];
      if(Render) {
        let render = new Render(this._tfp, this.dataModel, this.level);
        this._jqObj.html(render.getBodyHtml(false));
      }
      this.resetRowWith();
    }
  }

  getColWidth(width) {
    if(!width) return "80px";
    if(width.indexOf("px")<0 && width.indexOf("%")<0) return width+"px";
    return width;
  }

  resetRowWith() {
    if(this._jqObj.length==0) return;
    let divDataList = this._jqObj.find(".tfp-grid-datalist");
    if(divDataList.length==0) return;
    let 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);
    }
  }

  resetDataListPosition() {
    let 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");
    }
    let dataListBottom = 0;
    let divTotal = this._jqObj.find(".tfp-grid-total");
    if(divTotal.length>0) dataListBottom += divTotal.height()+1;
    let divFooter = this._jqObj.find(".tfp-grid-footer");
    if(divFooter.length>0) dataListBottom += divFooter.height()+1;
    divDataList.css("bottom", dataListBottom+"px");
  };

  getFooterHtml() {
    let indent = this.getHtmlIndent();
    let 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>";
        let pageSizeOptions = [20,30,50,100];
        for(var i=0;i<pageSizeOptions.length;i++) {
          let 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;
  }

  //获得行模板
  getRowTemplate() {
    if(!this.dataModel.columns) return;
    let html = "\t<div class=\"tfp-grid-datarow\" style=\"width:{data-row-width};";
    let 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";
    let 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 {
          let keys = this.dataModel.dataBindingKey.split(",");
          let 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++) {
      let col = this.dataModel.columns[i];
      html += "\t\t<div";
      if(col.class) html += " class=\""+col.class+"\"";
      html += " style=\"";
      let 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;
    let 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;
  }

  //添加行
  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);
  }

  deleteRow(keyValue) {
    if(!this.dataModel.delDataService) {
      alert("请设置删除数据的服务！");
      return;
    }
    if(!this.dataModel.dataBindingKey) {
      alert("请设置数据主键字段名！");
      return;
    }
    if(confirm("确定删除？")) {
      let serviceCpt = this._tfp.components[this.dataModel.delDataService];
      let args = {};
      if(this.dataModel.dataBindingKey.indexOf(",")<0) {
        args[this.dataModel.dataBindingKey] = keyValue;
      } else {
        let 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];
        }
      }
      let that = this;
      serviceCpt.request(args, function(req, res) {
        if(res.code!=0) {
          that._tfp.showMsg(res.message);
          return;
        }
        that.reloadData();
      });
    }
  }

  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;
      });
    }
  }

  getCheckedValues() {
    let vals = "";
    this._jqObj.find(".tfp-grid-datarow-checkbox").each(function() {
      let cbk = $(this).find("input").get(0);
      if(cbk.checked) {
        if(vals!="") vals += ",";
        vals += cbk.value;
      }
    });
    return vals;
  }

  getCheckedRows() {
    let rows = [];
    let cbks = this._jqObj.find(".tfp-grid-datarow-checkbox");
    for(var i=0;i<cbks.length;i++) {
      let cbk = $(cbks[i]).find("input").get(0);
      if(cbk.checked) {
        rows.push(this.dataList[i]);
      }
    }
    return rows;
  }

  //设置翻页行
  setFooter() {
    let 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);
    }
  }

  changePageSize(slt) {
    if(!this.dataModel.loadDataService || !this.dataModel.dataBindingMember) return;
    this.pageSize = slt.value;
    this.loadData(this.curPage);
  }

  gotoPage(toPage) {
    this.loadData(toPage);
  }

  bindData(data) {
    if(!data || !Array.isArray(data)) return;
    this.dataList = data;
    let 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();
  }

  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
      };
    }

    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);
      }
    });
  }

  reloadData = function() {
    this.loadData(1);
  }

  initRuntime() {
    let that = this;
    let divDataList = this._jqObj.find(".tfp-grid-datalist");
    divDataList.scroll(function() {
      let divHeader = that._jqObj.find(".tfp-grid-header");
      if(divHeader.length>0) {
        divHeader.get(0).scrollLeft = divDataList.get(0).scrollLeft;
      }
      let divTotalRow = that._jqObj.find(".tfp-grid-total");
      if(divTotalRow.length>0) {
        divTotalRow.get(0).scrollLeft = divDataList.get(0).scrollLeft;
      }
    });
    
    if(this.allowPaging) {
      let 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);
  }
}