import React, { Component } from "react";
import style from "../index.less";
import deleteIcon from '@common/images/delete.png';
import deleteIconNo from '@common/images/delete_no.png';
import allTableIcon from '@common/images/all-table.png';
import level1 from "@common/images/级别1.png";
import checkIcon from '@common/images/check.png';
import {ComplexModal,MiniToast,Radio} from '@commonComp';
import Notify from '@commonComp/Notify';
import {deepClone,preventDefault} from '@utils/tools';
import { getFormulaResult } from '@store/async-actions/fetchModules'
/**
 * 来源于页面选择
 *
 * **/
class ScaleItem extends Component {
  constructor(props) {
    super(props);
    this.$area = React.createRef();
    const {result}= props;
    let radioVal = result&&result.radioVal;
    this.state = {
      scaleId:'',
      scaleName:'',
      parentId:'',
      showScale:false,
      optionId:'',
      radioVal:Object.assign({},radioVal)||{},
      formulaId:'',
      text:props.text,
      isCalculated:false,
      calcuValues:deepClone(props.calcuValues),   //计算公式填的值
    };
    this.getItems = this.getItems.bind(this);
    this.getDetailItems = this.getDetailItems.bind(this);
    this.showOption = this.showOption.bind(this);
    this.closeOption = this.closeOption.bind(this);
    this.closeFormula = this.closeFormula.bind(this);
    this.handleInputformula =this.handleInputformula.bind(this);
  }
  showOption(id){
    this.setState({
      optionId: id,
      formulaId: ''
    })
  }
  closeOption(){
    const {result} = this.props;
    const possible=result&&result.possible;
    let {radioVal} = this.state;
    this.setState({
      radioVal:Object.assign({},radioVal,possible),
      optionId:null,
    });
  }
  confirmOption(){
    const {handleRes} = this.props;
    const {radioVal} = this.state;
    handleRes&&handleRes({
      possible:Object.assign({},radioVal),
      radioVal:Object.assign({},radioVal),//不设置radioVal只有最近一次选中的值
    });
    this.setState({
      optionId:null,
    });
  }
  handleShowScale(item){
    const {showScaleFn,closeAssess} = this.props;
    //closeAssess&&closeAssess();    //关闭评估弹窗
    showScaleFn&&showScaleFn(item,true);
  }
  handleRadio(item,parent){
    let {result} = this.props;
    let radioVal = result&&result.radioVal;
    this.setState({
      radioVal:Object.assign({},radioVal,{[parent.conceptId]:item.detailName})
    })
  }
  handleReg(e){   //只能输入数字和特殊符号
    const key = e.key;
    if(key!='Backspace'&&((/[^\d|.\/%*~]/.test(key)))){
      preventDefault(e);
    }
  }
  handleInputformula(id,calcuContent,i,e) {
    const {calcuValues} = this.state;
    let obj = deepClone(calcuValues);
    let values = (obj&&obj[id])||deepClone(calcuContent);
    const txt = e.target.value;
    values[i].value = txt.replace(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g,'');       //处理中文输入法的情况
    obj[id] = values;
    if(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g.test(txt)){
      e.target.value = txt.replace(/[\u4e00-\u9fa5]|[^\d|.\/%*~]/g,'');
    }
    this.setState({
      isCalculated:false,
      calcuValues:obj
    });
  }
  handleForRadio(id,calcuContent,i,fidx){//计算公式
    const { calcuValues } = this.state;
    let obj = deepClone(calcuValues);
    let values = (obj&&obj[id])||deepClone(calcuContent);
    let details = values[i].details;
    for(let x=0;x<details.length;x++){
      if(x!=fidx){
        details[x].state=0;
      }else{
        details[x].state=1;
      }
    }
    obj[id] = values;
    this.setState({
      isCalculated:false,
      calcuValues:obj
    });
  }
  showFormula(id){
    this.setState({
      formulaId: id,
      optionId: ''
    });
  }
  closeFormula(){
    if(this.state.isCalculated){
      this.setState({
        formulaId:null,
      });
    }else{
      this.setState({
        formulaId:null,
        calcuValues:deepClone(this.props.calcuValues)
      });
    }
  }
  calcuFormula(item) { //计算公式计算
    const { calcuResult,handleCalcu } = this.props;
    const {formulaId,calcuValues} = this.state;
    let it=calcuValues&&calcuValues[formulaId];
    let allHasInfo = true;
    for (let i = 0; i < it.length; i++) {
      if(it[i].controlType == 2) {  //输入框类型的有没有填值
        if(!it[i].value) {
          allHasInfo = false
        }
      } else if(it[i].controlType == 0) {
        let hasSelect = false;
        for( let z = 0; z <it[i].details.length; z++) {
          if(it[i].details[z].state == 1) {
            hasSelect= true
          }
        }
        if(!hasSelect) {
          allHasInfo = false
        }
      }
    }
    item.content.details = calcuValues[formulaId];
    if(allHasInfo) { //所有都有值，则计算
      let results = deepClone(calcuResult);
      getFormulaResult({type:2,data:item}).then((res)=>{
        if(+res.data.code==0){
          const result = res.data.data.result;
          results[formulaId] = result;
          handleCalcu&&handleCalcu(calcuValues,results);
          this.setState({
            isCalculated:true
          });
        }else{
          Notify.error(res.data.msg||'计算没有结果返回');
        }
      })
    } else {  //不是所有值都填过了
      Notify.info('请填写计算公式内容')
    }
  }
  getDetailItems(item,i){
    let arr = [],temp='';
    const {indexs,result,formulaResult,disabled,calcuResult} = this.props;
    const {optionId,formulaId,radioVal,calcuValues} = this.state;
    const possible=result&&result.possible;

    item.details.map((its,j)=>{
      let it=its;
      if(indexs[i]&&indexs[i].includes(j)){
        if(its.type==1){     //量表
          let scaleRes=formulaResult&&formulaResult[it.content.conceptId]&&formulaResult[it.content.conceptId].calcalculate;
          const name = scaleRes&&scaleRes.result?(' 【'+it.content.name+'】 结果：'+scaleRes.result.value+" "+(scaleRes.result.text||'')):'【'+it.content.name+'】';
          temp =<span className={style['scale']}
                      title={name}
                      onClick={this.handleShowScale.bind(this,it.content)}>
                        {name}
                        </span>;
        }else if(its.type==2){      //计算公式
          const showRes = calcuResult&&calcuResult[item.conceptId]||it.content.result;
          const details = calcuValues&&calcuValues[item.conceptId]||it.content.details;
          const cresult = showRes&&showRes[1]&&showRes[1].text;
                    temp = <div className={style['results']}>
                    <span>计算公式结果：</span>
                    <span className={style["blue"]} style={disabled?{cursor:'default'}:''} onClick={disabled?'':this.showFormula.bind(this,item.conceptId,it)}>{cresult?cresult:'请选择'}</span>
                      {disabled?'':<img src={level1} />}
                      {disabled?'':<MiniToast title={it.content.name}
                               confirmText='关闭'
                               icon={allTableIcon}
                               show={formulaId&&formulaId==item.conceptId?true:false}
                               close={this.closeFormula}
                               confirm={this.closeFormula}
                               footer="true">
                      <table>
                        {details.map((item1,idd)=>{
                          if(item1.controlType==0){//单选
                            return <tr>
                              <td>
                                <span>{item1.isShow == '0' ? item1.name+'：' : '请选择'+item1.name+'：'}</span>
                              </td>
                              <td>
                              {Array.isArray(item1.details)&&item1.isShow == '0'&&item1.details.map((ii,ind)=>{
                                return ii.state == 1 && <div className={style["chooseItem"]}>
                                          {ii.detailName}
                                      </div>
                              })}
                              {Array.isArray(item1.details)&&item1.isShow != '0'&&item1.details.map((ii,ind)=>{
                                return <div className={style["chooseItem"]}>
                                        <Radio label={ii.detailName}
                                                  isSelect={ii.state == 1}
                                                  handleClick={this.handleForRadio.bind(this,item.conceptId,details,idd,ind)}>
                                          </Radio>
                                      </div>
                              })}          
                                

                               
                              </td>
                            </tr>
                          }else if(item1.controlType==2){//输入框
                            return <tr>
                              <td>
                                <span>{item1.isShow == '0' ? item1.name+'：':'请输入'+item1.name+'：'}</span>
                              </td>
                              <td>
                                {item1.isShow == '0' ? item1.value + ' ' +item1.uint : <input type="text" placeholder="请输入"  value={item1.value} onKeyDown={this.handleReg.bind(this)} onInput={(e)=>this.handleInputformula(item.conceptId,details,idd,e)}/>}
                              </td>
                              <td>
                                {item1.isShow != '0'&&<span>{item1.uint}</span>}  
                              </td>

                            </tr>
                          }
                        })}
                      </table>
                      <div className={style["forMulBtn"]} onClick={this.calcuFormula.bind(this,its)}>计算</div>
                      <table>
                        {showRes && Array.isArray(showRes) &&showRes.map((itemResult) => {
                          return <tr>
                            <td>
                              <span>{itemResult.name+'：'}</span>
                            </td>
                            <td>
                              <span>{itemResult.text}</span>
                            </td>
                          </tr>
                        })}
                      </table>
                    </MiniToast>}
                </div>
        }else if(its.type==3){
          temp = <div className={style['results']}>
                    <span>可能结果：</span>
                    <span onClick={disabled?'':this.showOption.bind(this,item.conceptId)} style={disabled?{cursor:'default'}:''} className={style["blue"]}>{possible&&possible[item.conceptId]?possible[item.conceptId]:'请选择'}</span>
                    {disabled?'':<img src={level1} />}
                    {disabled?'':<MiniToast title='结果选择'
                         icon={checkIcon}
                         show={optionId&&optionId==item.conceptId?true:false}
                         close={this.closeOption}
                         confirm={this.confirmOption.bind(this,item.conceptId)}
                         footer={true}>
                        <div className={style["infoOption"]}>
                          <span>{it.content.name?it.content.name+'：':''}</span>
                          {it.content.details&&it.content.details.map((lis,ind)=>{
                            return <div className={style["chooseItem"]}>
                              <Radio label={lis.detailName}
                                     isSelect={radioVal&&radioVal[item.conceptId]==lis.detailName}
                                     handleClick={this.handleRadio.bind(this,lis,item,i)}>
                              </Radio>
                              {lis.state==1?<span className={style['recomand']}>（智能推荐）</span>:''}
                            </div>
                          })}
                        </div>
                    </MiniToast>}
                  </div>;
        }
        const passId = item.details[j].type==1?item.details[j].content.conceptId:undefined;
        const li = disabled?<li>
            <span className={style['s-title']}>{item.name}：</span>
            <div className={style['row']}>{temp}</div>
          </li>:<li>
          <span className={style['s-title']}>{item.name}：</span>
          <div className={style['row']}>{temp}</div>
          <div className={style["recommend"]} onClick={this.props.handleRemove.bind(this,false,i,passId,j)}>
            <img className={style["deleteIconNo"]} src={deleteIconNo} />
            <img className={style["deleteIcon"]} src={deleteIcon} />
          </div>
        </li>;
        arr.push(li);
      }
    });
    return arr;
  }
  getItems(){
    const { data } = this.props;
    return data&&data.map((it,i)=>{
      return this.getDetailItems(it,i);
    });
  }
  getScaleContent(data){
    if(!data){
      return null;
    }
    const item = data&&data.find((it)=>{
      return it.type==1;
    });
    const content = JSON.parse(item.content||null);
    return {conceptId:item.conceptId,content,name:content.scaleName};
  }
  getScales(){
    const {scaleItems,disabled,formulaResult} = this.props;
    let li='',temp='',arr=[],it={};
    if(!scaleItems){
      return '';
    };
    for( let i in scaleItems){
      it = {conceptId:i,name:scaleItems[i].name};//this.getScaleContent(scaleItems[i].data);
      if(!it) continue;
      let scaleRes=formulaResult&&formulaResult[it.conceptId]&&formulaResult[it.conceptId].calcalculate;
      const name = scaleRes&&scaleRes.result?(' 【'+scaleItems[i].name+'】 结果：'+scaleRes.result.value+" "+(scaleRes.result.text||'')):'【'+scaleItems[i].name+'】';
      //这里onClick不能用箭头函数，用箭头函数会一直绑定for的最后一个it
      temp =<span className={style['scale']}
                  title={name}
                  onClick={this.handleShowScale.bind(this,it)}>{name}</span>;
      li = disabled?<li>
        <span className={style['s-title']}>相关量表：</span>
        <div className={style['row']}>{temp}</div>
      </li>:<li>
        <span className={style['s-title']}>相关量表：</span>
        <div className={style['row']}>{temp}</div>
        <div className={style["recommend"]} onClick={this.props.handleRemove.bind(this,true,it.conceptId)}>
          <img className={style["deleteIconNo"]} src={deleteIconNo} />
          <img className={style["deleteIcon"]} src={deleteIcon} />
        </div>
      </li>;
      arr.push(li);
    };
    return arr;
  }
  handleInput(e){
    const text = e.target.value;
    this.setState({
      text
    });
  }
  componentWillReceiveProps(next){        //修复bug1329,第二次保存值不显示
    if(next.text!=this.state.text){
      this.setState({
        text:next.text
      });
    this.$area.current.value=next.text;
    }
  }
  render() {
    const {title,handleInp,disabled} = this.props;
    return <div className={style['assess-item']}>
      <h2>{title}</h2>
      <div className={style['item-content']}>
        <ul>
          {
            this.getItems()
          }
          {
            this.getScales()
          }
          <li>
            <textarea className={style['edit-row']}
                      ref={this.$area}
                      type="text"
                      disabled={disabled}
                      placeholder='评估描述'
                      onBlur={()=>handleInp(this.state.text)}
                      onInput={this.handleInput.bind(this)}>{this.state.text}</textarea>
            <div className={style['textareaStatic']}>评估描述：{this.state.text}</div>
          </li>
        </ul>
      </div>
    </div>;
  }
}

export default ScaleItem;