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

//插入病程变化模板
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);
  res.moduleData = action.data;
  res.processModule = action.processModule;//病程变化模板
  res.processModuleName = action.processModuleName;//模板名称
  res.emptyData = action.emptyData;//空模板
  let data = action.data;
  let sliceIdx;
  data.map((v,i)=>{
    if(v.flag && v.flag==2){
      sliceIdx = i;
    }
  })
  res.addModule = data.slice(0,sliceIdx+1);//截取到flag=2 有无治疗
  res.update=Math.random();
  return res;
}

//插入病程变化
export const insertProcess = (state,action)=>{
  const res = Object.assign({},state);
  const processModule = res.processModule;
  let data = res.data;
  res.data = insertPro(data,processModule);
  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 setData = (state,action) =>{
  let res = Object.assign({},state);
  res.editClear = false;
  res.symptomIds = JSON.parse(JSON.stringify(action.info.mainIds));
  const useEmpty = action.info.useEmpty;
  const num = action.info.num;//点击了几次添加病情变化
  let mainData = JSON.parse(JSON.stringify(action.info.mainData));//主诉模板数据
  let moduleData = JSON.parse(JSON.stringify(res.moduleData));//现病史模板
  let addModule = JSON.parse(JSON.stringify(res.addModule));//拷贝的模板
  let current = JSON.parse(JSON.stringify(moduleData));
  let newMain = [];
  let mainLabelModule = res.mainLabelModule;//主诉选中的症状id获取到的模板
  let objToArr = [];
  for(let m in mainLabelModule){
    objToArr.push(mainLabelModule[m]);
  }
  // 过滤掉没有mapping的数据
  let mainLabelModuleArr = objToArr.filter((item)=>{
    return item.questionMapping.length>0;
  })
  
  if (useEmpty) {
    res.data = res.emptyData;
  } else {
    // 目前只需要将第一个主诉病程移植到现病史
    let tongYong = "";
    let main = [];//主症状
    let withs = [];//伴随
    for(let i=0; i<mainData.length; i++){
        if(mainData[i].id==config.tongYId && !mainData[i].pos){//第一个通用特征描述
          if(mainData[i].value){
            tongYong = mainData[i].value;
          }
        }       
        else if(mainData[i].exist){
          mainData[i].exist==1?main.push(mainData[i]):withs.push(mainData[i])
        }
        
        // 处理时间和主诉通用症状--现病史模板无“主诉通用症状” 1-7
        for(let j=0; j<current.length; j++){
          if(mainData[i].id==current[j].id && mainData[i].controlType==5){//处理时间，避免手动输入的值
            if(mainData[i].value){
              current[j] = {id:mainData[i].id,name:mainData[i].value,value:mainData[i].value,tagType:config.tagType}
            }
          }  
        }
      }
      
      // 主症状添加tongYong标签选中文字
      let tongYText = tongYong?{name:tongYong,value:tongYong,tagType:config.tagType}:'';
      let mainCopy = JSON.parse(JSON.stringify(main));
      if(tongYText){
        /*for(let j=0; j<main.length; j++){
          mainCopy.splice(j*2,0,tongYText);
        }*/
        for(let j=0; j<mainCopy.length; j++){
          mainCopy[j].name = tongYong + mainCopy[j].name;
          mainCopy[j].value = tongYong + mainCopy[j].value;
        }
      }

       // 将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++;
              // newMainCopy.splice(k+1,0,...v.questionMapping);
              let items = v.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==1;
                            })  
              lengArr[k] = items.length;  //每一个主诉尾巴长度        
              /*if(ind==1){
                preLength = items.length;
              }else{
                insertInd += preLength;
              }*/
              if(ind>1){
                insertInd += lengArr[k-1];
              }
              newMainCopy.splice(k+insertInd+1,0,...items);
            }
        })
      }
      // 伴随
      let newWiths = JSON.parse(JSON.stringify(withs));
      if(withs.length>0){
        let withInd = 0;
        let withInsertInd = 0;
        let withPreLength = 0;
        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;
                            })
              if(withInd==1){
                withPreLength = items.length;
              }else{
                withInsertInd += withPreLength;
              }
              newWiths.splice(d+withInsertInd+1,0,...items);
            }
          })
        }
      }
      
      let symptomArr = newMainCopy.concat(newWiths);
      let newSymptomArr = JSON.parse(JSON.stringify(symptomArr));  
      //组装好的主症状和伴随症状插入现病史模板(flag=4前)
      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]);
      }
      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 = getIds(exists);
  let withsId = 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.length>0){
    for(let i in exists){
      arr.splice(ikey,0,getLabel(exists[i].id,exists[i].questionMapping.length==0?exists[i].name+'，':exists[i].name),...(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.length>0){
    for(let i in withs){
      // withsArr.splice(parseInt(ikey)+length,0,banText,getLabel(withs[i].id,withs[i].name),...(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.length==0?(ban.name+withs[i].name+'，'):(ban.name+withs[i].name)),...(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 {exists,labelInx,existsName} = action.data;
  let arr = res.data;
  arr[labelInx].value = existsName;
  res.saveText[labelInx] = existsName;
  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(+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] = hasValue?sub.join(''):'';
  }
  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;
    item.questionDetailList.map((its)=>{
      if(its.id === id){
        its.selected = true;
      }else{
        its.selected = false;
      }
    });
  }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 changeLabelVal = (state,action)=>{
  const res = Object.assign({},state);
  const index = action.data.ikey;
  const newVal = action.data.changeVal;
  let item = res.data[index];
  if(item){
    item.value = newVal;
  }
  res.saveText[index] = newVal;
  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.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);//console.log(789,res,action);
  const text = Object.assign(JSON.parse(config.textLabel),{name:action.name});
  const {index,data,isReplace,span}=action;
  let id = data.id;
  res.symptomIds.push(id);
  let focusIndex = res.focusIndex;
  
  if(isReplace){
    span.current.innerText = '';
    // res.data.splice(focusIndex,1,text,data);
    // 搜索结果展开伴随symptomType==2的尾巴
    let resData = JSON.parse(JSON.stringify(res.data));
    resData.splice(focusIndex,1,text,...(data.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==2;
                            })));
    res.data = fullfillText(resData).newArr;
    res.saveText[focusIndex] = action.name;
  }else{
    // res.data.splice(index,0,data);
    const searchStr = res.searchStr;
    let innerText = span.current.innerText;
    let strIndex = innerText.indexOf(searchStr);
    let value;
    if(strIndex <= 1){//前
      value = innerText.replace(searchStr,action.name);
    }else{
      let temp = innerText.substring(0,innerText.lastIndexOf(searchStr));
      value = temp + action.name;
    }
    span.current.innerText = value;
    let resData = JSON.parse(JSON.stringify(res.data));
    resData[focusIndex].value = value;
    resData.splice(focusIndex+1,0,...(data.questionMapping.filter((item)=>{
                              return item.symptomType==0||item.symptomType==2;
                            })));
    res.data = fullfillText(resData).newArr;
    res.saveText = fullfillText(resData).saveText;
  }
  res.searchData = [];    //选中清空搜索内容（即关闭搜索弹窗）
  res.update = Math.random();//console.log(899,res,action);
  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 = JSON.parse(config.textLabel);
  //使用Object.assign({},data)拷贝操作时复制项和原项会同步修改
  if(!data) return res;
  res.data.splice(i+1,0,JSON.parse(data),textLabel);
  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;
}