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

/**
 * 单选框组件
 * @param {[type]} dataModel [description]
 */
export default class Radio extends FormInput {

  constructor(__tfp, dataModel, parent) {
    super(__tfp, "Radio", dataModel, parent);
  }

  //属性
  get value() { return this.dataModel.value; }
  set value(value) { 
    this.dataModel.value = value;
    if(this._jqObj) {
      this._jqObj.find(".tfp-radio-box").each(function() {
        if($(this).attr("data-option")==value) {
          $(this).find("div").css("display", "inline-block");
        } else {
          $(this).find("div").css("display", "none");
        }
      });
      this.exeEventHandler("onChange");
    }
  }

  get options() { return this.dataModel.options }
  set options(value) {
    if(!value) return;
    this.setOptions(value);
    if(this._jqObj) {
      this._jqObj.empty();
      for(var i=0;i<value.length;i++) {
        this.addOption(value[i], true);
      }
    }
  }

  get portrait() { return this.dataModel.portrait }
  set portrait(value) { 
    this.dataModel.portrait = value ? true : false;
    if(this._jqObj) {
      if(value) {
        let that = this;
        this._jqObj.find("label").each(function(index) {
          if(index<(that._jqObj.find("label").length-1)) {
            $("<br/>").insertAfter($(this));
          }
        });
      } else {
        this._jqObj.find("br").remove();
      }
    }
  }

  getOptionHtml(indent, option) {
    let optionHtml = "";
    let optionDisplay = "none";
    if(this.value==option.value) optionDisplay = "inline-block";
    let disabledStyle = "";
    if(this.dataModel.disabled) disabledStyle = " style=\"background-color:#eeeeee;\"";
    optionHtml += indent+"\t<div class=\"tfp-radio-box\" "
      +disabledStyle+" data-option=\""+option.value+"\">"
      +"<div style=\"display:"+optionDisplay+";\"></div></div>";
    if(option.text) {
      optionHtml += "<label>"+option.text+"</label>\r\n";
    } else {
      optionHtml += "<label>"+option.value+"</label>\r\n";
    }
    return optionHtml;
  }

  addOption(option, isInit) {
    let indent = this.getHtmlIndent();
    let str = "";
    if(this.portrait && this._jqObj.children().length>0) 
      str += indent+"\t<br>\r\n";
    str += this.getOptionHtml(indent, option);
    if(str!="") {
      this._jqObj.append(str);
      if(!isInit) this.dataModel.options.push(option);
    }
  }

  initRuntime() {
    let that = this;
    this._jqObj.find(".tfp-radio-box").each(function() {
      $(this).click(function() {
        if(that.dataModel.disabled) return;
        that.value = $(this).attr("data-option");
      });
    });
  }
}