import React ,{Component} from 'react';
import {connect} from 'react-redux';

import SpreadDrop from '@components/SpreadDrop';
import {SETSELECTED,CLEARSELECTED,CONFIRMSELECTED,SETOTHERCHECKBOX,CHANGEOTHERTEXTLABEL} from '@types/otherHistory';
import {RESET,SETDROPSHOW,HIDEDROP,CLICKCOUNT,ISREAD} from '@store/types/homePage.js';
import {getModules as fetchModules} from '@store/async-actions/fetchModules.js';
import {getCommSymptomPush} from '@store/async-actions/mainSuit.js'
import {GET_BIGDATAPUSH,MIX_CONFIRM,COMM_CONFIRM,CHANGE_LABELVAL} from '@store/types/mainSuit';
import {SETCHECKBOX,CHANGECHECKTEXTLABEL,CHECKCONFIRMSELECTED} from '@types/checkBody';
import {CURRENT_CONFIRM,SETMAINCHECKBOX,CURRENT_TEXT_LABEL,CURRENT_GET_BIGDATAPUSH} from '@types/currentIll';
import {getLabelIndex,fullfillText,getIds} from '@common/js/func.js';
import {billing} from '@store/async-actions/pushMessage';
import {Notify} from '@commonComp';
import {filterArr,didPushParamChange,filterDataArr} from '@utils/tools.js';
import config from '@config/index.js';

function mapStateToProps(state) {//console.log(state);
  return {
    mainSaveText:state.mainSuit.saveText,
    mainData:state.mainSuit.data,
  }
}


function getNames(data,order){//从exist withs 中获取name字段
  let nameData = "";
  if(+order===1){     //成文默认按点选顺序排序，指定textGenerate=1按从上到下从左到右排序
    data.sort(function(a,b){
      return a.listIndex-b.listIndex;
    });
  }
  data&&data.forEach((it,i)=>{
    nameData += it.name;
  });
  return nameData;
}

function addPoint(data,num){//给伴随添加顿号
  for(let i=num; i<data.length; i++){
    data[i].name = '、'+ data[i].name;
  }
  return data;
}

/***********************标签展开确定事件***************************/

// 主诉--不用展开标签
function mainSuitModule(dispatch,store,params){
  const {nones,exists,withs,exclusion,excluName,ban,mainSaveText,mainData} = params;
  let text = filterDataArr(mainSaveText);
  if(text.length >= config.limited){
    Notify.info(config.limitText);
    return
  }
  // 给主症状伴随添加exists字段
  if(exists.length>0){
    for(let k=0; k<exists.length; k++){
      exists[k].value=exists[k].name;
      exists[k].exist=1;
    }
  }
  if(withs.length>0){
    for(let n=0; n<withs.length; n++){
      withs[n].value=withs[n].name;
      withs[n].exist=2;
    }
  }
  // let existsName = getNames(exists);
  // let withsName = getNames(withs);
  const copExists = JSON.parse(JSON.stringify(exists));
  const copWiths = JSON.parse(JSON.stringify(withs)); 
  let banName = ban.name;
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  let num = 0;
  let existNum = 0;
  let forwardId;
  let mainText;
  for(let n=ikey-1; n>0; n--){
    if(mainData[n].flag && mainData[n].flag==1){
      forwardId = n;
      continue;
    }
  }
  
  if(forwardId){
    mainText = mainSaveText.slice(forwardId,ikey);
    const mainSlice = mainData.slice(forwardId,ikey);
    let banIndex = mainText.indexOf('伴'); 
    if(banIndex==-1){
      num = 1;
    }
    // ikey前的data里没有exist=1的数据，则existNum=1
    if(exists.length>0){
      for(let i=0; i<mainSlice.length; i++){
        if(!mainSlice[i].exist && mainSlice[i].exist!==1){
          existNum = 1;
          continue;
        }
      }
    }
    
  }else{
    let banIndex = mainSaveText.indexOf("伴");
    if(banIndex==-1){
      num = 1;
    }
  }
  let withsName = getNames(addPoint(copWiths,num));
  let existsName = getNames(addPoint(copExists,existNum));
  let names;
  if(banName){
    names = existsName + banName + withsName;
  }else{
    names = existsName + withsName;
  } 
  // num==0 说明有“伴”，减1;
  let lengths = num==0?text.length + names.length - 1:text.length + names.length;
  // console.log(5656,num,existNum,text,text.length,names,lengths);
  if(lengths > config.limited){
    Notify.info(config.limitText);
    return
  }
  // const index = params.ikey;
  // let ikey = getLabelIndex(index);
  dispatch({
    type: MIX_CONFIRM,
    data: {exists:exists,withs:withs,withsName:withsName,existsName:existsName,ikey,ban}
  });
  dispatch({    //自由文本标签数据更新
    type:ISREAD
  });
  dispatch({//隐藏下拉
    type:HIDEDROP
  })
}


// 现病史
function currentIll(dispatch,store,params){
  const {nones,exists,withs,exclusion,excluName,ban,noneIds} = params;
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  let existsId = exists && exists.length>0?getIds(exists):[];
  let withsId = withs && withs.length>0?getIds(withs):[];
  const ids = (existsId.concat(withsId)).join(",");
  let has = [],wes=[];
  //获取选中项目模板
  fetchModules(ids).then((res)=>{
    if(+res.data.code===0){
      const list = res.data.data;
      // if(list&&list.length>0){
      if(list&&JSON.stringify(list) !== '{}'){
        existsId.map((i)=>{
          // has.push(...list[i].questionMapping);
          has.push(list[i]);
        });
        withsId.map((i)=>{
          // wes.push(...list[i].questionMapping);
          wes.push(list[i]);
        });
        dispatch({
          type: CURRENT_CONFIRM,
          data: {exists:has,withs:wes,nones:nones,ikey,ban,noneIds}
        });
      }else{
        dispatch({
          type: CURRENT_CONFIRM,
          data: {exists,withs,nones,ikey,ban,noneIds}
        });
      }
      dispatch({    //自由文本标签数据更新
        type:ISREAD
      });
    }else{
      console.log(res);
    }
  });

}


//其他史多选标签确定事件
function otherHisConfirm(dispatch,store,params){
  const {nones,exists,withs,exclusion,excluName,copyType} = params;
  // const ikey = params.ikey.substr(1,1);
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  if(params.exclusion){
    dispatch({
      type: CONFIRMSELECTED,
      data:{exclusion,excluName,ikey,copyType}
    });
    return ;
  }
  let existsId = getIds(exists);
  let withsId = getIds(withs);
  const ids = existsId.length>0?existsId.join(",")+','+withsId.join(","):withsId.join(",");
  if(!ids&&nones){      //只有无的项目
    dispatch({
      type: CONFIRMSELECTED,
      data: {exists:[],withs:[],nones:nones,ikey,copyType}
    });
    dispatch({
      type:ISREAD
    });
    return;
  }
  // const ids = exists.join(",")+withs.join(",");
  let has = [],wes=[];
  //获取选中项目模板
  fetchModules(ids).then((res)=>{
    if(+res.data.code===0){
      const list = res.data.data;
      existsId.map((i)=>{
        has.push(...list[i].questionMapping);
      });
      withsId.map((i)=>{
        wes.push(...list[i].questionMapping);
      });
      dispatch({
        type: CONFIRMSELECTED,
        data: {exists:fullfillText(has,false,true).newArr,withs:fullfillText(wes,false,true).newArr,nones:nones,ikey,copyType}
      });
      dispatch({
        type:ISREAD
      });
    }
  });
}

function checkBodyConfirm(dispatch,store,params){
  const {nones,exists,withs,exclusion,excluName,copyType} = params;
  // const ikey = params.ikey.substr(1,1);
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  if(params.exclusion){
    dispatch({
      type: CHECKCONFIRMSELECTED,
      data:{exclusion,excluName,ikey,copyType}
    });
    return ;
  }
  let existsId = getIds(exists);
  let withsId = getIds(withs);
  const ids = existsId.join(",")+','+withsId.join(",");
  if(!ids&&nones){      //只有无的项目
    dispatch({
      type: CHECKCONFIRMSELECTED,
      data: {exists:[],withs:[],nones:nones,ikey,copyType}
    });
    dispatch({
      type:ISREAD
    });
    return;
  }
  // const ids = exists.join(",")+withs.join(",");
  let has = [],wes=[];
  //获取选中项目模板
  fetchModules(ids).then((res)=>{
    if(+res.data.code===0){
      const list = res.data.data;
      existsId.map((i)=>{
        has.push(...list[i].questionMapping);
      });
      withsId.map((i)=>{
        wes.push(...list[i].questionMapping);
      });
      dispatch({
        type: CHECKCONFIRMSELECTED,
        data: {exists:fullfillText(has,false,false).newArr,withs:fullfillText(wes,false,false).newArr,nones:nones,ikey,copyType}
      });
      dispatch({
        type:ISREAD
      });
    }
  });
}

//在不同模块（主诉、现病史等）下拉选中调用不同事件
function handleModuleDiff(dispatch,store,params){
  const {type,mainSaveText} = params;
  switch (+type){
    case 1:
      /*let text = filterDataArr(mainSaveText);
      if(text.length >= config.limited){
        Notify.info(config.limitText);
        return
      }*/
      mainSuitModule(dispatch,store,params);
      break;
    case 2:
      currentIll(dispatch,store,params);
      break;
    case 3:
      otherHisConfirm(dispatch,store,params);
      break;
    case 4:
      checkBodyConfirm(dispatch,store,params);
      break;
    default:
  }
}


/*****************普通多选框确定事件**************************/

//主诉普通多选确定
function mainSuitCheck(dispatch,store,params){
  const {nones,exists,withs,order,mainSaveText,value,ikey} = params;
  let existsName = getNames(exists,order);
  let withsName = getNames(withs);
  let labelInx = getLabelIndex(ikey);
  let text = filterDataArr(mainSaveText);
  /*if(text.length >= config.limited){
    Notify.info(config.limitText);
    return
  }*/
  // let lengths = text.length + existsName.length;
  let lengths = value?(text.length - value.length + existsName.length):(text.length + existsName.length);
  if(lengths > config.limited){
    Notify.info(config.limitText);
    return
  }
  // const index = params.ikey;
  // let ikey = getLabelIndex(index);
  dispatch({
    type: COMM_CONFIRM,
    // data: {exists:exists,existsName:existsName,ikey}
    data:Object.assign({},params,{existsName,withsName,labelInx})
  });
  dispatch({//隐藏下拉
    type:HIDEDROP
  })
}

//现病史普通多选确定
function currentCheck(dispatch,store,params){
  const {ikey,exclusion,excluName,nones,exists,noneIds,noneOn,nowOn,withOn,withs,order} = params;
  let existsName = getNames(exists,order);
  let withsName = getNames(withs);
  let labelInx = getLabelIndex(ikey);
  dispatch({
    type:SETMAINCHECKBOX,
    // data:{labelInx,ikey,exclusion,excluName,nones,exists,existsName,noneIds,noneOn,nowOn,withOn,withs,withsName}
    data:Object.assign({},params,{existsName,withsName,labelInx})
  })
}


//查体普通多选确定
function checkBodyCheck(dispatch,store,params){
  const {ikey,exclusion,excluName,nones,exists,noneIds,noneOn,nowOn,withOn,withs,order} = params;
  let existsName = getNames(exists,order);
  let withsName = getNames(withs);
  let labelInx = getLabelIndex(ikey);
  dispatch({
    type:SETCHECKBOX,
    // data:{labelInx,ikey,exclusion,excluName,nones,exists,existsName,noneIds,noneOn,nowOn,withOn,withs,withsName}
    data:Object.assign({},params,{existsName,withsName,labelInx})
  })
}
//其他史普通多选确定
function otherHisCheck(dispatch,store,params){
  const {ikey,exclusion,excluName,nones,exists,noneIds,noneOn,nowOn,withOn,withs,order} = params;
  let existsName = getNames(exists,order);
  let withsName = getNames(withs);
  let labelInx = getLabelIndex(ikey);
  dispatch({
    type:SETOTHERCHECKBOX,
    // data:{labelInx,ikey,exclusion,excluName,nones,exists,existsName,noneIds,noneOn,nowOn,withOn,withs,withsName}
    data:Object.assign({},params,{existsName,withsName,labelInx})
  })
}

function handleCheckBox(dispatch,store,params){
  const {type,mainSaveText} = params;
  switch (+type){
    case 1:
      /*let text = filterDataArr(mainSaveText);
      if(text.length >= config.limited){
        Notify.info(config.limitText);
        return
      }*/
      mainSuitCheck(dispatch,store,params);
      break;
    case 2:
      currentCheck(dispatch,store,params);
      break;
    case 3:
      otherHisCheck(dispatch,store,params);
      break;
    case 4:
      checkBodyCheck(dispatch,store,params);
      break;
    default:
  }
}

/**************标签双击输入**************/
//主诉
function mainSuitLabelEdit(dispatch,params){
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  dispatch({
    type:CHANGE_LABELVAL,
    data:{changeVal:params.changeVal,ikey:ikey}
  })
}

//现病史
function currentLabelEdit(dispatch,params){
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  dispatch({
    type:CURRENT_TEXT_LABEL,
    data:{changeVal:params.changeVal,ikey:ikey}
  })
}

//其他史
function otherHisLabelEdit(dispatch,params){
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  dispatch({
    type:CHANGEOTHERTEXTLABEL,
    data:{changeVal:params.changeVal,ikey:ikey}
  })
}

//查体
function checkBodyLabelEdit(dispatch,params){
  const index = params.ikey;
  let ikey = getLabelIndex(index);
  const {changeVal} = params;
  dispatch({
    type:CHANGECHECKTEXTLABEL,
    data:{totalVal:changeVal,ikey:ikey,changeVal}
  })
}

function handleLabel(dispatch,params){
  const {type} = params;
  switch (+type){
    case 1:
      mainSuitLabelEdit(dispatch,params);
      break;
    case 2:
      currentLabelEdit(dispatch,params);
      break;
    case 3:
      otherHisLabelEdit(dispatch,params);
      break;
    case 4:
      checkBodyLabelEdit(dispatch,params);
      break;
    default:
  }
  dispatch(billing());
  dispatch({
    type:ISREAD
  })
}

function mapDispatchToProps(dispatch,store){
  return {
    handleConfirm(obj){
      if(obj.tagType == 6||obj.tagType == 11){//铺开
        handleModuleDiff(dispatch,store,obj);
      }else if(obj.tagType == 2){//普通多选
        handleCheckBox(dispatch,store,obj);
      }
      //右侧推送
      setTimeout(function(){      //延迟待确定后的数据更新后推送，避免获取的参数还是旧的
        if(didPushParamChange()){     //操作后内容有变化才推送
          dispatch(billing());
        }
      },500);
    },
    handleHide(){
      dispatch({
        type: HIDEDROP
      });
    },
    async handleShow(obj){
      // 埋点dispatch
      dispatch({
        type:CLICKCOUNT,
        data:obj,
        clickType:'单击',
        num:1
      });
      // 调大数据接口
      if(obj.tagType ==11 ){
        const bigData = await getCommSymptomPush();
        let result = bigData.data;
        if(+result.code == 0){
          // let pushDataList = result.data.symptom;
          let bigDataList = result.data.symptom;
          let pushDataList = [];
          if(bigDataList&&bigDataList.length>0){//剔除没有id
            pushDataList = bigDataList.filter(function(item){
              return item.id
            });
          }else{
            pushDataList = bigDataList;
          }
          /*if(pushDataList.length > 0){
            if(obj.type == 1){// 主诉--添加症状
              dispatch({
                type:GET_BIGDATAPUSH,
                data:pushDataList,
                info:obj
              })
            }else if(obj.type == 2){// 现病史--添加其他症状
              dispatch({
                type:CURRENT_GET_BIGDATAPUSH,
                data:pushDataList,
                info:obj
              })
            }
          }else{
            Notify.info("暂无推送");
            // return
          }*/
          //推送无数据显示空下拉并提示暂无推送--1.9/1.18
          if(!pushDataList || pushDataList.length == 0){Notify.info("暂无推送");}
          if(obj.type == 1){// 主诉--添加症状
              dispatch({
                type:GET_BIGDATAPUSH,
                data:pushDataList,
                info:obj
              })
            }else if(obj.type == 2){// 现病史--添加其他症状
              dispatch({
                type:CURRENT_GET_BIGDATAPUSH,
                data:pushDataList,
                info:obj
              })
            }
        }else{
          console.log(result.msg);
          Notify.info("暂无推送");
          // 接口请求失败，不往下执行显示下拉
          return
        }
      }
      dispatch({
        type:SETDROPSHOW,
        data:obj
      });
      dispatch({
        type: RESET
      });
    },
    handleDbclick(obj){//双击统计
      dispatch({
        type:CLICKCOUNT,
        data:obj,
        clickType:'双击',
        num:1
      });
    },
    handleLabelChange(obj){//标签内输入
      handleLabel(dispatch,obj);
    }
  }
}

const SpreadDropCont = connect(
  mapStateToProps,
  mapDispatchToProps
)(SpreadDrop);

export default SpreadDropCont;