import React from 'react';
import style from './index.less';
import { Radio,CheckBtn ,Notify} from '@commonComp';
 import Information from '../Information';
 import {getFormulaResult} from '@store/async-actions/fetchModules.js';
/**
*量表明细 @By_Liucf
*title: 量表标题/scaleName；
*tableId：量表id；
*scaleType:量表类型， 1-计分量表，接口算分；2-不计分量表，前端拼接结果；
*required：是否为必填项，1-必填，0-非必填；
*isSelect：必填项选中标识,true-表示该项下已有选中数据；
*select: 明细选中标识，1-选中，0-未选中；
*comfirnFlag：不计分量表父级确定事件标识，用于触发是否有必填项未填；
**/
class ScaleTable extends React.Component{
  constructor(props){
    super(props);
    this.state={
      selecteds:{},  //当前页面的选中标识，保存后使用select标识
      valueData:{},
      start:false,   //点击计算
      scaleResult1:null,
      result:{}
    }
    this.handleFormula = this.handleFormula.bind(this);
  }
  // 不计分选中事件
  handleRadio2(name,item,index){
    const {selecteds,valueData,result} = this.state;
    const selectName = item.detailName;
    const selectResult = item.result;
    // let newResult = Object.assign({},result,{[name]:selectName+'('+selectResult+')'});
    // 使用index，便于按顺序拼接结果
    let newResult = Object.assign({},result,{[index]:selectName+'('+selectResult+')'});
    this.setState({
      selecteds:Object.assign({},selecteds,{[name]:selectName}),
      result:newResult
    })
    const datas = JSON.parse(JSON.stringify(valueData));
    let rows = datas.rows;
    for(let i=0; i<rows.length; i++){
      if(rows[i].name==name){
        rows[i].isSelect = true;
        let details = rows[i].details;
        for(let k=0; k<details.length; k++){
          details[k].select = 0;
          if(details[k].detailName == selectName){
            details[k].select = 1;
          }
        }
      }
    }
    this.setState({
      valueData:datas
    })
  }
  
  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 rowsId = rows[j].indexId;
        if(rowsId==indexId){
          let row = rows[j].row;
          let required = rows[j].required; //必填
          let metux = rows[j].metux; //互斥
          if(required==1){ // 必填项处理
            for(let k=0;k < row.length; k++){
              row[k].isSelect = true;
              if(metux == 1){//互斥，把其他的清空
                let detList = row[k].details;
                for(let f=0; f<detList.length; f++){
                  detList[f].select = 0;
                }
              }
              if(row[k].name==name){
                details = row[k].details;
                // break;
              }
            }
          }else{
            for(let k=0;k < row.length; k++){
              if(metux == 1){//互斥，把其他的清空
                let detList = row[k].details;
                for(let f=0; f<detList.length; f++){
                  detList[f].select = 0;
                }
              }
              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 {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
    }
    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;
  }
  // 不计分结果
  getType2Reult(){
    const {result} = this.state;
    if(JSON.stringify(result) != '{}'){
      let data = '';
      for(let i in result){
        if(result[i]){
          data += result[i]+',';
        }
      }
      return data.slice(0,data.length-1);
    }
    return ''
  }
  componentWillReceiveProps(nextProps){
    const {tableId,closeTable,unscroeClose} = this.props;
    const {valueData} = this.state;
    const data = nextProps.scaleInfo;
    if(JSON.stringify(data) !== '{}' && data[tableId] && JSON.stringify(valueData) == '{}'){
      let scale = this.filterScale(data[tableId].data);
      this.setState({
        valueData:scale.content?JSON.parse(scale.content):{}
      })
    }
    if(nextProps.comfirnFlag){
      //非计分量表校验必填项
      if(valueData.scaleType==2){
        let unfinish;
        const rows = valueData.rows;
        for(let i=0; i<rows.length; i++){
          if(rows[i].required==1 && !rows[i].isSelect){//必填项未填
            unfinish = true;
          }
        }
        if(unfinish){
          Notify.info("请先将量表内容选择完整");
          return
        }
        unscroeClose();
      }else{
        closeTable();//计分量表关闭弹窗
      } 
    }
  }
  componentDidMount(){
    const {tableId,scaleInfo,resetFlag} = this.props;
    resetFlag&&resetFlag();//重置确定标识
    if(scaleInfo&&scaleInfo[tableId]){
      let scale = this.filterScale(scaleInfo[tableId].data);
      // 回读非计算量表结果result
      let data = scale.content?JSON.parse(scale.content):{};
      let result = {};
      if(data.scaleType==2){
        let rows = data.rows;
        for(let i=0; i<rows.length; i++){
          if(rows[i].isSelect){
            let details = rows[i].details;
            for(let j=0; j<details.length; j++){
              if(details[j].select==1){
                result[i] = details[j].detailName+'('+details[j].result+')'
              }
            }
          }else{
            result[i] = '';
          }
        }
      }
      this.setState({
        valueData:data,
        result:result
      }) 
    }  
  }
  componentWillUnmount(){
    // 储存计算结果和选择后的data
    const {title,tableId,getResult,scaleInfo,saveScaleData,formulaResult,comfirnFlag,flagT} = this.props;
    const {valueData,scaleResult1,start} = this.state;
    // 替换表格内容--1）没有点计算且没有计算结果；2）点了计算
    const scaleResult = scaleResult1 || formulaResult&&formulaResult[tableId]; //量表计算结果
    if(start || !scaleResult && valueData.scaleType==1){//仅计分量表储存
      let allDatas = scaleInfo[tableId]&&scaleInfo[tableId].data?[...scaleInfo[tableId].data]:'' ;
      if(allDatas){
        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,name:title});
      }
    }
     if(scaleResult1){
      const params = {
        type:1,
        data:scaleResult1,
        id:tableId,
      }
      getResult&&getResult(params);
    }
    // 非计分
    if(comfirnFlag && flagT){
      // 存值-拼成与计算接口返回的格式一致
      const data1 = {
        calcalculate:{
          result:{
            value:this.getType2Reult()
          }
        }
      }
      const params = {
        type:1,
        data:data1,
        id:tableId,
      }
      getResult&&getResult(params);
      // 存数据源
      let allDatas = scaleInfo[tableId]&&scaleInfo[tableId].data?[...scaleInfo[tableId].data]:'' ;
      if(allDatas){
        for(let i=0; i<allDatas.length; i++){
          if(allDatas[i].type==1){
            allDatas[i].content = JSON.stringify(valueData);
          }
        }
        saveScaleData&&saveScaleData({id:tableId,data:allDatas,name:title});
      }
    }
  }
  getContent(){ 
    let {selecteds,valueData,start,scaleResult1} = this.state;
    const {tableId,formulaResult,comfirnFlag} = this.props;
    const scaleResult = scaleResult1 || formulaResult&&formulaResult[tableId]; //量表计算结果
    // const datas = valueData&&valueData.group?valueData:'';
    // const datas = valueData;
    const datas = JSON.parse(JSON.stringify(valueData));
    let content;
    if(valueData&&valueData.scaleType==1){//计分
      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}
                                           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>
              })
    }else if(valueData&&valueData.scaleType==2){//不计分
      content =  datas&&datas.rows.map((item,i)=>{
        return <div className={style['block']} style={{border:item.required==1&&!item.isSelect&&comfirnFlag?'1px solid #f00':'none'}}>
            <p className={style['miniName']}>{item.name}</p>
            {item.details&&item.details.map((vv,ii)=>{
              return <div className={style['item']}>
                      <Radio label={vv.detailName+'('+vv.result+')'}
                         isSelect={vv.select==1||selecteds[item.name]==vv.detailName}
                         handleClick={this.handleRadio2.bind(this,item.name,vv,i)}>
                      </Radio>
                      {vv.state==1?<span className={style['recomand']}>（智能推荐）</span>:''}
                  </div>
            })}
            
          </div>
      })
    }

    return content;
  }

  render(){
    const {scaleInfo,tableId,formulaResult,resRef} = this.props;
    const data = scaleInfo[tableId].data;
    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 ref={resRef}>{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>:
                  (this.getType2Reult()||scaleResult&&scaleResult.calcalculate&&scaleResult.calcalculate.result&&scaleResult.calcalculate.result.value)?
                  <p className={style['totalR']}>{"结果："}{this.getType2Reult()||scaleResult&&scaleResult.calcalculate&&scaleResult.calcalculate.result&&scaleResult.calcalculate.result.value}</p>:''}
                </div>
              }
            })}
          </div>
  }
}
export default ScaleTable;