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 setMainMoudle = (state,action) => {
  const res = Object.assign({},state);
  // const emptySpan = JSON.parse(config.textLabel);
  // let data = action.data.push(emptySpan);
  res.moduleData = action.data;
  res.saveText = res.save||[];
  res.addSmoduleData = action.addSymptom;
  res.addModuleName = action.addModuleName;
  res.update=Math.random();
  return res;
}

//获取常见症状
export const getCommSymptoms = (state,action) => {
  const res = Object.assign({},state);
  res.CommonSymptoms = action.data;
  return res;
}

//清除常见症状
export const clearCommSymptoms = (state,action) => {
  const res = Object.assign({},state);
  res.CommonSymptoms = [];
  return res;
}

//获取大数据推送症状
export const getBigSymptom = (state,action) => {
  const res = Object.assign({},state);
  res.showDrop = !res.showDrop;
  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;
    }
  }
  
  return res;
}

//点击插入新模板--添加病程变化
export const handleTailClick = (state,action)=>{
  const res = Object.assign({},state);
  res.showDrop = !res.showDrop;
  let num = res.moduleNum.num;
  num++;
  const addSmoduleData = JSON.parse(JSON.stringify(res.addSmoduleData));
  // const addDatas = JSON.parse(JSON.stringify(fullfillText(action.info).newArr));
  let datas = JSON.parse(JSON.stringify(res.data));
  let leng = datas.length;
  for(let i=0; i<addSmoduleData.length; i++){
    addSmoduleData[i].pos = num;
    // let pos = leng-1+i;
   /* let pos = leng-2+i;
    datas.splice(pos,0,addDatas[i]);*/
  }
  res.data = insertPro(datas,addSmoduleData);
  res.saveText = fullfillText(res.data).saveText;
  res.moduleNum.num = num;
  return res;
}


//将选择的常见症状插入
export const insertMain = (state,action) => {
  const res = Object.assign({},state);
  res.showDrop = !res.showDrop;//防止不更新
  const item = action.item.name;
  const id = action.item.questionId;
  // 将选中的id存起，现病史时获取模板
  // let data = res.data;
  let data = JSON.parse(JSON.stringify(res.moduleData));
  // const text = {id:id,name:item,tagType:config.tagType,controlType:3,exist:1};
  const text = {id:id,name:item,value:item,tagType:config.tagType,exist:1};
  const emptySpan = JSON.parse(config.textLabel);
  let inserIndx = null;
  data.map((it,i)=>{
    if(it.flag == 1){//在此处插入主诉数据
      inserIndx = i;
    }
  })
  // data.splice(inserIndx,0,text,emptySpan);
  // data.splice(inserIndx,0,text);
  data[inserIndx-1] = text;//替换空标签
  res.data = data;
  res.saveText = [];//将手动输入的值清掉
  // res.saveText[inserIndx] = text.name;
  res.saveText = fullfillText(res.data).saveText;
  res.mainIds.push(id);
  res.editClear = false;//主诉框编辑状态
  res.update=Math.random();
  return res;
}


function getTextLabel(id,name,flag){
  // exist 主症状1，伴随2
  return {id:id,name:name,value:name,tagType:config.tagType,exist:flag};
}

//多选标签选中确定处理
export const confirm = (state,action) =>{
  const res = Object.assign({},state);
  let arr = res.data;
  let saveText = JSON.parse(JSON.stringify(res.saveText));
  const {exists,withs,ikey,withsName,existsName,ban} = action.data;
  let existsId = getIds(exists);
  let withsId = getIds(withs);
  let banText = JSON.stringify(ban) == "{}" ? '':{id:ban.id,name:ban.name,value:ban.name,tagType:config.tagType};
  res.mainIds = res.mainIds?res.mainIds.concat(existsId,withsId):[];
  let length = exists.length;
  let labelIndx = parseInt(ikey);//当前点击标签的index

  let text = saveText.slice(0,labelIndx);
  let index = text.indexOf('伴');
    if(index==-1){//没有伴,直接插入ikey前
      if(exists.length > 0){
        for(let i=0; i<exists.length; i++){
          let pos = labelIndx + i;
          arr.splice(pos,0,getTextLabel(exists[i].id,exists[i].name,1));
          res.saveText[pos] = exists[i].name;
        }
      }
      if(withs.length > 0){
        let newWiths = JSON.parse(JSON.stringify(withs));
        if(banText){
         newWiths.unshift(banText);
       }
       for(let j=0; j<newWiths.length; j++){
        let withsPos = labelIndx +length + j;
        arr.splice(withsPos,0,getTextLabel(newWiths[j].id,newWiths[j].name,2));
        res.saveText[withsPos] = newWiths[j].name;
      }
    }
    }else{//有伴
      if(exists.length > 0){
        for(let i=0; i<exists.length; i++){
          let pos = index + i;
          arr.splice(pos,0,getTextLabel(exists[i].id,exists[i].name,1));
          res.saveText[pos] = exists[i].name;
        }
      }
      
      if(withs.length>0){//有伴插到ikey前既可     
        for(let j=0; j<withs.length; j++){
          // let withsPos = labelIndx + j;
          let withsPos = labelIndx +length + j;
          arr.splice(withsPos,0,getTextLabel(withs[j].id,withs[j].name,2));
          res.saveText[withsPos] = withs[j].name;
        }
      }
    }
    
    res.data = arr;
    res.saveText = fullfillText(arr).saveText;
    res.update=Math.random();
    return res;
  };


// 普通多选确定事件
export const commConfirm=(state,action)=>{
  const res = Object.assign({},state);
  const {exists,ikey,existsName} = action.data;
  let arr = res.data;
  arr[ikey].value = existsName;
  res.saveText[ikey] = existsName;
  res.selecteds[ikey] = action.data;
  res.update=Math.random();
  return res;
}


export const setSearch = (state,action)=>{
  const res = Object.assign({},state);
  res.showDrop = !res.showDrop;//防止不更新
  let searchData = action.data;
  res.searchDatas = searchData;
  res.searchStr = action.inpStr;
  return res;
}

//将选中的搜索结果插入
export const insertSearch = (state,action)=>{
  // 如果没有模板就插入模板，有模板则只插入所传文字
  const res = Object.assign({},state);
  let data = res.data;
  let moduleData = JSON.parse(JSON.stringify(res.moduleData));
  let searchData = action.info.name;
  const id = action.info.questionId;
  let focusIndex = res.focusIndex;
  let span = action.span;
  let text = {id:id,name:searchData,value:searchData,tagType:config.tagType};
  const emptySpan = JSON.parse(config.textLabel);
  if(data.length==0){   
    let inserIndx = null;
    moduleData.map((it,i)=>{
      if(it.flag == 1){//在此处插入主诉数据
        inserIndx = i;
      }
    })
    // flag=1前是文本标签就替换，否则插入
    const iftext = moduleData[inserIndx-1].tagType;
    if(iftext==config.tagType){
       moduleData.splice(inserIndx-1,1,{id:id,name:searchData,value:searchData,tagType:config.tagType,exist:1});
     }else{
       moduleData.splice(inserIndx,0,{id:id,name:searchData,value:searchData,tagType:config.tagType,exist:1});
     }
    // moduleData.splice(inserIndx,0,{id:id,name:searchData,value:searchData,tagType:config.tagType,exist:1},emptySpan);   
    res.saveText = [];//将手动输入的值清掉
    res.data = moduleData;
    // res.saveText[inserIndx] = searchData;
    res.saveText = fullfillText(res.data).saveText;
    res.mainIds.push(id);
    res.editClear = false;//主诉框编辑状态
  }else{
    // 替换
    /*span.current.innerText = '';
    res.data.splice(focusIndex,1,text);
    res.saveText[focusIndex] = searchData;
    res.mainIds.push(id);*/
    // 追加--前or后？searchStr
    const searchStr = res.searchStr;
    let innerText = span.current.innerText;
    let index = innerText.indexOf(searchStr);
    let value;
    if(index <= 1){//前
      value = innerText.replace(searchStr,searchData);
    }else{
      let temp = innerText.substring(0,innerText.lastIndexOf(searchStr));
      value = temp + searchData;
    }
    // let value = innerText + searchData;
    span.current.innerText = value;
    res.data[focusIndex].value = value;
    res.saveText[focusIndex] = value;
    res.mainIds.push(id);
  }
  // console.log(456,res,action);
  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] = sub.join(',');
    res.saveText[labelInx] = hasValue?sub.join(''):'';
    item.value = 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] = sub.join(',');
    res.saveText[labelInx] = hasValue?sub.join(''):'';
    item.value = 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 saveFreeVal = (state,action)=>{
  const res = Object.assign({},state);
  let data = action.data;
  res.saveText[0] = data;
  /*if(data.trim()){
   res.saveText[0] = data;
  }else{
    res.saveText = [];
  }*/
  res.update = Math.random();
  return res;
}


export const clearMainSuit = (state,action)=>{//回读和清除
  const res = Object.assign({},state);
  res.data = action.data;
  res.saveText = action.saveText;
  // res.saveText = fullfillText(action.data).saveText;//解决删除data里的值保存，回读后页面上有内容saveText里没有的情况
  res.selecteds = action.selecteds?action.selecteds:[];
  res.mainIds = action.mainIds
  if(action.editClear){
    res.editClear = action.editClear;
  }
  if(res.data.length>0){//回读
    res.editClear = false;
  }
  return res;
}


//文本模式下值保存
export const setTextModeValue = (state,action)=>{
  const res = Object.assign({},state);
  res.saveText[0] = action.text;
  return res;
};


//自由文本
export function setCheckText(state,action) {
  let res = Object.assign({},state);
  const {i,text} = action;
  res.data[i].value=text;
  res.saveText[i] = text;
  /*if(res.data[i]){
    res.data[i].value=text;
  }
  res.saveText[i] = text;*/
  res.update = Math.random();
  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);//console.log(state,action)
  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;//console.log(res)
  res.update = Math.random();
  return res;
}