import config from '@config/index.js';
import {getLabelIndex,checkFullfillText,fullfillText,shiftLocalDelTag,getEMRParams,storageLocal} from './tools';
import { json } from "./ajax";
/**
 * 各类标签统一的处理函数
 *
 * */
const api = {
  push:'/push/pushInner'
};
//数字键盘选中事件
export function setNumberValue(state,action){
  let res = Object.assign({},state);
  const param = action.params;
  const ikey = param.ikey;
  let labelInx = getLabelIndex(ikey);
  const subInx = ikey.split("-")[2];
  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;
      }
      if(it.tagType===8){       //维护时的连接词无value
        return it.name;
      }else{
        //组合中未填值的子标签预览中不显示
        if(!it.value){
          return '';
        }
        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.split("-")[2];
  let item = res.data[labelInx];
  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;
      }
      if(it.tagType===8){      //维护时的连接词无value
        return it.name;
      }else{
        //组合中未填值的子标签预览中不显示
        if(!it.value){
          return '';
        }
        return (it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||'');
      }
    });
    res.saveText[labelInx] = hasValue?sub.join(''):'';
    item.value = 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 item = res.data[index];
  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 = '';
    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;
  res.saveText[index] = str;
  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 = fullfillText(arr);
  res.data = dataArr.newArr;
  res.saveText = dataArr.saveText;
  shiftLocalDelTag();
  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.saveText[i] = text;
  res.update = Math.random();
  return res;
}

//复制标签（如血压）事件
export function addLabelItem(state,action,boxMark){
  let res = Object.assign({},state);
  const {data,i} = action;
  const item = JSON.parse(data);
  const textL = JSON.parse(config.textLabel);
  //查体添加的自由文本标签需要逗号，且要设置隐藏状态
  const textLabel = boxMark==='4'?Object.assign({},textL,{showInCheck:item.showInCheck,name:'，'}):textL;
  //使用Object.assign({},data)拷贝操作时复制项和原项会同步修改
  if(!data) return res;
  res.data.splice(+i+2,0,item,textLabel);
  res.saveText.splice(+i+2,0,'','');
  res.update = Math.random();
  return res;
}

//文本输入标签inlineTag值保存
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)=>{
      if(it.tagType===8){
        return it.name;
      }else{
        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;
    }
  }
  if(text){
    res.saveText[i] = prefix+text+suffix;
  }else{//删除完要清空
    res.saveText[i] = "";
  }
  res.update = Math.random();
  return res;
}

//获取大数据推送结果:
// type需推送的类型，symData症状相关的内容（symptom入参）,save参数是否要保存到本地做变化对比
export async function getBigPush(type,symData,save){
  const emrData = getEMRParams();
  const params = {
    "age": emrData.age,
    "hosCode": emrData.hosCode,
    "featureType": type,  //类型1：症状，4：查体，5：化验，6：辅检，7：诊断
    "ruleType":config.ruleTypeMap[type],
    "diag": emrData.dis,
    "lis": emrData.lis,
    "other": emrData.other,
    "pasts": emrData.other,
    "pacs": emrData.pacs,
    "sex": emrData.sex,
    "vital":emrData.vital,
    "symptom": symData||emrData.current + emrData.main
  };
  if(save){
    let savePm = Object.assign({},params);
    delete savePm.featureType;
    storageLocal.set('emrParam',savePm);      //推送数据存储，用作推送前对比是否有变，有变才推送
  }
  return json(api.push,params);
}