import React, { Component } from "react";
import style from "../index.less";
import deleteIcon from '@common/images/delete.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} from '@utils/tools';
/**
 * 来源于页面选择
 *
 * **/
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,
      formulaData:{},       //计算公式值
      isFormulaConfirm:false,
    };
    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
    })
  }
  closeOption(){
    this.setState({
      optionId:null
    })
  }
  confirmOption(){
    const {handleRes} = this.props;
    const {radioVal,possible} = this.state;
    handleRes&&handleRes({
      possible:Object.assign({},possible,radioVal),
      radioVal:Object.assign({},possible,radioVal),//不设置radioVal只有最近一次选中的值
    });
    this.closeOption();
  }
  handleShowScale(item,parentId){
    const {showScaleFn,closeAssess} = this.props;
    closeAssess&&closeAssess();    //关闭评估弹窗
    showScaleFn&&showScaleFn(item,parentId);        //显示量表

  }
  handleRadio(item,parent){
    let {result} = this.props;
    let radioVal = result&&result.radioVal;
    this.setState({
      radioVal:Object.assign({},radioVal,{[parent.id]:item.detailName})
    })
  }
  handleForRadio(id,idd, ind){
    const {formulaData} = this.state;
    const obj = JSON.parse(JSON.stringify(formulaData));
    const data = obj&&obj[id];
    if (data) {
      for(let z = 0; z <  data.content.details[idd].details.length; z++) {
        data.content.details[idd].details[z].state = 0;
      }
      data.content.details[idd].details[ind].state = 1;
    };
    this.setState({
      formulaData:obj
    });
  }
  showFormula(id,it){
    const {formulaData} = this.state;
    const obj = JSON.parse(JSON.stringify(formulaData)||{});
    if(!obj[id]){
      obj[id] = it;
    }
    this.setState({
      formulaId:id,
      formulaData:obj
    });
  }
  confirmFormula(){//计算公式确定
    this.setState({
      isFormulaConfirm:true,
      formulaId:null
    });
  }
  closeFormula(){
    this.setState({
      formulaId:null
    })
  }
  calcuFormula(j, v, ii) { //计算公式计算
    const { calcuFormula,chronicPushItems } = this.props;
    const {formulaId,formulaData} = this.state;
    const it =formulaData&&formulaData[formulaId];
    let pushObj = deepClone(chronicPushItems);
    pushObj[ii].details[j]=it;
    let allHasInfo = true
    for (let i = 0; i < it.content.details.length; i++) {
      if(it.content.details[i].controlType == 2) {  //输入框类型的有没有填值
        if(!it.content.details[i].value) {
          allHasInfo = false
        }
      } else if(it.content.details[i].controlType == 1) {
        let hasSelect = false
        for( let z = 0; z <it.content.details[i].details.length; z++) {
          if(it.content.details[i].details[z].state == 1) {
            hasSelect= true
          }
        }
        if(!hasSelect) {
          allHasInfo = false
        }
      }

    }
    if(allHasInfo) { //所有都有值，则计算
      // delete it.content.resultz
      let param = {
        type: 2,
        data: it,
        disId: v.id,
        pIndex: j,
        ppIndex: ii,
      }
      calcuFormula({param,chronicPushItems:pushObj})
    } else {  //不是所有值都填过了
      Notify.info('请填写计算公式内容')
    }
  }
  handleInputformula(id,idd,text) {
    const {formulaData} = this.state;
    const obj = deepClone(formulaData);
    const data = obj&&obj[id];
    if (data) {
      data.content.details[idd].value = text;
    }
    this.setState({
      formulaData:obj
    });
  }
  getDetailItems(item,i){
    let arr = [],temp='';
    const {indexs,result,formulaResult,calcuResult,disabled} = this.props;
    const {optionId,formulaId,radioVal,formulaData,isFormulaConfirm} = this.state;
    const possible=result&&result.possible;

    item.details.map((its,j)=>{
      if(indexs[i]&&indexs[i].includes(j)){
        let it=null;
        if(its.type==1){     //量表
          it=deepClone(its);
          let scaleRes=formulaResult&&formulaResult[it.content.id]&&formulaResult[it.content.id].calcalculate;

          temp =<span className={style['scale']}
                      onClick={()=>this.handleShowScale(it.content,item.id)}>
                        {scaleRes&&scaleRes.result?(' 【'+it.content.name+'】 结果：'+scaleRes.result.value+" "+scaleRes.result.text):'【'+it.content.name+'】'}
                        </span>;
        }else if(its.type==2){      //计算公式
          it=formulaData[formulaId]||deepClone(its);
          const showRes = calcuResult&&calcuResult[item.id]||it.content.result;
          const cresult = showRes&&showRes[1]&&showRes[1].text;
                    temp = <div className={style['results']}>
                    <span>计算公式结果：</span>
                    <span className={style["blue"]} onClick={this.showFormula.bind(this,item.id,it)}>{cresult?cresult:'请选择'}</span>
                    <img src={level1} />
                    <MiniToast title={it.content.name}
                               icon={allTableIcon}
                               show={formulaId&&formulaId==item.id?true:false}
                               close={this.closeFormula}
                               confirm={this.confirmFormula.bind(this,item,i)}
                               footer="true">
                      <table>
                        {it.content.details.map((item1,idd)=>{
                          if(item1.controlType==1){//单选
                            return <tr>
                              <td>
                                <span>{'请选择'+item1.name+'：'}</span>
                              </td>
                              <td>
                                {item1.details.map((ii,ind)=>{
                                  return <div className={style["chooseItem"]}>
                                    <Radio label={ii.detailName}
                                           isSelect={ii.state == 1}
                                           disabled={disabled}
                                           handleClick={this.handleForRadio.bind(this,item.id,idd, ind)}>
                                      >
                                    </Radio>
                                  </div>
                                })}
                              </td>
                            </tr>
                          }else if(item1.controlType==2){//输入框
                            return <tr>
                              <td>
                                <span>{'请输入'+item1.name+'：'}</span>
                              </td>
                              <td>
                                <input type="text" disabled={disabled} placeholder="请输入"  value={item1.value} onInput={(e)=>this.handleInputformula(item.id,idd,e.target.value)}/>
                              </td>
                              <td>
                                <span>{item1.uint}</span>
                              </td>

                            </tr>
                          }
                        })}
                      </table>
                      {disabled?"":<div className={style["forMulBtn"]} onClick={this.calcuFormula.bind(this,j, item, i)}>计算</div>}
                      <table>
                        {showRes && Array.isArray(showRes) &&showRes.map((itemResult, resultIndex) => {
                          return <tr>
                            <td>
                              <span>{itemResult.name+'：'}</span>
                            </td>
                            <td>
                              <span>{itemResult.text}</span>
                            </td>
                          </tr>
                        })}
                      </table>
                    </MiniToast>
                </div>
        }else if(its.type==3){
          it=deepClone(its);
          temp = <div className={style['results']}>
                    <span>可能结果：</span>
                    <span onClick={this.showOption.bind(this,item.id)} className={style["blue"]}>{possible&&possible[item.id]?possible[item.id]:'请选择'}</span>
                    <img src={level1} />
                    <MiniToast title='结果选择'
                         icon={checkIcon}
                         show={optionId&&optionId==item.id?true:false}
                         close={this.closeOption}
                         confirm={this.confirmOption.bind(this,item.id)}
                         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.id]==lis.detailName}
                                     handleClick={this.handleRadio.bind(this,lis,item,i)}>
                              </Radio>
                            </div>
                          })}
                        </div>
                    </MiniToast>
                  </div>;
        }
        const li = disabled?<li>
            <span>{item.name}：</span>
            <div className={style['row']}>{temp}</div>
          </li>:<li>
          <span>{item.name}：</span>
          <div className={style['row']}>{temp}</div>
          <div className={style["recommend"]} onClick={()=>this.props.handleRemove(i,j)}>
            <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);
    });
  }
  handleInput(e){
    const text = e.target.value;
    this.setState({
      text
    });
  }
  render() {
    const {title,handleInp,disabled,isRecommend,formulaResult} = this.props;
    return <div className={style['assess-item']}>
      {isRecommend?'':<h2>{title}</h2>}
      <div className={style['item-content']}>
        <ul>
          {
            this.getItems()
          }
          {isRecommend?'':<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;