import React,{Component} from 'react';
import classNames from 'classnames';
import RadioDrop from "@containers/RadioDrop";
import NumberDrop from "@containers/NumberDrop";
import RadioInpDrop from "@containers/RadioInpDrop";
import InlineTag from '@containers/InlineTag';
import Multiple from '@containers/Multiple';
import addIcon from '@images/addItem.png';
import addIcon1 from '@images/addItem2.png';
import style from "./index.less";
import tools from '@utils/tools';
import {setFontColorSize,handleMouseUp} from '@utils/tools';
import NumberUnitDrop from '@containers/NumberUnitDrop';


/****
 * 多标签组合
 * author:zn@2018-11.26
 * 接收参数：
 * data:展开标签数据
 * showAdd：是否显示加号（复制）
 * copyId：该标签id
 * fullData:该标签完整数据
 * showArr:是否显示下拉的总对象
 * ikey：当前组件唯一标识，由模块index+标签index+标签内index三个组成的字符串
 * boxMark：当前所在的模块
 * isImports：是否高亮（仅查体使用）
 * saveText：该模块的预览数据
 * textPrefix:前缀
 * textSuffix：后缀
 *
 * ***/

class MultSpread extends Component{
  constructor(props){
    super(props);
    this.state = {
      numDoms:[],
      tall:0,       //升高
      weight:0,     //体重
      bmi:'',        //BMI
      wrBmi:false,      //是否无效bmi值，是则要清空身高体重,不能用判断bmi是否为空来判断，因为初始就是为空
      isSelectAll:false
    };
    this.setBMIParam = this.setBMIParam.bind(this);
    this.setBMI = this.setBMI.bind(this);
    this.isBMIUseable = this.isBMIUseable.bind(this);
    this.setBMIstate = this.setBMIstate.bind(this);
  }
  getClass(){
    const {saveText,ikey,showAdd,isExtBlue,mouseSelect} = this.props;
    const labelInx = tools.getLabelIndex(ikey);
    const text = saveText&&saveText[+labelInx];
    //const orgBorder = isImports&&!text?style['orange-border']:'';
    const isSelected = text?style['selected']:style['container'];
    const hasAdd = showAdd?style['add']:'';
    const selectedArea = mouseSelect?style['selected-area']:'';
    return classNames(isSelected,hasAdd,setFontColorSize(!!text?'2,6':isExtBlue?2:1),selectedArea);
  }
  saveDoms(it){
    const doms = this.state.numDoms;
    doms.push(it);
    this.setState({
      numDoms:doms
    });
  }
  moveEnd(obj) {
    if(window.getSelection){//ie11 10 9 ff safari
      obj.focus(); //解决ff不获取焦点无法定位问题
      var range = window.getSelection();//创建range
      range.selectAllChildren(obj);//range 选择obj下所有子内容
      range.collapseToEnd();//光标移至最后
    }
    else if (document.selection) {//ie10 9 8 7 6 5
      var range = document.selection.createRange();//创建选择对象
      range.moveToElementText(obj);//range定位到obj
      range.collapse(false);//光标移至最后
      range.select();
    }
  }
  setNextFocus(i){
    const doms = this.state.numDoms;
    doms[i+1]&&this.moveEnd(doms[i+1].current)
  }
  isBMIUseable(name,val){
    const {tall,weight} = this.state;
    //身高不能为0，否则分母为0，身高体重任何一个为空，则BMI清空
    if((name==='tall'&&(!val||!weight))||(name==='weight'&&(!tall||!val))){
      return false;
    }
    return true;
  }
  setBMIParam(name,val){        //设置bmi相关数据，身高、体重
    const {tall,weight} = this.state;
    const useable = this.isBMIUseable(name,val);
    this.setState({
      [name]:val
    });
    if(useable){
      const result = name==='tall'?weight/Math.pow(val/100,2):val/Math.pow(tall/100,2);
      this.setState({
        bmi:result.toFixed(1),
        wrBmi:false
      })
    }else{
      this.setState({
        bmi:'',
        wrBmi:false
      })
    }
  }
  setBMI(val){
    //手动修改BMI赋值，且身高体重清空
    if(val===this.state.bmi){     //聚焦但未修改时
      return ;
    }
    this.setState({
      bmi:val,
      wrBmi:true,
      tall:0,
      weight:0
    });
  }
  setBMIstate(item){
    //回读时bmi相关state赋值
    const map={
      BMI_SG:'tall',
      BMI_TZ:'weight',
      BMI_RES:'bmi',
    };
    const st = this.state;
    const key = map[item.formulaCode];
    //回读BMI相关项有值时，state赋值
    if(key&&st[key]!==item.value){
      this.setState({
        [key]:item.value
      });
    }
  }
  getLabels(){
    const {data,ikey,showArr,copyId,boxMark,isExtBlue,saveText} = this.props;
    const {wrBmi,bmi,isSelectAll} = this.state;
    const labelInx = tools.getLabelIndex(ikey);
    const text = !!(saveText&&saveText[+labelInx]);
    let show = false;
    let inx = '',count=0;
    const list = data.map((it,i)=>{
      inx=ikey+'-'+i;
      show = showArr&&showArr[inx];
      switch (true){
        case +it.tagType===8:
          return it.name;
        case +it.controlType===1:
          const list = it.questionDetailList&&it.questionDetailList.length>0?it.questionDetailList:it.questionMapping;
          return <RadioDrop data={list}
                            boxMark={boxMark}
                            isExtBlue={isExtBlue}
                            placeholder={it.name}
                            show={show}
                            value = {it.value}
                            ikey={inx}
                            id={it.id}
                            patId = {copyId}
                            hideTag={true}></RadioDrop>;
        case +it.controlType===2:
          const dataList = it.questionDetailList&&it.questionDetailList.length>0?it.questionDetailList:it.questionMapping;
          return <Multiple data={dataList}
                           ikey={inx}
                           placeholder={it.name}
                           isExtBlue={isExtBlue}
                           value={it.value}
                           copyType={it.copyType}
                           selecteds={it.selecteds}
                           show={showArr&&showArr[inx]}
                           order={it.textGenerate}
                           type={boxMark}
                           id={it.id}
                           hideTag={true}></Multiple>;
        case +it.controlType===5://带单位数字键盘
        return <NumberUnitDrop prefix={it.labelPrefix}
                               suffix={it.labelSuffix}
                               placeholder={it.name}
                               boxMark={ikey.substr(0,1)}
                               isExtBlue={isExtBlue}
                               id={it.id}
                               show={show}
                               ikey={inx}
                               value={it.value}
                               hideTag={true}></NumberUnitDrop>;
        case +it.controlType===3:
        case +it.controlType===6:
          return <InlineTag prefix={it.labelPrefix}
                            suffix={it.labelSuffix}
                            placeholder={it.name}
                            isExtBlue={isExtBlue}
                            value={it.value}
                            id={it.id}
                            ikey={inx} hideTag={true}></InlineTag>;
        case +it.controlType===7:
          const min = it.minValue;//!=null&&it.minValue!=undefined?it.minValue-1:undefined;
          const max = it.maxValue;//!=null&&it.maxValue!=undefined?+it.maxValue+1:undefined;
          this.setBMIstate(it);
          return <NumberDrop prefix={it.labelPrefix}
                             suffix={it.labelSuffix}
                             boxMark={boxMark}
                             placeholder={it.name}
                             isExtBlue={isExtBlue}
                             isSelectAll={text}
                             //inputRef = {this['$inp'+(count++)]}
                             saveDoms={this.saveDoms.bind(this)}
                             reFocus={this.setNextFocus.bind(this)}
                             setBMI={this.setBMI}
                             formulaCode={it.formulaCode}
                             wrBmi={wrBmi}
                             bmi={bmi}
                             setBMIParam={this.setBMIParam}
                             num = {count++}
                             min={min}
                             max={max}
                             show={show}
                             allClick={false}
                             ikey={inx}
                             id={it.id}
                             patId = {copyId}
                             value={it.value}
                             hideTag={true}></NumberDrop>;
        case +it.controlType===11:
          return <RadioInpDrop data={it.questionDetailList}
                             vals={it.vals}
                             placeholder={it.name}
                             show={showArr&&showArr[inx]}
                             value = {it.value}
                             boxMark={boxMark}
                             isExtBlue={isExtBlue}
                             id={it.id}
                             ikey={inx}
                             hideTag={true}></RadioInpDrop>;
        default:
          return it.name;
      }
    });
    return list;
  }
  handleMouseDown(){
    const {i,setSelectArea,boxMark}= this.props;
    setSelectArea({i,boxMark,dir:'start'});
  }
  componentDidMount(){
    //挂载完成保存有加号的项目数据
    const {saveAddItem,fullData,copyId,showAdd} = this.props;
    if(showAdd){
      const data = tools.deepClone(fullData);
      setTimeout(function(){        //修改个别历史病例引用报错bug
        saveAddItem&&saveAddItem(copyId,data);
      })
    }
  }
  getContClass(){
    const {isImports,ikey,saveText,isExtBlue,mouseSelect} = this.props;
    const labelInx = tools.getLabelIndex(ikey);
    const text = saveText&&saveText[+labelInx];
    const ext = !text&&isExtBlue?style['ext']:'';
    const orgBorder = isImports&&!text?style['orange-border']:'';
    const selectedArea = mouseSelect?style['selected-area']:'';
    return classNames(orgBorder,ext,selectedArea);
  }
  render(){
    const {showAdd,addLabelItem,ikey,copyId,textPrefix,textSuffix,isExtBlue,select_start,i,boxMark} = this.props;
    return (<div className={this.getContClass()}
                 style={{display:'inline-block'}}
                 onMouseUp={()=>handleMouseUp({select_start,i,boxMark})}
                 onMouseDown={this.handleMouseDown.bind(this)}>
        {textPrefix?<span className="prefixUnset">{textPrefix}</span>:''}
        <div className={this.getClass()}>
          {this.getLabels()}
          {textSuffix?<span className="prefixUnset">{textSuffix}</span>:''}
          {showAdd?<img src={isExtBlue?addIcon1:addIcon} alt="复制该项"
                        className={style['add-icon']}
                        onClick={()=>addLabelItem({ikey,copyId})}/>:''}
        </div>
    </div>)
  }
}

export default MultSpread;