import React, { Component } from "react";
import style from "./index.less";
import Notify from '../Notify';
import config from '@config/index';
import {setLastPosition} from '@common/js/util';

class Textarea extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timer:null,
      inpText:'',
      overFlag:false
    };
    this.$dom = React.createRef();
    this.handleInput = this.handleInput.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    //this.handleBlur = this.handleBlur.bind(this);
  }
  handleFocus(){            //初始显示props中的值，focus已经显示输入的值，避免值更新闪烁
    const {handleFocus,fuzhen,handleInput} = this.props;
    handleFocus&&handleFocus();         //其他史、查体获取数据的方法
    if(fuzhen&&!this.$dom.current.innerText){
      const text = config.currentText.replace("(**)",fuzhen);
      this.$dom.current.innerText = text;
      handleInput&&handleInput({text});
    }

  }
  handleInput(e){
    const {handleInput,boxMark,handlePush,hasMain} = this.props;
    const {inpText,overFlag} = this.state;
    const text = e.target.innerText;
    const stimer = this.state.timer;
    if(boxMark=='1'&&text.length>config.limited){           //主诉字符数限制
      e.target.innerText = text.substr(0,config.limited); 
      e.target.blur();
      Notify.error(config.limitText);
      if(overFlag){
        e.target.innerText = inpText;
        return
      }
      this.setState({
        inpText:text.substr(0,config.limited),
        overFlag:true
      })
      return;
    }
    if(boxMark=='3'&&!hasMain){
      e.target.innerText = '';
      return;
    }
    this.setState({
      inpText:text,
      overFlag:false
    })

    //存值到store
    handleInput&&handleInput({text});
    //右侧推送--延时推送
    clearTimeout(stimer);
    let timer = setTimeout(function(){
      handlePush&&handlePush();
      clearTimeout(stimer);
    },config.delayPushTime);
    this.setState({
      timer
    });
  }
  shouldComponentUpdate(next){
    if(JSON.stringify(next) == JSON.stringify(this.props)){
      return false;
    }
    return true;
  }
  componentWillReceiveProps(next){
    const isRead = this.props.isRead;
    if(next.isRead != isRead){
      this.$dom.current.innerText = next.value||'';
    }
  }
  componentDidMount(){
    const {value} = this.props;
    if(value){
      this.$dom.current.innerText = value||'';
    }
  }
  render() {
    const { title } = this.props;
    return (
      <div className={style["box"]}>
        <div className={style["title"]}>{title}</div>
        {/*{isRead?<div className={style["content"]+" "+'11'} contentEditable={true} onFocus={this.handleFocus}>{value}</div>:''}*/}
        <div className={style["content"]}
             onFocus={this.handleFocus}
             ref={this.$dom}
             contentEditable={true}
             onInput={this.handleInput}>
        </div>
      </div>
    );
  }
}

export default Textarea;
