import React,{Component} from 'react';
import style from './index.less';
import {isIE,handleEnter} from '@utils/tools.js';
import $ from 'jquery';
/***
 * author:zn@2018-11-13
 * 电子病历项内容框
 * 接收参数：
 * boxHeight：框高度
 * boxWidth：框宽度
 * title：框名称（如主诉、现病史）
 * editable：是否可编辑
 * children：框内内容
 * border:边框样式,
 * style
 *
 * ***/
class ItemBox extends Component {
  constructor(props){
    super(props);
    this.$div = React.createRef();
    this.handleClick = this.handleClick.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }
  getBoxStyle(){
    const {boxHeight,boxWidth,boxLineHeight,marginTop,backgroundColor,style} = this.props;
    const sty = {width:boxWidth?boxWidth:undefined,height:boxHeight?boxHeight:undefined,lineHeight:boxLineHeight?boxLineHeight:'22px',marginTop:marginTop,backgroundColor:backgroundColor?backgroundColor:''};
    return style?Object.assign(style,sty):sty;
  }

  handleClick(e){
    const {handleClick} = this.props;
    handleClick && handleClick(e);//为了获取鼠标位置，显示搜索结果框；
  }
  handleInput(e){
    const {handleChange,data} = this.props;
    if(!data || (data.length==0)){//避免结构化下触发onchange，导致下拉要点两下
      handleChange&&handleChange(e)
    }
  }

  componentDidMount(){
    const {setRef} = this.props;
    this.$div.current.innerHTML='';     //bug2276,FF26初始光标位置问题
    setRef&&setRef(this.$div);
    if(isIE()){
      $(this.$div.current).onIe8Input(function(e){
        this.handleInput(e)
      },this);
    }
  }
componentWillReceiveProps(nextP){
    if(nextP.children.length>1){
      const that = this;
      //数据渲染后更新滚动条
      setTimeout(function(){
        that.context.scrollArea&&that.context.scrollArea.refresh();
      });
    }
}
  render(){
    const {title,children,editable,className,handleFocus,fuzhen,border,handleBlur,titleTop,backgroundColor,boxId} = this.props;
    return <div className={style["box"]+" "+"clearfix"} >
      <div className={style["title"] + ' '+(className||'')} style={{marginTop:titleTop?'22px':''}}>{title}</div>
      <div ref={this.$div} className={`${style["content"]} ${border?style["border"]:''} ${backgroundColor?style["noBorder"]:''}`} contentEditable={editable} style={this.getBoxStyle()} onFocus={editable?handleFocus:null} onInput={this.handleInput} onClick={(e)=>{this.handleClick(e);}} onBlur={handleBlur} id={boxId} onkeydown={handleEnter}>
        {fuzhen?children||fuzhen:children}
      </div>
    </div>
  }
}
ItemBox.contextTypes = {
  scrollArea: React.PropTypes.object
};
export default ItemBox;