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

//多选标签选中确定处理
export const confirm = (state,action) =>{
  let res = Object.assign({},state);
  let arr = res.data;
  const {nones,exists,withs,ikey,exclusion,excluName,copyType} = action.data;
  const items = [...exists||[],...withs||[]];
  if((!exists||!withs||items.length==0)&&!nones&&!exclusion){       //取消无殊的选中，空白提交
    arr[ikey].value = '';
    res.saveText[ikey] = '';
    res.selecteds.splice(ikey,1);
    res.update=Math.random();
    return res;
  }
  //选中互斥项
  if(exclusion){
    arr[ikey].value = excluName;
    res.saveText[ikey] = excluName;
    res.selecteds[ikey] = action.data;
    res.update=Math.random();
    return res;
  }
  //只有无的项目选中
  if(+copyType===0) {      //原标签保留
    arr.splice(ikey,1);
  }
  if(arr[ikey].value)  arr[ikey].value= '';
  let preText = arr[ikey-1].value!==undefined?arr[ikey-1].value:arr[ikey-1].name||'';
  let newPreText =preText +nones;//console.log(arr[ikey-1],newPreText)
  if(items.length==0&&nones){
    arr[ikey-1].value = newPreText;
    res.saveText[ikey-1] = newPreText;
    res.selecteds[ikey] = null;       //无殊选中状态遗留bug修改
    res.update=Math.random();
    return res;
  }
  //有，伴，无随配
  let flabel = items[items.length-1];         //要插入的最后一个标签
  let labelText = flabel.value!==undefined?flabel.value:flabel.name;
  let text = labelText;
  //要插入的最后一个标签为自由文本，则和后面的文本标签文字合并
  if(flabel.tagType==8){
    flabel.value = labelText+nones;
    text = flabel.value;
  }
  arr.splice(ikey,0,...exists,...withs);
  res.saveText = fullfillText(arr).saveText;
  res.update=Math.random();         //用于触发组件更新（data变化了因在对象中无法被组件检测到）
  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;
    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 function setNumberValue(state,action){
  let res = Object.assign({},state);
  const param = action.params;
  const ikey = param.ikey;
  const code = param.formulaCode;
  let labelInx = getLabelIndex(ikey);
  const subInx = ikey.substr(ikey.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[code] = param.text;
  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 setOtherInput(state,action){
  let res = Object.assign({},state);
  const {i,text,prefix,suffix} = action;
  if(res.data[i]){
    res.data[i].value=text;
  }
  res.saveText[i] = prefix+text+suffix;
  res.update = Math.random();
  return res;
}

//多选文字，如杂音
export function setCheckBoxValue(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 setSearchData(state,action){
  let res = Object.assign({},state);
  res.searchData = action.data;
  res.searchStr = action.inpStr;
  res.searchInEnd = action.isEnd;
  return res;
}

//插入标签数据-搜索
export function insertLabelData(state,action){
  let res = Object.assign({},state);
  const text = Object.assign({},JSON.parse(config.textLabel));
  const searchStr = res.searchStr;
  const {index,data,isReplace,span,searchInEnd}=action;
  const showText = res.saveText[index];
  let searchLabels = data.tagType==4?fullfillText(data.questionMapping).newArr:[data];
  const spreadLabels = formatContinueDots(searchLabels);
  let reg = searchInEnd?new RegExp(searchStr+"$"):new RegExp("^"+searchStr);
  const newText=showText.replace(reg,'')||' ';
  if(!isReplace){
    span.current.innerText?(span.current.innerText = newText):(span.current.innerHTML = newText);
    const pText = Object.assign({},text,{value:newText});
    if(searchInEnd){
      res.data.splice(index,1,pText,...spreadLabels,text);
      res.saveText = fullfillText(res.data).saveText;
      res.selecteds.splice(index,1,null,...new Array(spreadLabels.length).fill(null),null);
      //res.saveText.splice(index,1,newText,'','');
    }else{
      res.data.splice(index,1,...spreadLabels,pText,text);
      res.saveText = fullfillText(res.data).saveText;//.splice(index,1,'',newText,'');
      res.selecteds.splice(index,1,...new Array(spreadLabels.length).fill(null),null,null);
    }
  }else{
    span.current.innerText?(span.current.innerText = ' '):(span.current.innerHTML = ' ');
    if(searchInEnd){
      res.data.splice(index+1,0,spreadLabels,text);
      res.saveText.splice(index+1,0,'','');
      res.selecteds.splice(index+1,0,...new Array(spreadLabels.length).fill(null),null);
    }else{
      res.data.splice(index,0,text,spreadLabels);
      res.saveText.splice(index,0,'','');
      res.selecteds.splice(index,0,null,...new Array(spreadLabels.length).fill(null));
    }

  }
  res.searchData = [];    //选中清空搜索内容（即关闭搜索弹窗）
  res.update = Math.random();
  return res;
}

export function changeTextLabel(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;
      //月经史特殊处理
      if(item.formulaCode){
        res[item.formulaCode] = 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]));
        }
        //取消原选中状态
        item.questionDetailList.find((it)=>it.selected==true).selected=false;
      }
      item.labelPrefix = prefix||'';
      item.labelSuffix = suffix||'';
      res.saveText[index] = labText;
    }
  }else{//删除完标签内容则删除该标签
    const num = nextIsDot?2:1;
    //月经史特殊处理
    if(res.data[index].formulaCode){
      res[res.data[index].formulaCode]=undefined;
    }
    res.data.splice(index,num);
    res.selecteds.splice(index,num);//杂音类样式选中状态对应
    res.saveText = fullfillText(res.data).saveText;
  }
  res.update = Math.random();//console.log(888,res,action);
  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.selecteds.splice(index,num);//杂音类样式选中状态对应
    res.saveText = fullfillText(res.data).saveText;
  };
  res.update = Math.random();
  return res;
}

export function clearOtherHistory(state,action){       //清空数据
  let res = Object.assign({},state);
  for(let it in action){
    if(it!='type'){
      res[it] = action[it];
    }
  }
  /*res.data = action.data;
  res.saveText = action.saveText;
  res.selecteds = action.selecteds;
  res.editClear = action.editClear;
  res.isEmpty = action.isEmpty;*/
  return res;
}
//文本模式下值保存
export const setTextModeValue = (state,action)=>{
  const res = Object.assign({},state);
  res.saveText[0] = action.text;
  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 const otherEditClear = (state,action)=>{
  const res = Object.assign({},state);
  res.editClear = action.bool;
  return res;
};

// backspace删除
export function backspaceText(state,action){
  let res = Object.assign({},state);
  const {delIndex} = action;
  const data = res.data;
  if(data[delIndex-1].flag&&data[delIndex-1].flag==3){
  // if(data[delIndex-1].tagType==8 ||data[delIndex-1].flag&&data[delIndex-1].flag==3){
    // 前一个是文本标签或者子模板 不做处理
  }else if(data[delIndex-1].tagType==8){
    data.splice(delIndex,1);
    res.selecteds.splice(delIndex,1);      //杂音类样式选中状态对应
    res.saveText.splice(delIndex,1);
  }
  else{
    //月经史删除处理
    if(data[delIndex-1].formulaCode){
      res[data[delIndex-1].formulaCode]=undefined;
    }
    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;
}

//删除后移除空标签
export function removeId(state,action){
  let res = Object.assign({},state);
  const {index} = action;
  const data = res.data;
  if(!data[index].value && data[index-1].tagType==8){
    data.splice(index,1);
    res.saveText.splice(index,1);
  } 
  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;//console.log(action,data[ikey])
  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;
}