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

/**
 * 单行文本组件
 * @param {[type]} dataModel [description]
 */
export default class Text extends FormInput {

  constructor(__tfp, dataModel, parent, inputType) {
    if(inputType) {
      super(__tfp, inputType, dataModel, parent);
    } else {
      super(__tfp, "Text", dataModel, parent);
    }
  }

  get value() { 
    if(!this.dataModel.value) return "";
    return this.dataModel.value; 
  }
  set value(value) {
    let val = value;
    if(isNull(value)) {
      val = "";
      this.dataModel.value = null;
    } else {
      //如果设置了计算公式，则需要替换掉金额里的逗号
      if(this.dataModel.formula) {
        val = (val + "").trim().replaceAll(",", "");
        if(isNaN(val)) return;
      }
      try {
        if(this.dataModel.dataType=="int") {
          val = parseInt(val);
        } else if(this.dataModel.dataType=="float") {
          val = parseFloat(val);
        } else if(this.dataModel.dataType=="money") {
          val = this._tfp.formatMoney(val, 2);
        }
      } catch(err) {
        console.error(err.message);
        //this._tfp.showMsg(err.message);
        return;
      }
      this.dataModel.value = val;
    }
    if(this._jqObj) {
      this._jqObj.val(val);
    }
    if(!this._tfp.isDesigning) {
      this.valueOnChange();
      this.exeEventHandler("onChange", val);
    }
  }

  get maxLength() { return this.dataModel.maxLength }
  set maxLength(value) { 
    this.dataModel.maxLength = value;
    if(this._jqObj) this._jqObj.attr("maxlength", value);
  }

  get placeHolder() { return this.dataModel.placeHolder }
  set placeHolder(value) { 
    this.dataModel.placeHolder = value;
    if(this._jqObj) this._jqObj.attr("placeholder", value);
  }

  get dataType() {
    if(!this.dataModel.dataType) this.dataModel.dataType = "text";
    return this.dataModel.dataType; 
  }
  set dataType(value) {
    this.dataModel.dataType = value;
  }

  initRuntime() {
    let that = this;
    this._jqObj.blur(function() {
      let val = $(this).val().trim();
      if(!isNull(val)) {
        if(that.dataModel.dataType && that.dataModel.dataType!="text") {
          if(isNaN(val)) {
            $(this).focus();
            return;
          }
        }
        try {
          if(that.dataModel.dataType=="int") {
            if (!isInt(val)) {
              $(this).focus();
              return;
            }
            val = parseInt(val);
          } else if(that.dataModel.dataType=="float") {
            val = parseFloat(val);
          } else if(that.dataModel.dataType=="money") {
            val = that._tfp.formatMoney(val, 2);
          }
        } catch(err) {
          console.error(err.message);
          $(this).focus();
          return;
        }
      }
      that.dataModel.value = val;
      that.valueOnChange();
      that.exeEventHandler("onChange", val);
    });
  }
}