import React from 'react';
import style from './index.less';
// import mocks from '../../mock/chronicTable.js'
import { Radio,CheckBtn ,Notify} from '@commonComp';
 import Information from '../Information';
 import {deepClone} from '@utils/tools.js';
 import {getFormulaResult} from '@store/async-actions/fetchModules.js';
/**
*量表 具体信息页面
*title:量表标题/scaleName
*data:量表内容:scaleName量表标题，calculate量表计算结果，group分组，
*
*
**/
class ScaleTable extends React.Component{
  constructor(props){
    super(props);
    this.state={
      selecteds:{},  //当前页面的选中标识，保存后使用select标识
      valueData:{},
      start:false,   //点击计算
      scaleResult1:null
    }
    this.handleFormula = this.handleFormula.bind(this);
  }
  
  handleRadio(groupName,name,item,indexId){
    const {selecteds,valueData} = this.state;
    const value = item.detailName;
    this.setState({
      selecteds:Object.assign({},selecteds,{[name]:value})
    })
    const datas = JSON.parse(JSON.stringify(valueData));
    const group = datas.group;
    let rows;
    let details;
    for(let i=0; i<group.length; i++){
      if(group[i].groupName==groupName){
        rows = group[i].rows;
        break;
      }
    }
    if(rows){
      for(let j=0; j<rows.length; j++){
        let row = rows[j].row;
        let required = rows[j].required;
        let rowsId = rows[j].indexId;
        // 必填项处理
        if(required==1&&rowsId==indexId){
          for(let k=0;k < row.length; k++){
            row[k].isSelect = true;
            if(row[k].name==name){
              details = row[k].details;
              // break;
            }
          }
        }else{
          for(let k=0;k < row.length; k++){
            if(row[k].name==name){
              details = row[k].details;
              row[k].isSelect = true;
              break;
            }
          }
        }
        
      }
    }
    if(details){
      for(let n=0; n<details.length; n++){
        details[n].select = 0;
        if(details[n].detailName==value){
          details[n].select = 1;
        }
      }
    }
    this.setState({
      valueData:datas
    })
  }
  
  handleCheckbox(groupName,name,item){
    let {selecteds,valueData} = this.state;
    const value = item.detailName;
    selecteds[name]?selecteds[name]:selecteds[name]=[];
    const index = selecteds[name].findIndex((i)=>i==value);
    if(index!=-1){
      selecteds[name].splice(index,1);
    }else{
      selecteds[name].push(value);
    }
    this.setState({
      selecteds:selecteds
    });

    const datas = JSON.parse(JSON.stringify(valueData));
    const group = datas.group;
    let rows;
    let details;
    for(let i=0; i<group.length; i++){
      if(group[i].groupName==groupName){
        rows = group[i].rows;
        break;
      }
    }
    if(rows){
      for(let j=0; j<rows.length; j++){
        let row = rows[j].row;
        for(let k=0;k < row.length; k++){
          if(row[k].name==name){
            details = row[k].details;
            row[k].isSelect = true;
            break;
          }
        }
      }
    }
    if(details){
      for(let n=0; n<details.length; n++){
        if(details[n].detailName==value){
          if(!details[n].select || details[n].select==0){
            details[n].select = 1;
          }else{
            details[n].select = 0;
          }
        }
      }
    }
    this.setState({
      valueData:datas
    })
  }

  handleFormula(data){//得分计算
    const {tableId,parentId,scaleInfo,parentIndex} = this.props; 
    const {valueData} = this.state; 
    this.setState({
      start:true
    })
    // 遍历是否有必填项未填的情况 filter:required==1 && !isSelect
    const group = valueData.group;
    let unfinish;
    for(let i=0; i<group.length; i++){
      let rows = group[i].rows;
      for(let j=0; j<rows.length; j++){
        // if(rows[j].required==1&& (rows[j].row.filter((it,i)=>{return !it.isSelect})).length>0){
        // 必填项下有一项选中既可
        if(rows[j].required==1&& (rows[j].row.filter((it,i)=>{return it.isSelect})).length==0){
          unfinish = true;
          break;
        }
      }
    }
    if(unfinish){
      Notify.info("请先将量表内容选择完整");
      return
    }
    // 将计算结果存在state，防止页面跳动问题
    const params = {
      type:1,
      data:valueData,
      pId:parentId,
      id:tableId,
      pIndex:parentIndex
    }
    const that = this;
    getFormulaResult(params).then((res)=>{
      if(+res.data.code==0){
        that.setState({
          scaleResult1:res.data.data
        })
      }else{
        Notify.error(res.data.msg||'计算没有结果返回');
      }
    })
  }
  filterScale(data){//type=1为表格内容
    let scale = {};
    for(let i=0; i<data.length; i++){
      if(data[i].type==1){
        scale = data[i];
      }
    }
    return scale;
  }
  componentWillReceiveProps(nextProps){ 
    const {tableId} = this.props;
    const data = nextProps.scaleInfo;
    if(JSON.stringify(data) !== '{}' && data[tableId]){
      let scale = this.filterScale(data[tableId]);
      this.setState({
        // valueData:JSON.parse(nextProps.scaleInfo[tableId][1].content),
        valueData:scale.content?JSON.parse(scale.content):{}
      })
    }
  }
  componentDidMount(){
    const {tableId,scaleInfo} = this.props;
    if(scaleInfo&&scaleInfo[tableId]){
      let scale = this.filterScale(scaleInfo[tableId]);
      this.setState({
        // valueData:JSON.parse(scaleInfo[tableId][1].content)
        valueData:scale.content?JSON.parse(scale.content):{}
      })
    }  
  }
  componentWillUnmount(){
    // 储存计算结果和选择后的data
    const {tableId,getResult,parentId,parentIndex,scaleInfo,saveScaleData} = this.props; 
    const {valueData,scaleResult1} = this.state; 
    // 替换表格内容
    let allDatas = scaleInfo[tableId]?JSON.parse(JSON.stringify(scaleInfo[tableId])):'' ;
    if(allDatas){
      // allDatas[1].content = JSON.stringify(valueData);
      for(let i=0; i<allDatas.length; i++){
        if(allDatas[i].type==1){
          allDatas[i].content = JSON.stringify(valueData);
        }
      }
      // 需求：未点计算，直接点确定、关闭也保存选中数据 4-30
      saveScaleData&&saveScaleData({id:tableId,data:allDatas});
    }
    
     if(scaleResult1){
      const params = {
        type:1,
        data:scaleResult1,
        id:tableId,
        pIndex:parentIndex
      }
      getResult&&getResult(params);
     }  
  }
  getContent(){ 
    let {selecteds,valueData,start,scaleResult1} = this.state;
    const {tableId,formulaResult} = this.props;
    const scaleResult = scaleResult1 || formulaResult&&formulaResult[tableId]; //量表计算结果
    const datas = valueData&&valueData.group?valueData:'';//console.log(666,datas);
    let content =  datas&&datas.group&&datas.group.map((v,i)=>{
                return <div className={style['group']}>
                  <p className={style['groupName']}>{v.groupName}</p>
                  {v.rows&&v.rows.map((it,ind)=>{
                    return <div className={style['rows']}>
                        {it.required==1&&it.row.length>1?<span className={style['tip']}>本组选项可多选或根据需要选择某一条选项</span>:''}
                      {it.row.map((item,index)=>{
                        if(item.controlType==0){
                          return <div className={style['block']} style={{border:it.required==1&&!item.isSelect&&start?'1px solid #f00':'none'}}>
                              {/*<p className={style['miniName']}>{item.name}</p>*/}
                              <p className={style['miniName']}> 
                                <i>{index==0?it.indexId + '.':''}</i> 
                                {item.name}
                              </p>
                              {item.details&&item.details.map((vv,ii)=>{
                                return <div className={style['item']}>
                                        <Radio label={vv.detailName+'('+vv.score+')'}
                                           isSelect={vv.select==1||selecteds[item.name]==vv.detailName}
                                           handleClick={this.handleRadio.bind(this,v.groupName,item.name,vv,it.indexId)}>
                                        </Radio>
                                        {vv.state==1?<span className={style['recomand']}>（智能推荐）</span>:''}
                                    </div>
                              })}
                              
                            </div>
                          }else{
                            return <div className={style['block']}>
                                <p className={style['miniName']}>{item.name}</p>
                                  {item.details&&item.details.map((vv,ii)=>{
                                    return <div className={style['item']}>
                                    <CheckBtn value={vv.detailName}
                                                    label={vv.detailName}
                                                    isSelect={vv.select==1||selecteds[item.name]&&selecteds[item.name].includes(vv.detailName)}
                                                    handleClick={this.handleCheckbox.bind(this,v.groupName,item.name,vv)}>
                                          </CheckBtn>
                                    {vv.state==1?<span className={style['recomand']}>（智能推荐）</span>:''}
                                    </div>
                                  })}
                            </div>
                          }
                        
                      })}
                    </div>
                  })}
                  {v.groupCalculate.isShow==1?<p className={style['subTotal']}>
                    <span>计分：</span>
                    {/*<span>{v.groupCalculate.result.value}</span>*/}
                    <span>{scaleResult&&scaleResult.group.map((m,ii)=>{
                      if(m.groupName==v.groupName){
                        return m.groupCalculate.result.value;
                      }
                    })}</span>
                  </p>:''}  
                </div>
              })
    return content;
  }

  render(){
    const {title,scaleInfo,tableId,formulaResult} = this.props;
    const data = scaleInfo[tableId];
    let {selecteds,scaleResult1} = this.state;
    const scale = data && this.filterScale(data);
    const datas = scale && scale.content && JSON.parse(scale.content);
    const scaleResult = scaleResult1 || formulaResult&&formulaResult[tableId]; //量表计算结果
    return <div className={style['tableBox']} id="printcontent">
            <div className={style['printShow']}>
              <Information></Information>
            </div> 
            <h1>{datas?datas.scaleName:''}</h1>
            {data && data.map((v,i)=>{
              if(v.type==0){
                return <div dangerouslySetInnerHTML={{__html:v.content}} className={style['textlh']}></div>
              }else{
                return <div className={style['textContent']}>
                  {this.getContent()}
                  {datas&&datas.Calc==1?<div className={style['total']}>
                    <span>总分：</span>
                    <span>{scaleResult&&scaleResult.calcalculate&&scaleResult.calcalculate.result&&scaleResult.calcalculate.result.value +' '+ (scaleResult.calcalculate.result.text?scaleResult.calcalculate.result.text:'')}</span>
                    <span className={style['totalBtn']} onClick={this.handleFormula}>得分</span>
                  </div>:''}
                </div>
              }
            })}
          </div>
  }
}
export default ScaleTable;