import config from '@config/index.js';
import {formatContinueDots,getLabelIndex,handleLocalDelTag,checkFullfillText} from '@utils/tools.js';
import {shiftLocalDelTag} from "../../utils/tools";

export function preSetCheckbody(state,action) {
  let res = Object.assign({},state);
  const {data} = action;
  res.preData = data;
  return res;
}
//设置查体数据
export function set(state,action){
  let res = Object.assign({},state);
  const {data,isText,isEmpty} = action;
  if(isText){        //查体只显示文本时（引用预问诊）
    const label = Object.assign(JSON.parse(config.textLabel),{value:data,noSearch:true});
    res.data = [label];
    res.saveText = [data];
    res.showAll = true;
    res.update = Math.random();
    res.isEmpty = isEmpty;
    return res;
  }
  const obj = checkFullfillText(data);
  res.data = obj.newArr;
  res.saveText = obj.saveText;//存逗号
  res.showAll = obj.checkHiddenDefault;
  res.update = Math.random();
  res.isEmpty = isEmpty;
  return res;
}
//多选标签选中确定处理
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 = '';
    arr[ikey].selecteds = {};
    res.saveText[ikey] = '';
    res.update=Math.random();
    return res;
  }
  //选中互斥项
  if(exclusion){
    arr[ikey].value = excluName;
    arr[ikey].selecteds = action.data;
    res.saveText[ikey] = excluName;
    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.update=Math.random();
    return res;
  }
  //有，伴，无随配
  //arr.splice(ikey-1,1);
  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);
  //arr[ikey-1].value = text;
  //res.saveText[ikey+items.length] = text;
  res.saveText = checkFullfillText(arr).saveText;
  res.update=Math.random();         //用于触发组件更新（data变化了因在对象中无法被组件检测到）
  return res;
};

//多选文字，如杂音
export function setCheckBoxValue(state,action) {
  let 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.data[labelInx].selecteds = action.data;
  res.saveText = checkFullfillText(res.data).saveText;
  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 searchStr = res.searchStr;
  const {index,data,isReplace,span,searchInEnd}=action;
  const showText = res.saveText[index];
  let tempLabels = data.tagType==4?checkFullfillText(data.questionMapping).newArr:[data];
  tempLabels = formatContinueDots(tempLabels);
  //查体中，默认显示区域搜索出来的标签要默认显示，隐藏区域搜索出的默认隐藏
  let hideAreaIndex = [...res.data].reverse().findIndex((it)=>it.showInCheck);
  hideAreaIndex = res.data.length-hideAreaIndex-1;        //默认显示的最后一个标签的位置
  const text = Object.assign({},JSON.parse(config._textLabel),{showInCheck:index>hideAreaIndex?false:true});
  let spreadLabels =tempLabels.map((it)=>{
    return Object.assign({},it,{showInCheck:index>hideAreaIndex?false:true});
  });
  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 = checkFullfillText(res.data).saveText;
    }else{
      res.data.splice(index,1,text,...spreadLabels,pText);
      res.saveText = checkFullfillText(res.data).saveText;
    }

  }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,'','');
    }else{
      res.data.splice(index,0,text,spreadLabels);
      res.saveText.splice(index,0,'','');
    }
  }
  res.searchData = [];    //选中清空搜索内容（即关闭搜索弹窗）
  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(newVal && newVal.trim()){
  if(labText && 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]));
        }
        //取消原选中状态
        item.questionDetailList.find((it)=>it.selected==true).selected=false;
      }
      item.labelPrefix = prefix||'';
      item.labelSuffix = suffix||'';
      // res.saveText[index] = totalVal;
      res.saveText[index] = labText;
    }
  }else{//删除完标签内容则删除该标签
    const num = nextIsDot?2:1;
    handleLocalDelTag('4',index,res.data[index]);
    res.data.splice(index,num);
    res.saveText = checkFullfillText(res.data).saveText;
  }
  res.update = Math.random();
  return res;
}

function hasNoSame(arr,text){
  return arr.findIndex((it)=>text==it.name)==-1;
}

export function clearCheckBody(state,action){  //清空
  let res = Object.assign({},state);
  res.data = action.data;
  res.preData = [];
  res.saveText = action.saveText;
  res.isEmpty = action.isEmpty;
  if(action.flg){res.showAll = true}
  return res;
}

// backspace删除
export function backspaceText(state,action){
  let res = Object.assign({},state);
  const {delIndex,flag} = action;
  const data = res.data;
  let inx = delIndex-1;     //要删除的（非文本）标签的index
  if(flag == 'backsp'){
    // 前一个是文本标签或者子模板，只改变值
    if(data[inx].flag&&data[inx].flag==3){//子模板不删
      // data[delIndex].value = text;
    }else if(data[inx].tagType==8){
      data.splice(delIndex,1);
      res.saveText.splice(delIndex,1);
    }else{
      handleLocalDelTag(4,inx,data[inx]);
      let n = ''
      if(action.text=='&nbsp;'){
        n = 2
      }else if(action.text.length>0&&(config.punctuationReg.test(action.text))){
        n = 1
      }else{
        n = 2
      }
      data.splice(inx,n);
      res.saveText.splice(inx,n);
    }
  }else if(flag == 'del'){
    inx = delIndex+1;
    if(!data[inx]||(data[inx] && data[inx].flag&&data[inx].flag==3)){//子模板不删
      
    }else if(data[inx] && data[inx].tagType==8){
      data.splice(delIndex,1);
      res.saveText.splice(delIndex,1);
    }else{
      handleLocalDelTag(4,delIndex,data[inx]);
      data.splice(delIndex,2);
      res.saveText.splice(delIndex,2);
    }
  }
  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[index].selecteds = action.data;
    item.map((it)=>{
      if(it.value){
        arr.push(it.labelPrefix+it.value+it.labelSuffix);
      }
    });
    res.saveText[ikey] = arr.join("");
    res.update = Math.random();
    return res;
  }
  data[ikey].value = seleData;
  data[ikey].selecteds = action.data;
  res.saveText[ikey] = seleData;
  res.update = Math.random();
  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;
}
//查体推送高亮标签
export function setImportCheckbodyLabel(state,action) {
  let res = Object.assign({},state);
  res.importLabel = action.labels;
  res.update = Math.random();
  return res;
}

//恢复已删除的标签
export function recoveTag(state,action) {
  let res = Object.assign({},state);
  let arr = [...res.data];
  arr.splice(action.index,0,action.data);
  const dataArr = checkFullfillText(arr);
  let nextLabel = dataArr.newArr[(+action.index)+1];
  //展开收起状态
  if(nextLabel.tagType==8){
    nextLabel.showInCheck=action.data.showInCheck;
  }
  res.data = dataArr.newArr;
  res.saveText = dataArr.saveText;
  shiftLocalDelTag();
  res.update = Math.random();
  return res;
}