import {getLabelIndex,fullfillText,getIds} from '@common/js/func.js';
import config from '@config/index.js';
import {formatContinueDots} from '@utils/tools';

//插入病程变化模板
function insertPro(data,processModule){
  let index;
  for(let i=0; i<data.length; i++){
    if(data[i].flag && data[i].flag==3 ){
      index = i;
    }
  }
  for(let j=0; j<processModule.length; j++){
    let pos = index + j;
    data.splice(pos,0,processModule[j]);
  }
  return data;
}

//设置模板
export const setModule = (state,action)=>{
  const res = Object.assign({},state);
  // 处理tagType=4的类型
  const originalData = action.data||[];
  const originalSonData = action.processModule||[];
  let spreadLabels=[];
  let sonSpreadLabels=[];//子模板
  if(originalData&&originalData.length>0){
    for(let i=0; i<originalData.length;i++){
      if(originalData[i].tagType==4){
        spreadLabels.push(...originalData[i].questionMapping);
      }else{
        spreadLabels.push(originalData[i]);
      }
    }
  }
  if(originalSonData&&originalSonData.length>0){
    for(let j=0; j<originalSonData.length;j++){
      if(originalSonData[j].tagType==4){
        sonSpreadLabels.push(...originalSonData[j].questionMapping);
      }else{
        sonSpreadLabels.push(originalSonData[j]);
      }
    }
  }
  
  // res.moduleData = action.data;
  // res.processModule = action.processModule;//病程变化模板
  res.moduleData = spreadLabels;
  res.processModule = sonSpreadLabels;//病程变化模板
  res.emptyData = action.emptyData;//空模板
  let data = action.data;
  let sliceIdx;
  data&&data.map((v,i)=>{
    if(v.flag && v.flag==2){
      sliceIdx = i;
    }
  })
  res.addModule = data&&data.slice(0,sliceIdx+1);//截取到flag=2 有无治疗
  res.update=Math.random();
  return res;
}

//插入病程变化
export const insertProcess = (state,action)=>{
  const res = Object.assign({},state);
  const sonId = action.id;//子模板id
  // const processModule = JSON.parse(JSON.stringify(res.processModule));
  let addSmoduleData;
  // let allModules = JSON.parse(localStorage.getItem('modules'));
  let allModules = action.allModules;
  for(let k=0; k<allModules.length; k++){
    if(allModules[k].id==sonId){
      addSmoduleData = JSON.parse(JSON.stringify(allModules[k].moduleDetailDTOList));
    }
  }
  let data = res.data;
  let newData = insertPro(data,addSmoduleData);
  res.data = fullfillText(newData).newArr;
  res.saveText = fullfillText(res.data).saveText;
  res.update=Math.random();
  return res;

}


function addPos(data,num){
  let newData = JSON.parse(JSON.stringify(data));
  newData.forEach((it,i)=>{
    it.pos = num;
  })
  return newData;
}

//慢病填充模板
export const fillChronicModule = (state,action)=>{
  let res = Object.assign({},state);
  let moduleData = JSON.parse(JSON.stringify(res.moduleData));//现病史模板
  res.data = fullfillText(moduleData).newArr;
  res.saveText = fullfillText(res.data).saveText;
  res.update=Math.random();
  return res;
}

//聚焦时设置 现病史模板
export const setData = (state,action) =>{
  let res = Object.assign({},state);
  res.editClear = false;
  const mainIds = action.info.mainIds;
  res.symptomIds = JSON.parse(JSON.stringify(mainIds));
  const num = action.info.num;//点击了几次添加病情变化
  const symptomFeature = action.info.symptomFeature;//分词
  const isChronic = action.info.isChronic;//慢病标识
  let useEmpty,mainData;
  let mainModleData = JSON.parse(JSON.stringify(action.info.mainData));//主诉模板数据
  let moduleData = JSON.parse(JSON.stringify(res.moduleData));//现病史模板
  let current = JSON.parse(JSON.stringify(moduleData));
  let newMain = [];
  let mainLabelModule = res.mainLabelModule;//主诉选中的症状id获取到的尾巴
  let mainLabelModuleArr = [];
  if(mainLabelModule){
    let keyArr = Object.keys(mainLabelModule);
    for(let i=0; i<keyArr.length; i++){
      mainLabelModuleArr.push(mainLabelModule[JSON.parse(keyArr[i])]);
    }
  }
 
  // 是否使用空模板：num=0时判断mainIds，num>=1，截取第一病程遍历是否有症状exist
  if(num==0){
    useEmpty = mainIds.length>0 ? false:true;
    mainData = mainModleData;
  }else{
    // 模板也分词时得加上分词结果的判断
    let sliceIdx;
    for(let j=0; j<mainModleData.length; j++){
      // if(mainModleData[j].id==config.tongYId && mainModleData[j].pos==1){
      if(mainModleData[j].pos==1){
        sliceIdx = j;
        break;
      }
    }
    mainData = mainModleData.slice(0,sliceIdx);//截取第一病程
    let existData = mainData.filter((item)=>{
      return item.exist;
    })
    useEmpty = existData&&existData.length>0?false:true;
  }
  
  if (useEmpty) {
    const data = res.emptyData?JSON.parse(JSON.stringify(res.emptyData)):[];
    res.data = fullfillText(data).newArr;
  } else {
    if(mainData&&mainData.length>0){//主诉使用模板
      // 目前只需要将第一个主诉病程移植到现病史
      let tongYong = "";
      let main = [];//主症状
      let withs = [];//伴随
      let firstT = 0;
      mainData.map((v,i)=>{
        // 主诉通用症状描述
        if(v.id==config.tongYId && v.value && !v.pos){tongYong = v.value;}
        if(v.exist){v.exist==1?main.push(v):withs.push(v)}
        // 时间单位
        if(v.controlType==5&&v.value){
          firstT++;
          current.map((it,ii)=>{
            if(it.id==v.id&& firstT==1){it.value=v.value}
          })
        } 
      })
      
      // 主症状添加tongYong标签选中文字
      let mainCopy = JSON.parse(JSON.stringify(main));
      let manInput = [];
      // 去掉主诉添加的顿号 
      mainCopy.map((ele,ind)=>{
        if(tongYong){
          ele.name = tongYong + (ele.name).replace('、',"");
          ele.value = tongYong + (ele.value).replace('、',"");
        }else{
          ele.name = (ele.name).replace('、',"");
          ele.value = (ele.value).replace('、',"");
        }
        //查询是否有手动输入--输入的内容放到最后（3-27）
        if(ele.name != ele.value){
          const inputText = ele.value.replace(ele.name,"");
          const textObj = Object.assign({},JSON.parse(config.textLabel),{name:inputText});
          if(config.textReg.test(inputText)){//包含中英文或数字->即不全是标点符号才插入
             manInput.push(textObj);
          }
          ele.value = ele.name;
        }
      })

       // 将ids接口获取到的模板匹配到对应主症状后面
      // 主症状
      let newMainCopy = JSON.parse(JSON.stringify(mainCopy));
      let ind = 0;
      let insertInd = 0;
      // let preLength = 0;
      let lengArr=[];
      for(let k=0; k <mainCopy.length;k++){
          mainLabelModuleArr.map((v,i)=>{
            if(mainCopy[k].id==v.id){
              ind++;
              let items = v.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==1;
                            })          
              lengArr[k] = items.length;  //每一个主诉尾巴长度 
              
              if(items.length==0){//没有尾巴时给症状后加逗号(3.5)
                for(let j=0; j<newMainCopy.length; j++){
                  if(newMainCopy[j].id==mainCopy[k].id){
                    newMainCopy[j].value = newMainCopy[j].name = (mainCopy[k].value||mainCopy[k].name)+'，';
                  }
                }
              } 
              if(ind>1){
                insertInd += lengArr[k-1];
              }
              newMainCopy.splice(k+insertInd+1,0,...items);
            }
        })
      }
      // 伴随
      // 去掉顿号
      let newWiths = [];
      let manWithInput = [];
      if(withs.length>0){
        for(let b=0; b<withs.length; b++){
          withs[b].name = withs[b].name.replace('、',"");
          withs[b].value = withs[b].value.replace('、',"");
          if(withs[b].name != withs[b].value){
            const inputText = withs[b].value.replace(withs[b].name,"");
            const textObj = Object.assign({},JSON.parse(config.textLabel),{name:inputText});
            if(config.textReg.test(inputText)){//包含中英文或数字->即不全是标点符号才插入
              manWithInput.push(textObj);
            }           
            withs[b].value = withs[b].name;  
          }
        }
        newWiths = JSON.parse(JSON.stringify(withs));
        let withInd = 0;
        let withInsertInd = 0;
        let withLengArr=[];
        for(let d=0; d <withs.length;d++){
          mainLabelModuleArr.map((v,i)=>{
            if(withs[d].id==v.id){
              withInd++;
              let items = v.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==2;
                            })
              withLengArr[d] = items.length;
              if(items.length==0){//没有尾巴时给症状后加逗号(3.5)
                for(let j=0; j<newWiths.length; j++){
                  if(newWiths[j].id==withs[d].id){
                    newWiths[j].value = newWiths[j].name = (withs[d].value||withs[d].name)+'，';
                  }
                }
              }
              if(withInd>1){
                withInsertInd += withLengArr[d-1];
              }
              newWiths.splice(d+withInsertInd+1,0,...items);
            }
          })
        }
      }
      
      let symptomArr = newMainCopy.concat(manInput,newWiths,manWithInput);
      let newSymptomArr = formatContinueDots(JSON.parse(JSON.stringify(symptomArr)));   //过滤连续标点
      //组装好的主症状和伴随症状插入现病史模板(flag=4前)--现病史是否有模板
      if(moduleData&&moduleData.length>0){
        let insertIdx = null;
        for(let j=0; j<current.length; j++){
          if(current[j].flag && current[j].flag==4){
            insertIdx = j;  
          }
        }
        for(let k=0; k<newSymptomArr.length; k++){
          let pos = insertIdx+k;
          current.splice(pos,0,newSymptomArr[k]);
        }
      }else{//现病史没有模板
        current = newSymptomArr;
      }
      let currentData = JSON.parse(JSON.stringify(current));
      res.data = fullfillText(currentData).newArr;
    }else{//分词
      if(symptomFeature&&symptomFeature.length>0){
        let featureData = JSON.parse(JSON.stringify(symptomFeature));
        let ind = 0;
        let insertInd = 0;
        let lengArr=[];
        for(let k=0; k <symptomFeature.length;k++){        
          mainLabelModuleArr.map((v,i)=>{
            if(symptomFeature[k].id==v.id){
              ind++;
              let items = v.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==1;
                            })          
              lengArr[k] = items.length;  //每一个主诉尾巴长度 
              
              if(items.length==0){//没有尾巴时给症状后加逗号(3.5)
                for(let j=0; j<featureData.length; j++){
                  if(featureData[j].id==symptomFeature[k].id){
                    featureData[j].value = featureData[j].name = symptomFeature[k].value||symptomFeature[k].name+'，';
                  }
                }
              }
              if(ind>1){
                insertInd += lengArr[k-1];
              }
              featureData.splice(k+insertInd+1,0,...items);
            }
          })
        }
        //组装好的主症状和伴随症状插入现病史模板(flag=4前)
        let endFeatureData = JSON.parse(JSON.stringify(featureData));
        if(moduleData&&moduleData.length>0){
          let insertIdx = null;
          for(let j=0; j<current.length; j++){
            if(current[j].flag && current[j].flag==4){
              insertIdx = j;  
            }
          }
          for(let k=0; k<endFeatureData.length; k++){
            let pos = insertIdx+k;
            current.splice(pos,0,endFeatureData[k]);
          }
        }else{//现病史没有模板
          current = endFeatureData;
        }
        let currentData = JSON.parse(JSON.stringify(current));
        res.data = fullfillText(currentData).newArr;
      }
    }
  }
  let resData = JSON.parse(JSON.stringify(res.data));
  res.saveText = fullfillText(resData).saveText;
  res.update=Math.random();
  return res;
}

function getLabel(lid,lname){
  return {id:lid,name:lname,value:lname,tagType:config.tagType}
}

// 多选展开确定事件--主、伴、无
export const confirm = (state,action) =>{
  let res = Object.assign({},state);
  let length1 = res.data.length;
  let arr = JSON.parse(JSON.stringify(res.data));
  const {nones,exists,withs,ikey,exclusion,excluName,ban,noneIds} = action.data;
  let existsId = exists && exists.length>0?getIds(exists):[];
  let withsId = withs && withs.length>0?getIds(withs):[];
  res.symptomIds = res.symptomIds.concat(existsId,withsId,noneIds);//搜索去重
  // 伴 标签
  const banText = JSON.stringify(ban)=='{}'?'':{id:ban.id,name:ban.name,value:ban.name,tagType:config.tagType};

  // 处理主症状标签及尾巴展开symptomType=1
  if(exists && exists.length>0){
    // for(let i in exists){//ie8不支持for in循环
     for(let i=0;i<exists.length; i++){
      arr.splice(ikey,0,getLabel(exists[i].id,exists[i].questionMapping && exists[i].questionMapping.length==0?exists[i].name+'，':exists[i].name),...(exists[i].questionMapping && exists[i].questionMapping.filter((item)=>{return item.symptomType==0||item.symptomType==1;})));
    }
  }

  let length = arr.length - length1;
  let withsArr = JSON.parse(JSON.stringify(arr));
  // 伴 伴随症状标签及尾巴展开symptomType=2
  if(withs && withs.length>0){
    // for(let i in withs){
    for(let i=0;i<withs.length; i++){
      withsArr.splice(parseInt(ikey)+length,0,banText,getLabel(withs[i].id,withs[i].questionMapping && withs[i].questionMapping.length==0?(withs[i].name+'，'):(withs[i].name)),...(withs[i].questionMapping&&withs[i].questionMapping.length>0?withs[i].questionMapping.filter((item)=>{return item.symptomType==0||item.symptomType==2;}):[]));
      /*withsArr.splice(parseInt(ikey)+length,0,getLabel(withs[i].id,withs[i].questionMapping && withs[i].questionMapping.length==0?(ban.name+withs[i].name+'，'):(ban.name+withs[i].name)),...(withs[i].questionMapping && withs[i].questionMapping.filter((item)=>{return item.symptomType==0||item.symptomType==2;})));*/
    }
  }

  // 无 不用展开
  let lengthN = withsArr.length - length1;
  let noneArr = JSON.parse(JSON.stringify(withsArr));  
  if(nones.length>1){//只点无不上去
    const nonesName = nones.slice(0,nones.length-1)+'，';
    const noneObj = Object.assign({},JSON.parse(config.textLabel),{name:nonesName,value:nonesName});
    const none = nones?noneObj:'';
    noneArr.splice(parseInt(ikey)+lengthN,0,none);
  }

  let resData = JSON.parse(JSON.stringify(noneArr));
  // res.data = resData;
  res.data = fullfillText(resData).newArr;
  res.saveText = fullfillText(resData).saveText;
  res.update=Math.random();
  return res;
};


//普通多选确定事件-主诉通用特征、初为后为等
export const setCheckBox = (state,action)=>{
  const res = Object.assign({},state);
  const {labelInx,excluName,existsName,nones,withsName,ban} = action.data;
  // 若每个选项都有符号，去掉最后一个，因与标签间的符号有冲突
  let showText = (excluName||'')+(existsName||'')+(ban.name||'')+(withsName||'')+(nones&&nones.replace('、','')||'');
  let pattern = new RegExp(/\,+$|\，+$|\.+$|\。+$|\、+$/);//+ 一次或多次
  if(pattern.test(showText)){
    showText = showText.substr(0,showText.length-1);
  }
  res.data[labelInx].value = showText;
  res.saveText[labelInx] = showText;
  res.selecteds[labelInx] = action.data;
  res.update=Math.random();
  return res;
}


//数字键盘选中事件
export function setNumberValue(state,action){
  let res = Object.assign({},state);
  const param = action.params;
  const index = param.ikey;
  let labelInx = getLabelIndex(index);
  const subInx = index.substr(index.length-1);
  let item = res.data[labelInx];
  // if(param.text.trim()){
    if(+item.tagType===1){
      item.value = param.text;
      res.saveText[labelInx] = param.text?item.labelPrefix+param.text+item.labelSuffix:'';
    }else{
      item.questionMapping[subInx].value = param.text;
      let hasValue = false;
      const sub = item.questionMapping.map((it)=>{
        if(it.value){     //至少有一个子值才黑显
          hasValue = true;
        }
        return (it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||'');
      });
      // res.saveText[labelInx] = sub.join(',');
      res.saveText[labelInx] = hasValue?sub.join(''):'';
      item.value = sub.join('');
    }
  /*}else{//删除完标签内容则删除该标签
    res.data.splice(labelInx,1);
    res.saveText = fullfillText(res.data).saveText;
  }*/
  res.update = Math.random();
  return res;
}

//单选下拉选中
export function setRadioValue(state,action){
  let res = Object.assign({},state);
  const {ikey,id,text} = action;
  let labelInx = getLabelIndex(ikey);
  const subInx = ikey.substr(ikey.length-1);
  let item = res.data[labelInx];
  if(typeof text != 'string'){    //需要展开项--有无治疗类型
    const len = +item.copyType === 0?1:0;
    res.data.splice(labelInx,len,text);
    return res;
  }
  if(+item.tagType===1){
    item.value = text;
    res.saveText[labelInx] = item.labelPrefix+text+item.labelSuffix;
    const exist = JSON.parse(localStorage.getItem('radio'+item.id)||null);
    if(exist){    //选中状态处理
      exist[0].selected=exist[0].id==id;
      localStorage.setItem('radio'+item.id,JSON.stringify(exist));
    }
    item.questionDetailList.map((its)=>{
      if(its.id === id){
        its.selected = true;
      }else{
        its.selected = false;
      }
    });
  }else{
    item.questionMapping[subInx].value = text;
    /*if(item.questionMapping[subInx].controlType==1){//例如：有无治疗-未经治疗
      item.value = text;
    }else{
      item.questionMapping[subInx].value = text;
    }*/
    let hasValue = false;
    const sub = item.questionMapping.map((it)=>{
      //添加选中状态
      it.questionDetailList.map((its)=>{
        if(its.id === id){
          its.selected = true;
        }else{
          its.selected = false;
        }
      });

      if(it.value){     //至少有一个子值才黑显
        hasValue = true;
      }
      return (it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||'');
    });
    res.saveText[labelInx] = hasValue?sub.join(''):'';
  }
  res.update = Math.random();
  return res;
}
//单选带输入值保存
export const setRadioInputValue = (state,action)=>{
  const res = Object.assign({},state);
  const {ikey,values,id} = action.data;
  let index = getLabelIndex(ikey);
  let innerInx = ikey.substr(ikey.length-1);
  let item = res.data[index];
  if(item.tagType!=1){      //在组合项中
    item = res.data[index].questionMapping[innerInx];
  }
  let str='',temp='',obj=item.questionDetailList;
  if(!values){    //清空
    let sld=obj.find((item)=>{
      return item.selected==true;
    });
    sld?sld.selected=false:'';
    item.vals = null;
    item.value = '';
    if(res.data[index].tagType!=1){
      let hasValue = false;
      const sub = res.data[index].questionMapping.map((it)=>{
        if(it.value){     //至少有一个子值才黑显
          hasValue = true;
        }
        return (it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||'');
      });
      res.saveText[index] = hasValue?sub.join(''):'';
    }else{
      res.saveText[index] = '';
    }
    res.update = Math.random();
    return res;
  }
  for(let i in values){
    temp = values[i];
    if(typeof temp=='object'){
      str+=temp.value;
    }else{
      str+=temp;
    }
  }
  //选中状态
  if(id){
    obj.map((its)=>{
      if(its.id === id){
        its.selected = true;
      }else{
        its.selected = false;
      }
    });
  }
  item.vals = values;
  item.value = str;
  if(res.data[index].tagType!=1){
    let hasValue = false;
    const sub = res.data[index].questionMapping.map((it)=>{
      return (it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||'');
    });
    res.saveText[index] = sub.join('');
  }else {
    res.saveText[ikey] = str;
  }
  res.update = Math.random();
  return res;
}

//双击标签输入改变值
export const changeLabelVal = (state,action)=>{
  const res = Object.assign({},state);
  const {changeVal,totalVal,ikey,prefix,suffix} = action.data;
  const index = ikey;
  const newVal = changeVal;
  let labText = totalVal?totalVal:newVal;
  let item = res.data[index];
  const next = res.data[+index+1];
  const nextVal = next.value||next.name;
  //标签后是不是标点符号标签,是的话删除本标签时一起删除
  let nextIsDot = +next.tagType===8&&!nextVal.match(config.punctuationReg);
  if(labText.trim()){
    if(item){
      item.value = newVal;
      const canAdd=hasNoSame(item.questionDetailList,labText);
      //单选双击编辑的内容自动加到下拉选项中,双击编辑但未修改不添加
      if(canAdd&&+item.tagType===1&&(+item.controlType===1||+item.controlType===0)){
        const li = {
          id:-Math.floor(Math.random()*1000),
          name:labText,
          questionId:item.id,
          orderNo:0,
          code:0,
          defaultSelect:"0",
          remark:null,
          abnormal:0,
          selected:true
        };

        const exist = JSON.parse(localStorage.getItem('radio'+item.id)||null);
        //console.log(exist)
        if(exist&&typeof exist=='object'){     //已添加过编辑的数据
          //exist.push(li);
          exist[0]=li;        //暂限添1条
          localStorage.setItem('radio'+item.id,JSON.stringify(exist));
        }else{
          localStorage.setItem('radio'+item.id,JSON.stringify([li]));
        }
        //取消原选中状态
        const seld = item.questionDetailList.find((it)=>it.selected==true);
        if(seld){
          seld.selected=false;
        }
      }
      item.labelPrefix = prefix||'';
      item.labelSuffix = suffix||'';
      res.saveText[index] = labText;
    }
  }else{//删除完标签内容则删除该标签
    const num = nextIsDot?2:1;
    res.data.splice(index,num);
    res.saveText.splice(index,num);
    // res.saveText = fullfillText(res.data).saveText;
  } 
  res.update = Math.random();
  return res;
}

function hasNoSame(arr,text){
  return arr.findIndex((it)=>text==it.name)==-1;
}
// 数字键盘较特殊，有直接输入
export const changeNumLabelVal = (state,action)=>{
  const res = Object.assign({},state);
  const {changeVal,totalVal,ikey,prefix,suffix} = action.data;
  const index = ikey;
  const newVal = changeVal;
  let item = res.data[index];
  const next = res.data[+index+1];
  const nextVal = next.value||next.name;
  //标签后是不是标点符号标签,是的话删除本标签时一起删除
  let nextIsDot = +next.tagType===8&&!nextVal.match(config.punctuationReg);
  let labText = totalVal?totalVal:newVal;   //如单选没有前后缀
  if(labText.trim()){
    if(item){
      item.value = newVal;
      item.labelPrefix = prefix||'';
      item.labelSuffix = suffix||'';
    }
    res.saveText[index] = labText;
  }else{//删除完标签内容则删除该标签
    const num = nextIsDot?2:1;
    res.data.splice(index,num);
    res.saveText.splice(index,num);
    // res.saveText = fullfillText(res.data).saveText;
  }
  res.update = Math.random();
  return res;
}

export const clearCurrentIll = (state,action)=>{
  const res = Object.assign({},state);
  res.data = action.data;
  res.saveText = action.saveText;
  res.selecteds = action.selecteds?action.selecteds:[];
  res.symptomIds = action.symptomIds;
  res.symptomIds = action.symptomIds;
  if(action.editClear){
    res.editClear = action.editClear;
  }
  if(res.data.length>0){
    res.editClear = false;
  }
  res.update = Math.random();
  return res;
}
//文本模式下值保存
export const setTextModeValue = (state,action)=>{
  const res = Object.assign({},state);
  res.saveText[0] = action.text;
  return res;
};


//获取大数据推送症状
export const bigDataSymptom = (state,action) => {
  const res = Object.assign({},state);
  res.bigDataSymptom = action.data;//推送数据
  let inlineDatas = res.data;
  const index = action.info.ikey;
  let labelInx = getLabelIndex(index);
  // 添加症状 暂时剔除没有id、questionMapping字段的数据
  let pushDataList = action.data;
  /*let pushDataList = action.data.filter(function(item){
    return item.id
  });*/
  let dataList = inlineDatas[labelInx].questionMapping;
  for(let k=0; k<dataList.length; k++){
    if(dataList[k].controlType == 99){
      dataList[k].questionDetailList = pushDataList;
    }
  }
  res.update = Math.random();
  return res;
}


//自由文本
export function setCheckText(state,action) {
  let res = Object.assign({},state);
  const {i,text} = action;
  if(res.data[i]){
    res.data[i].value=text;
    //res.data[i].name='';      //默认显示的文字
  }
  res.saveText[i] = text;
  res.update = Math.random();
  return res;
}


//搜索 插入标签数据
export function insertLabelData(state,action){
  let res = Object.assign({},state); 
  const {index,data,isReplace,span}=action;
  let id = data.id;
  let searchData = action.name;
  // res.symptomIds.push(id);
  const text = Object.assign(JSON.parse(config.textLabel),{name:searchData},{id:id});
  const textEmpty = Object.assign({},JSON.parse(config.textLabel));
  let focusIndex = res.focusIndex;
  let saveText = res.saveText;
  let banIdx = saveText.indexOf("伴");
  //伴随展开数据-过滤了连续标点
  const FilteredDotMapping2=formatContinueDots(data.questionMapping.filter((item)=>{
    return item.symptomType==0||item.symptomType==2;
  }));
  //主症状展开数据-过滤连续了标点
  const FilteredDotMapping1=formatContinueDots(data.questionMapping.filter((item)=>{
    return item.symptomType==0||item.symptomType==1;
  }));
  if(isReplace){
    span.current.innerText?(span.current.innerText = ''):(span.current.innerHTML = '');
    // res.data.splice(focusIndex,1,text,data);
    // 搜索结果展开伴随symptomType==2的尾巴

    let resData = JSON.parse(JSON.stringify(res.data));
    resData.splice(focusIndex,1,text,...(FilteredDotMapping2));
    res.data = fullfillText(resData).newArr;
    res.saveText = fullfillText(res.data).saveText;
  }else{
    let resData;
    const searchStr = res.searchStr;
    let innerText = span.current.innerText || span.current.innerHTML;
    let strIndex = innerText.indexOf(searchStr);
    const value = innerText.replace(searchStr,"");
    const pText = Object.assign({},textEmpty,{value:value});
    if(data.itemType==0){//症状
      res.symptomIds.push(id);
      // 没有伴展开主诉symptomType=0/1的尾巴，有伴一>第一个点选上去的伴为依据，伴前展开主诉，伴后展开伴随；多余的伴以及手动输入的伴不做处理（2-25）
      if(banIdx==-1){

        // if(strIndex <= 1){//前
        if(strIndex < 1){//前
          res.data.splice(index,1,text,...(FilteredDotMapping1),pText);
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,null,...new Array(FilteredDotMapping1.length).fill(null),null);
        }else{
          res.data.splice(index,1,pText,text,...(FilteredDotMapping1));
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,null,null,...new Array(FilteredDotMapping1.length).fill(null));
        }
      }else{
        if(focusIndex > banIdx){//伴后
          if(strIndex < 1){//前
            res.data.splice(index,1,text,...(FilteredDotMapping2),pText);
            res.saveText = fullfillText(res.data).saveText;
            res.selecteds.splice(index,1,null,...new Array(FilteredDotMapping2.length).fill(null),null);
          }else{
            res.data.splice(index,1,pText,text,...(FilteredDotMapping2));
            res.saveText = fullfillText(res.data).saveText;
            res.selecteds.splice(index,1,null,null,...new Array(FilteredDotMapping2.length).fill(null));
          }
        }else{//伴前
          if(strIndex < 1){//前
            res.data.splice(index,1,text,...(FilteredDotMapping1),pText);
            res.saveText = fullfillText(res.data).saveText;
            res.selecteds.splice(index,1,null,...new Array(FilteredDotMapping1.length).fill(null),null);
          }else{
            res.data.splice(index,1,pText,text,...(FilteredDotMapping1));
            res.saveText = fullfillText(res.data).saveText;
            res.selecteds.splice(index,1,null,null,...new Array(FilteredDotMapping1.length).fill(null));
          }
        }
      }
      res.data = fullfillText(res.data).newArr;
      res.saveText = fullfillText(res.data).saveText;
    }else{//标签
      const arr=fullfillText(data.questionMapping).newArr;      //过滤连续标点
      const spreadLabels = data.tagType==4?formatContinueDots(arr):[data];
      if(strIndex < 1){//前
        // 判断前一个是否为文本标签，是直接插入标签，不是则在前面插入一个空文本标签
        const preItem = res.data[index-1];
        if(preItem&&preItem.tagType==8){
          res.data.splice(index,1,...spreadLabels,pText);
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,...new Array(spreadLabels.length).fill(null),null);
        }else{
          res.data.splice(index,1,textEmpty,...spreadLabels,pText);
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,null,...new Array(spreadLabels.length).fill(null),null);
        }
        // res.data.splice(focusIndex,0,data,textEmpty);
        
      }else{
        // 后面插入 ：判断后一个标签是否为文本标签，不是则插入一个空标签
        const afterItem = res.data[index+1];
        if(afterItem&&afterItem.tagType==8){
          res.data.splice(index,1,pText,...spreadLabels);
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,null,...new Array(spreadLabels.length).fill(null));
        }else{
          res.data.splice(index,1,pText,...spreadLabels,textEmpty);
          res.saveText = fullfillText(res.data).saveText;
          res.selecteds.splice(index,1,null,...new Array(spreadLabels.length).fill(null),null);
        }   
      }
    }
  }
  res.searchData = [];    //选中清空搜索内容（即关闭搜索弹窗）
  res.update = Math.random();//console.log('现病史',res);
  return res;
}

export const clearCurrentEdit = (state,action)=>{
    const res = Object.assign({},state);
    res.editClear = action.editClear
    return res;
  }
//复制标签（如血压）事件
export function addLabelItem(state,action){
  let res = Object.assign({},state);
  const {data,i} = action;
  const textLabel = Object.assign({},JSON.parse(config._textLabel),{showInCheck:JSON.parse(data).showInCheck});
  //使用Object.assign({},data)拷贝操作时复制项和原项会同步修改
  if(!data) return res;
  res.data.splice(+i+2,0,JSON.parse(data),textLabel);
  res.saveText.splice(+i+2,0,'','');
  res.selecteds.splice(+i+2,0,null,null);
  res.update = Math.random();
  return res;
}

//文本输入标签
export function setInputLabel(state,action){
  let res = Object.assign({},state);
  const {i,text,prefix,suffix,subIndex} = action;
  const item = res.data[i];
  if(+item.tagType===3){      //multSpred标签
    item.questionMapping[subIndex].value = text;
    let texts = item.questionMapping.map((it)=>{
      return it.value?(it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||''):'';
    });
    res.saveText[i] = texts.join('');
    res.update = Math.random();
    return res;
  }else{
    if(item){
      item.value=text;
    }
  }
  res.saveText[i] = prefix+text+suffix;
  res.update = Math.random();
  return res;
}

// backspace删除
export function backspaceText(state,action){
  let res = Object.assign({},state);
  const {delIndex,text} = action;
  const data = res.data;
  // if(data[delIndex-1].tagType==8 ||data[delIndex-1].flag&&data[delIndex-1].flag==3){
  // 前一个是文本标签或者子模板，只改变值
  if(data[delIndex-1].flag&&data[delIndex-1].flag==3){//子模板不删  
    // data[delIndex].value = text;
  }else if(data[delIndex-1].tagType==8){
    data.splice(delIndex,1);
    res.selecteds.splice(delIndex,1);      //杂音类样式选中状态对应
    res.saveText.splice(delIndex,1);
  }
  else{
    data.splice(delIndex-1,2);
    res.selecteds.splice(delIndex-1,2);      //杂音类样式选中状态对应
    res.saveText.splice(delIndex-1,2);
  }
  // res.saveText = fullfillText(data).saveText;
  res.update = Math.random();
  return res;
}

//删除后移除id
export function removeId(state,action){
  let res = Object.assign({},state);
  const {index,text} = action;
  const data = res.data;
  const id = data[index].id;
  let ids = res.symptomIds;
  if(ids.includes(id)){
    ids.splice(ids.indexOf(id),1);
  }
  if(!data[index].value && data[index-1].tagType==8){
    data.splice(index,1);
    res.saveText.splice(index,1);
  }else{
    data[index].id = "";
    data[index].name = text;
    data[index].value = text;
  }
  res.update = Math.random();
  return res;
}

// 单列多选
export function multipleComfirn(state,action){
  let res = Object.assign({},state);
  const {ikey,seleData,fullIkey} = action.data;
  let data = res.data;
  let index = fullIkey.substr(fullIkey.length-1,1);
  if(data[ikey].tagType==3){    //在组合项中
    let item = data[ikey].questionMapping;
    let arr=[];
    item[index].value = seleData;
    item.map((it)=>{
      if(it.value){
        arr.push(it.labelPrefix+it.value+it.labelSuffix);
      }
    });
    res.saveText[ikey] = arr.join("");
    res.update = Math.random();
    res.selecteds[ikey] = {[index]:action.data};
    return res;
  }
  data[ikey].value = seleData;
  res.saveText[ikey] = seleData;
  res.selecteds[ikey] = action.data;
  return res;
}


export function delSingleLable(state,action){
  let res = Object.assign({},state);
  const {index} = action;
  let data = res.data;
  // 前一个不是文本标签 并且不是子模板，则删除
  if(data[index-1].flag&&data[index-1].flag==3){

  }
  else if(data[index-1].tagType != 8){
    data.splice(index-1,1);
    res.saveText.splice(index-1,1);
  }
  res.update = Math.random();
  return res;
}