import store from '@store';
import { REINITPATINFO, CLEARINITPATINFO } from '@store/types/patInfo';
import {
  CLEAR_MAIN_SUIT,
  CLEAR_SEARCH,
  REMAINSUITDATA,
  CLEARMAINSUITDATA,
} from '@store/types/mainSuit';
import {
  CLEAR_CURRENT_ILL,
  CURRENT_CLEAR,
  RECURRENTDATA,
  CLEARCURRENTDATA,
} from '@store/types/currentIll';
import { REPASTTEXTDATA, CLEARPASTTEXTDATA } from '@store/types/pastHistory';
import { CLEAR_MR_INFO } from '@store/types/print';
import { REPERSONTEXTDATA, CLEARPERSONTEXTDATA } from '@store/types/personalHistory';
import { REFAMILYTEXTDATA, CLEARFAMILYTEXTDATA } from '@store/types/familyHistory';
import { REMARRIAGETEXTDATA, CLEARMARRIAGETEXTDATA } from '@store/types/marriageHistory';
import {REMENSTRUATIONTEXTDATA,CLEARMENSTRUATIONTEXTDATA,} from '@store/types/menstruationHistory';
import { REINSPECTDATA, CLEARINSPECTDATA } from '@store/types/inspect';
import { REASSISTCHECKDATA, CLEARASSISTCHECKDATA } from '@store/types/assistCheck';
import { RENEWADVICEDATA, CLEARNEWADVICEDATA } from '@store/types/newAdvice';
import {CLEAROTHERHISTORY,OTHERHIS_CLEAR} from '@store/types/otherHistory';
import { CLEARCHECKBODY, SET, CHECKBODY_CLEAR, RECHECKBODYTEXTDATA,CLEARCHECKBODYTEXTDATA } from '@store/types/checkBody';
import {clearAssistData,addAssistLabel} from '@store/actions/assistCheck';
import { clearAllLabel, addLabel} from '@store/actions/inspect';
import { CLEAR_ALL_DIAG, REDIAGDATA, CLEARDIAGDATA } from '@store/types/diagnosticList';
import {CLEAR_ALL_PUSH_MESSAGE, SET_TIPS,BILLING_ADVICE,PUSHCHANGE,SET_MR_ANALYSE} from '@store/types/pushMessage';
import {ISREAD, SETREADDITEMS,SET_SELECTED_AREA,SET_CURRENT_MODULE} from "../store/types/homePage";
import {CLEAR_FIRST_MAIN_DIAG, CLEAR_ALL_TREAT} from "../store/types/treat";
import {tabChange} from '@store/actions/tabTemplate';
import {CLEAR_ASSESS_RESULT_VALUE} from '@types/assessResult';
import { SET_READ_MODE } from "@store/types/typeConfig";
import config from '@config/index';
import up from '@images/up.png';
import down from '@images/down.png';
import $ from 'jquery';
import {CLEAR_SEARCH_PARAM} from "../store/types/print";

// import { embedPush } from '@store/async-actions/pushMessage'
/***
 * 工具函数
 *
 * ***/
const qs = require('qs');
//localStorage方法封装
const storageLocal = {
  set: function (name, data) {
    if(!data) {
      return;
    }
    if(typeof data !== 'string') {
      data = JSON.stringify(data);
    }
    localStorage.setItem(name, data);
  },
  get: function (name) {
    return localStorage.getItem(name);
  },
  remove: function (name) {
    localStorage.removeItem(name);
  },
  clear: function () {
    localStorage.clear();
  }
};

//是否为空
const isNull = (item)=>{
    return String(item)=== "" || String(item)==="null" || String(item)==="undefined";
};

const isNotNull = (item)=>{
    return !(isNull(item));
};

//判断是否为ie浏览器
const isIE  = () => { //ie?
    if (!!window.ActiveXObject || "ActiveXObject" in window){
        return true;
    } else{
        return false;

    }
}

const deepClone = (data)=>{
    return JSON.parse(JSON.stringify(data)||null)||{};
};

const getUrlArgObject = (parm) => {
    let query = window.location.search;
    let args = qs.parse(query.substr(1));
    return args[parm];//返回对象  
} 

// 转换jsonData 数据  转为json
const getAllDataList =(baseList) =>{           //获取所有模块结构化的数据
    let jsonData = {};
    jsonData.lis = {};
    jsonData.chief = baseList.mainSuit.saveText&&baseList.mainSuit.saveText[0];   // 主诉
    jsonData.currentIll = baseList.currentIll.saveText && baseList.currentIll.saveText[0];   //现病史
    jsonData.pastHistory = baseList.pastHistory.saveText && baseList.pastHistory.saveText[0];   //既往史
    jsonData.personalHistory = baseList.personalHistory.saveText && baseList.personalHistory.saveText[0];   //个人史
    jsonData.familyHistory = baseList.familyHistory.saveText && baseList.familyHistory.saveText[0];   //家族史
    jsonData.marriageHistory = baseList.marriageHistory.saveText && baseList.marriageHistory.saveText[0];   //婚育史
    jsonData.menstruationHistory = baseList.menstruationHistory.saveText && baseList.menstruationHistory.saveText[0];   //月经史
    jsonData.checkBody = baseList.checkBody.saveText && baseList.checkBody.saveText[0];   //查体


    jsonData.lis.labelList = baseList.inspect.labelListSmall &&  baseList.inspect.labelListSmall;      //化验
    jsonData.pacs = baseList.assistCheck.assistLabel;     //辅检
    jsonData.diag = baseList.diagnosticList.diagnosticList;      //诊断
    jsonData.advice = baseList.newAdvice.labelListSmall;       //医嘱


    //月经史公式
    // const other = baseList.otherHistory;
    // jsonData.lis = {};
    // jsonData.chief = baseList.mainSuit.data;      //主诉
    // jsonData.present = baseList.currentIll.data;    //现病史
    // jsonData.other = other.data;      //其他史
    // jsonData.otherHistoryIsEmpty = other.isEmpty;
    // jsonData['yjs_1'] = other['yjs_1'];
    // jsonData['yjs_2'] = other['yjs_2'];
    // jsonData['yjs_3'] = other['yjs_3'];
    // jsonData['yjs_4'] = other['yjs_4'];
    // jsonData.vital = baseList.checkBody.data;    //查体
    // jsonData.checkBodyIsEmpty = baseList.checkBody.isEmpty;
    // jsonData.lis.labelList = baseList.inspect.labelList;      //化验
    // jsonData.lis.getExcelDataList =  baseList.inspect.getExcelDataList;      //化验导入
    // jsonData.checkedListImport = baseList.assistCheck.checkedListImport;     //辅检导入
    // jsonData.pacs = baseList.assistCheck.assistLabel;     //辅检
    // jsonData.diag = baseList.diagnosticList.diagnosticList;      //诊断
    // jsonData.advice = baseList.pushMessage.advice;       //医嘱
    // jsonData.addItems = baseList.homePage.addItems||{};
    // jsonData.mainsuitIds = baseList.mainSuit.mainIds;      //主诉去重
    // jsonData.mainChronicDesease = baseList.mainSuit.chronicDesease;      //主诉慢病{}
    // jsonData.diagChronicMagItem = baseList.diagnosticList.chronicMagItem;      //诊断慢病{}
    // jsonData.currentIds = baseList.currentIll.symptomIds;      //现病史去重
    // jsonData.isFirstMainDiag = baseList.treat.isFirstMainDiag;      //治疗方案
    // jsonData.mainReadSonM = baseList.mainSuit.addSmoduleData;      //主诉-子模板
    // jsonData.currReadSonM = baseList.currentIll.useEmpty?baseList.currentIll.currentEmptySon:baseList.currentIll.processModule;      //现病史-子模板
    return jsonData;
}
const getAllDataStringList =(baseList) =>{           //获取所有模块文本的数据
    let jsonDataString = {};
    jsonDataString.lis = {};
    let chiefData = [],presentData=[],otherData=[],vitalData=[];
    if(baseList.mainSuit.saveText.length == 1 && baseList.mainSuit.saveText[0].trim() == ''){
        chiefData = []
    }else{
        chiefData = baseList.mainSuit.saveText
    }
    if(baseList.currentIll.saveText.length == 1 && baseList.currentIll.saveText[0].trim() == ''){
        presentData = []
    }else{
        presentData = baseList.currentIll.saveText
    }
    const oText = baseList.otherHistory.saveText;
    if(oText.length == 1 && oText[0] && oText[0].trim() == ''){
        otherData = []
    }else{
        otherData = baseList.otherHistory.saveText
    }

    if(baseList.checkBody.saveText.length == 1 && baseList.checkBody.saveText[0].trim() == ''){
        vitalData = []
    }else{
        vitalData = baseList.checkBody.saveText
    }
    jsonDataString = {
      'chief' : JSON.stringify(chiefData),
      'present' : JSON.stringify(presentData),
      'other' : JSON.stringify(otherData),
      'vital' : JSON.stringify(vitalData),
      'lis' : baseList.inspect.inspectStrPlus,
      'pacs' : baseList.assistCheck.dataString,
      'diag' : baseList.diagnosticList.diagnosticStr,
      'advice' : baseList.pushMessage.AdviceStr
    }
    return jsonDataString;
}

 // 返回文本信息 转换preview 数据  转为json
const formatTextInfo = (baseList) =>{console.log(1,baseList)
  // console.log(baseList,'=========baseList==========');
  let labelList = {
    labelListSmall: [],
    labelListBig: [],
  };
  labelList.labelListSmall = baseList.inspect.labelListSmall;
  labelList.labelListBig = baseList.inspect.labelListBig;

  let newAdviceLabelList = {
    labelListSmall: [],
    labelListBig: [],
    labelListBlood: [],
  };
  newAdviceLabelList.labelListSmall = baseList.newAdvice.labelListSmall;
  newAdviceLabelList.labelListBig = baseList.newAdvice.labelListBig;
  newAdviceLabelList.labelListBlood = baseList.newAdvice.labelListBlood;
  newAdviceLabelList.operationName = baseList.newAdvice.operationName;

  let assistLabelList = {
    dataString: baseList.assistCheck.dataString,
    assistLabel: baseList.assistCheck.assistLabel,
  };

  let diagnosticList = {
    diagnosticList: baseList.diagnosticList.diagnosticList,
    diagnosticStrNoType: baseList.diagnosticList.diagnosticStrNoType,
    diagnosticStr: baseList.diagnosticList.diagnosticStr,
    diseaseName: baseList.diagnosticList.diseaseName,
  };
    const {otherIndex} = baseList.diagnosticList;
    const {tcmList} = baseList.diagnosticList;
    let str = '';
    tcmList.map((it)=>{
        str+=it.tcmDiag+"-"+it.tcmSyndrome+','
    });
  let diagnosticTcmList = {
      diagnosticList: baseList.diagnosticList.tcmList,
      diagnosticStrNoType: otherIndex?(otherIndex.tcmDiag+otherIndex.tcmSyndrome):'',
      diagnosticStr: str,
      diseaseName: otherIndex,
  };
  return {
    chief: JSON.stringify(baseList.mainSuit.saveText),
    present: JSON.stringify(baseList.currentIll.saveText),
    pastHistory: JSON.stringify(baseList.pastHistory.saveText),
    personalHistory: JSON.stringify(baseList.personalHistory.saveText),
    familyHistory: JSON.stringify(baseList.familyHistory.saveText),
    marriageHistory: JSON.stringify(baseList.marriageHistory.saveText),
    menstruationHistory: JSON.stringify(baseList.menstruationHistory.saveText),
    vital: JSON.stringify(baseList.checkBody.saveText),
    lis: labelList, //化验
    pacs: assistLabelList,
    diag: diagnosticList,
    tcmDiag:diagnosticTcmList,
    advice: newAdviceLabelList,
  };
}

// 回读数据_lcq_2020.08.17
const pushHistoryDataList = (reData) =>{
 store.getState().inspect.context.scrollArea&&store.getState().inspect.context.scrollArea.scrollTop()
 let dataJson = JSON.parse(reData.preview)
  // 回显头部表单数据 
 store.dispatch({
   type: REINITPATINFO,
   params: reData,
 });
  store.dispatch({
    type: RENEWADVICEDATA,
    params: dataJson,
  });
  // 回显 主诉数据
  store.dispatch({
    type: REMAINSUITDATA,
    params: dataJson,
  });

  // 回显 现病史数据
  store.dispatch({
    type: RECURRENTDATA,
    params: dataJson,
  });

  // 回显 既往史数据
  store.dispatch({
    type: REPASTTEXTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REPERSONTEXTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REFAMILYTEXTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REMARRIAGETEXTDATA,
    params: dataJson,
  }); 
  // 月经史
  store.dispatch({
    type: REMENSTRUATIONTEXTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: RECHECKBODYTEXTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REINSPECTDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REASSISTCHECKDATA,
    params: dataJson,
  }); 
  store.dispatch({
    type: REDIAGDATA,
    params: dataJson,
  });

  store.dispatch({
    type: ISREAD,
  });

}

// 清空数据 _lcq_2020.08.18
const delHistoryDataList = () =>{
  store.getState().inspect.context.scrollArea && store.getState().inspect.context.scrollArea.scrollTop();
  store.dispatch({
    type: CLEARINITPATINFO,
  });
  store.dispatch({
    type: CLEARMAINSUITDATA,
  });
  store.dispatch({
    type: CLEARCURRENTDATA,
  });
  store.dispatch({
    type: CLEARPASTTEXTDATA,
  });
  store.dispatch({
    type: CLEARPERSONTEXTDATA,
  });
  store.dispatch({
    type: CLEARFAMILYTEXTDATA,
  });
  store.dispatch({
    type: CLEARMARRIAGETEXTDATA,
  });
  store.dispatch({
    type: CLEARMENSTRUATIONTEXTDATA,
  });
  store.dispatch({
    type: CLEARCHECKBODYTEXTDATA,
  });
  store.dispatch({
    type: CLEARINSPECTDATA,
  });
  store.dispatch({
    type: CLEARASSISTCHECKDATA,
  });
  store.dispatch({
    type: CLEARDIAGDATA,
  });
  store.dispatch({
      type: 'CLEARTCMDIAGDATA',
  });
  store.dispatch({
    type: CLEARNEWADVICEDATA,
  });
  store.dispatch({
    type: CLEAR_MR_INFO,
  });
  store.dispatch({
    type: ISREAD,
  });
  

}


// 防抖函数
export function debounce(func, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}




/**
 * 
 * @param {回读数据} reData 
 * @param {回读数据是历史病历'history'，还是模板'template',预问诊引用'preIcss'} type 
 * @param {什么操作，回读'push'还是清空'clear'} action 
 * @param {引用的话是保存时候的文本类型，编辑的时候是当前页面设置的文本类型} whichSign 
 */
const pushAllDataList =(whichSign,action,reData,type) =>{           //回读清空所有的数据
  store.getState().inspect.context.scrollArea&&store.getState().inspect.context.scrollArea.scrollTop()
    if(action == 'clear'){    //清空
      const embedPush=require('@store/async-actions/pushMessage').embedPush;    //直接在上面import会报错
      const block = Object.assign(JSON.parse(config.textLabel),{full:true});//空白时保留一个自由文本标签
      //清除已删除标签记录
      //localStorage.removeItem('deletedTags');
      //store.dispatch({type: SET_READ_MODE, readMode: -1,readConfig:-1,isPreIcss:false});      //清除回读模式值
      store.dispatch({type: CLEAR_MAIN_SUIT,data:[],saveText:[],editClear:true,mainIds:[],mainTailIds:[],clearAction:true,symptomFeature:[],chronicDesease:null,mainReadSonM:[]});
        store.dispatch({type: CLEAR_CURRENT_ILL,data:[],saveText:[],editClear:true,symptomIds:[],currReadSonM:[]});
        store.dispatch({type: CLEAROTHERHISTORY,data:[block],isEmpty:true,saveText:[],editClear:true,yjs_1:'',yjs_2:'',yjs_3:'',yjs_4:''});
        store.dispatch({type: CLEARCHECKBODY,data:[block],isEmpty:true,saveText:[]});
        //store.dispatch({type:SETREADDITEMS});     //清空已存的血压加号项
        store.dispatch(clearAssistData([],'',[]));
        store.dispatch(clearAllLabel([],[],''));
        store.dispatch(embedPush({mode:1}));  //刷新右侧推送
        //右侧搜索条件清空
        store.dispatch({
          type: CLEAR_SEARCH_PARAM,
          data: Math.random()
        });
        //tab跳回辅助信息
        store.dispatch(tabChange('0'));
        store.dispatch({
            type: SET_TIPS,
            tips: {}
        })
        store.dispatch({
            type: CLEAR_ALL_DIAG,
            data:[],
            saveText:'',
            mainSuitStr: '',
            chronicMagItem:null
        });
        store.dispatch({
            type: CLEAR_ALL_PUSH_MESSAGE,
            data:{},
            saveText:'',
        });
        store.dispatch({
          type:CLEAR_FIRST_MAIN_DIAG,
          flag:true
        });
        store.dispatch({
          type: CLEAR_ALL_TREAT,
        });
        //清空已选的指标推送数据及填的值
        /*store.dispatch({
          type: CLEAR_ASSESS_RESULT_VALUE,
        });*/
        store.dispatch({//推送重置
          type: BILLING_ADVICE,
          determine:[],
          doubt:[],
          possible:[],
          vigilant: [],
          likely:[],
          lab: [],
          pacs:[],
          setPushEmergency:{},
          setPushEmergencyIdx:''
        });
        /*store.dispatch({
          type: SET_CURRENT_MODULE,
          moduleName: ''
        })
        store.dispatch({
          type: SET_MR_ANALYSE,
          MRAnalyseResult: []
        })*/
        storageLocal.remove('emrParam');
       // Notify.success('页面已清空')
    }else if(type == 'preIcss'){
      store.dispatch({type: SET_READ_MODE, readMode: whichSign,isPreIcss:true});
      store.dispatch({     //主诉文本框
          type: CLEAR_MAIN_SUIT,
          data:[],
          saveText:reData.chief
      });
      store.dispatch({
          type: CLEAR_CURRENT_ILL,
          data:[],
          saveText:reData.current
      });
      store.dispatch({
          type: CLEAROTHERHISTORY,
          data:[],
          isEmpty:false,
          saveText:reData.other
      });
      store.dispatch({
          type: SET,
          isEmpty:reData.checkBody?false:true,
          data:reData.checkBody,
          isText:true,    //查体只显示文本
      });
      store.dispatch({type:SETREADDITEMS});     //清空已存的血压加号项
        store.dispatch(clearAssistData([],'',[]));
        store.dispatch(clearAllLabel([],[],''));
        store.dispatch({
            type: SET_TIPS,
            tips: {}
        })
        store.dispatch({
            type: CLEAR_ALL_DIAG,
            data:[],
            saveText:'',
            mainSuitStr: '',
            chronicMagItem:null
        });
        store.dispatch({
            type: CLEAR_ALL_PUSH_MESSAGE,
            data:{},
            saveText:'',
        });
        store.dispatch({
          type:CLEAR_FIRST_MAIN_DIAG,
          flag:true
        });
        store.dispatch({
          type: CLEAR_ALL_TREAT,
        });
        //清空已选的指标推送数据及填的值
        store.dispatch({
          type: CLEAR_ASSESS_RESULT_VALUE,
        });
        store.dispatch({//推送重置
          type: BILLING_ADVICE,
          determine:[],
          doubt:[],
          possible:[],
          vigilant: [],
          likely:[],
          lab: [],
          pacs:[],
          setPushEmergency:{},
          setPushEmergencyIdx:''
        });
        storageLocal.remove('emrParam');
    }else{
        let dataJson = JSON.parse(reData.dataJson);
        const docConfig = dataJson.docConfigs;
        //回读/引用设置回读模式值（主诉-其他史使用）
        store.dispatch({type: SET_READ_MODE, readMode: whichSign,readConfig:docConfig});
        if (whichSign == 0) {
          //其他史data
          const oData = dataJson.other;
          const onlyOneText = oData.length==1&&oData[0].tagType==8&&!(oData[0].name||oData[0].value);
          if(type == 'template'){        //结构化模板回读
              let dataJsonStr = JSON.parse(reData.preview);
                // console.log(dataJson,dataJsonStr,'结构化模板引用')
                //清空已选的指标推送数据及填的值
                store.dispatch({
                  type: CLEAR_ASSESS_RESULT_VALUE,
                });
                store.dispatch({
                    type: CLEAR_MAIN_SUIT,
                    data:dataJson.chief,
                    saveText:JSON.parse(dataJsonStr.chief),
                    mainIds:dataJson.mainsuitIds?dataJson.mainsuitIds:[],
                    chronicDesease:dataJson.mainChronicDesease,
                    mainReadSonM:dataJson.mainReadSonM,
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:dataJson.present,
                    saveText:JSON.parse(dataJsonStr.present),
                    symptomIds:dataJson.currentIds?dataJson.currentIds:[],
                    currReadSonM:dataJson.currReadSonM
                });
                store.dispatch({
                    type: CLEAROTHERHISTORY,
                    data:dataJson.other,
                    yjs_1:dataJson.yjs_1,
                    yjs_2:dataJson.yjs_2,
                    yjs_3:dataJson.yjs_3,
                    yjs_4:dataJson.yjs_4,
                    isEmpty:onlyOneText?true:false,//dataJson.otherHistoryIsEmpty,
                    saveText:JSON.parse(dataJsonStr.other),
                    editClear:dataJson.other.length>0?false:true
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    isEmpty:dataJson.checkBodyIsEmpty,
                    saveText:JSON.parse(dataJsonStr.vital)
                });
                store.dispatch(clearAllLabel(
                    dataJson.lis.labelList,
                    dataJson.lis.getExcelDataList,
                    dataJsonStr.lis.split('-')[0],
                    dataJsonStr.lis.split('-')[1]
                ));
                store.dispatch(clearAssistData(dataJson.pacs,dataJsonStr.pacs,dataJson.checkedListImport||[]));
                store.dispatch({
                    type: CLEAR_ALL_DIAG,
                    data:dataJson.diag,
                    saveText:dataJsonStr.diag,
                    chronicMagItem:dataJson.diagChronicMagItem
                });
                store.dispatch({
                    type: CLEAR_ALL_PUSH_MESSAGE,
                    data:dataJson.advice,
                    saveText:dataJsonStr.advice
                });
                store.dispatch({
                  type:SETREADDITEMS,
                  data:dataJson.addItems
                });
                store.dispatch({
                  type:CLEAR_FIRST_MAIN_DIAG,
                  flag:dataJson.isFirstMainDiag
                });
              //tab跳回辅助信息
              store.dispatch(tabChange('0'));
            }else{    //结构化历史病历回读
                let dataJsonStr = reData.detailList;
                //清空已选的指标推送数据及填的值
                store.dispatch({
                  type: CLEAR_ASSESS_RESULT_VALUE,
                });
                store.dispatch({
                    type: CLEAR_MAIN_SUIT,
                    data:dataJson.chief,
                    saveText:dataJsonStr[0].content ? JSON.parse(dataJsonStr[0].content) :[],
                    mainIds:dataJson.mainsuitIds?dataJson.mainsuitIds:[],
                    chronicDesease:dataJson.mainChronicDesease,
                    mainReadSonM:dataJson.mainReadSonM,
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:dataJson.present,
                    saveText:dataJsonStr[1].content ? JSON.parse(dataJsonStr[1].content):[],
                    symptomIds:dataJson.currentIds?dataJson.currentIds:[],
                    currReadSonM:dataJson.currReadSonM
                });
                store.dispatch({
                    type: CLEAROTHERHISTORY,
                    data:dataJson.other,
                    yjs_1:dataJson.yjs_1,
                    yjs_2:dataJson.yjs_2,
                    yjs_3:dataJson.yjs_3,
                    yjs_4:dataJson.yjs_4,
                    saveText:dataJsonStr[2].content ? JSON.parse(dataJsonStr[2].content):[],
                    isEmpty:onlyOneText?true:false,//dataJson.otherHistoryIsEmpty,回读回来后判断是否只有一个空标签，是的话要使用模板
                    editClear:dataJson.other.length>0?false:true
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    isEmpty:dataJson.checkBodyIsEmpty,
                    saveText:dataJsonStr[3].content ? JSON.parse(dataJsonStr[3].content):[]
                });
                store.dispatch(clearAllLabel(
                    dataJson.lis.labelList,
                    dataJson.lis.getExcelDataList,
                    dataJsonStr[4].content ? dataJsonStr[4].content.split('-')[0] :'',
                    dataJsonStr[4].content ? dataJsonStr[4].content.split('-')[1] :''
                ));
                store.dispatch(clearAssistData(
                    dataJson.pacs,
                    dataJsonStr[5].content ? dataJsonStr[5].content:'',
                    dataJson.checkedListImport||[]
                ));
                store.dispatch({
                    type: CLEAR_ALL_DIAG,
                    data:dataJson.diag,
                    saveText:dataJsonStr[6].content ? dataJsonStr[6].content:'',
                    chronicMagItem:dataJson.diagChronicMagItem
                });
                store.dispatch({
                    type: CLEAR_ALL_PUSH_MESSAGE,
                    data:dataJson.advice,
                    saveText:dataJsonStr[7].content ? dataJsonStr[7].content:''
                });
              store.dispatch({
                type:SETREADDITEMS,
                data:dataJson.addItems
              });
              store.dispatch({
                type:CLEAR_FIRST_MAIN_DIAG,
                flag:dataJson.isFirstMainDiag
              });
            }
        } else {
            if(type == 'template'){     //纯文本模板回读
                //let dataJson = JSON.parse(reData.dataJson);
                let dataJsonStr = JSON.parse(reData.preview);
                // console.log(dataJson,dataJsonStr,'纯文本模板引用')
                store.dispatch({     //主诉文本框
                    type: CLEAR_MAIN_SUIT,
                    data:[],
                    saveText:JSON.parse(dataJsonStr.chief)
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:[],
                    saveText:JSON.parse(dataJsonStr.present)
                });
                store.dispatch({
                    type: CLEAROTHERHISTORY,
                    data:[],
                    isEmpty:dataJson.otherHistoryIsEmpty,
                    saveText:JSON.parse(dataJsonStr.other)
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    isEmpty:dataJson.checkBodyIsEmpty,
                    flg:true,
                    saveText:JSON.parse(dataJsonStr.vital)
                });
                store.dispatch(clearAllLabel(
                    dataJson.lis.labelList,
                    dataJson.lis.getExcelDataList,
                    dataJsonStr.lis.split('-')[0],
                    dataJsonStr.lis.split('-')[1]
                ));
                store.dispatch(clearAssistData(dataJson.pacs,dataJsonStr.pacs,dataJson.checkedListImport||[]));
                store.dispatch({
                    type: CLEAR_ALL_DIAG,
                    data:dataJson.diag,
                    saveText:dataJsonStr.diag
                });
                store.dispatch({
                    type: CLEAR_ALL_PUSH_MESSAGE,
                    data:dataJson.advice,
                    saveText:dataJsonStr.advice,
                });
              store.dispatch({
                type:SETREADDITEMS,
                data:dataJson.addItems
              });
              store.dispatch({
                type:CLEAR_FIRST_MAIN_DIAG,
                flag:dataJson.isFirstMainDiag
              });
              //tab跳回辅助信息
              store.dispatch(tabChange('0'));
            }else{  //纯文本历史病历回读
                //let dataJson = JSON.parse(reData.dataJson);
                let dataJsonStr = reData.detailList;
                // console.log(dataJson,dataJsonStr,'纯文本历史病历回读')
                if(!dataJson && !dataJsonStr && !reData.sign){
                    return;
                }
                store.dispatch({
                    type: CLEAR_MAIN_SUIT,
                    data:[],
                    saveText:dataJsonStr[0].content ? JSON.parse(dataJsonStr[0].content) :[]
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:[],
                    saveText:dataJsonStr[1].content ? JSON.parse(dataJsonStr[1].content) :[]
                });
                store.dispatch({
                    type: CLEAROTHERHISTORY,
                    data:[],
                    isEmpty:dataJson.otherHistoryIsEmpty,
                    saveText:dataJsonStr[2].content ? JSON.parse(dataJsonStr[2].content) :[]
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    flg:true,
                    isEmpty:dataJson.checkBodyIsEmpty,
                    saveText:dataJsonStr[3].content ? JSON.parse(dataJsonStr[3].content):[]
                });
                store.dispatch(clearAllLabel(
                    dataJson.lis.labelList,
                    dataJson.lis.getExcelDataList,
                    dataJsonStr[4].content ? dataJsonStr[4].content.split('-')[0] :'',
                    dataJsonStr[4].content ? dataJsonStr[4].content.split('-')[1]:''
                ));
                store.dispatch(clearAssistData(
                    dataJson.pacs,
                    dataJsonStr[5].content ? dataJsonStr[5].content:'',
                    dataJson.checkedListImport||[]
                ));
                store.dispatch({
                    type: CLEAR_ALL_DIAG,
                    data:dataJson.diag,
                    saveText:dataJsonStr[6].content ? dataJsonStr[6].content:''
                });
                store.dispatch({
                    type: CLEAR_ALL_PUSH_MESSAGE,
                    data:dataJson.advice,
                    saveText:dataJsonStr[7].content ? dataJsonStr[7].content:''
                });
              store.dispatch({
                type:SETREADDITEMS,
                data:dataJson.addItems
              });
              store.dispatch({
                type:CLEAR_FIRST_MAIN_DIAG,
                flag:dataJson.isFirstMainDiag
              });
            }
        }
    }
  store.dispatch({
    type:ISREAD
  });
}

function filterArr(arr){
    let tmpArr = arr.filter((item)=>{
        if(item){
          return item
        }
    });
    return tmpArr.join("").replace(/\s/g,'');
}

function filterDataArr(arrTmp){   //数据处理
    if(!Array.isArray(arrTmp)){
      return
    }
    let tmpArr = [];
    tmpArr = arrTmp.map((it,i)=>{     //连续的标点符号保留第一个
      if(!it)return '';
      if(!it.match(config.punctuationReg)&&!arrTmp[i-1]){        //只有标点符号或者前一个标签无值是（说明本标点灰显，不显示在预览中）
          return '';
      }
      return it.replace(config.punReg,function(word){
        return word.substr(0,1);
      });
    });
   

    return trimDots(tmpArr.join(''));      //去掉开头的标点符号，最后的标点保留第一个,中间连续的保留第一个
}
//其他史预览数据处理-月经史
function filterOtherDataArr(arrTmp,jsonArr){
  let tmpArr = [];
  let index1 = jsonArr.findIndex((item)=>{
    return item.formulaCode=='yjs_1';
  });
  let index2 = jsonArr.findIndex((item)=>{
    return item.formulaCode=='yjs_2';
  });
  let index3 = jsonArr.findIndex((item)=>{
    return item.formulaCode=='yjs_3';
  });
  let index4 = jsonArr.findIndex((item)=>{
    return item.formulaCode=='yjs_4';
  });
  if(index1==-1&&index2==-1&&index3==-1&&index4==-1){//无月经史
    return {str1:filterDataArr(arrTmp),str2:''};
  }
  tmpArr = arrTmp.map((it,i)=>{     //连续的标点符号保留第一个
    if(!it.match(config.punctuationReg)&&!arrTmp[i-1]||[index1,index2,index3,index4].includes(i)){        //只有标点符号或者前一个标签无值是（说明本标点灰显，不显示在预览中）
      return '';
    }
    return it.replace(config.punReg,function(word){
      return word.substr(0,1);
    });
  });
  const splitNum = [index1,index2,index3,index4].find((i)=>i!=-1);
  const str1 = [...tmpArr].splice(0,splitNum).join("");
  const str2 = [...tmpArr].splice(splitNum).join("");
  return {str1:trimDots(str1),str2:trimDots(str2),index:index1};
}
//去掉开头的标点符号，最后的标点保留第一个,中间连续的保留第一个
function trimDots(str){
  if(!str)return'' ;
  return str.replace(config.punReg,function(word){
    return word.substr(0,1);
  }).replace(/^[,，.。:："“？?”；;、!！\s]+/,'').replace(/[,，.。:："“？?”；;、!！\s]*$/,'。');
}

//标签间连续标点只保留一个，保留前面一个
function formatContinueDots(data){
  let arr=[];
  arr=data&&data.filter((it,i)=>{
    if(i==0||(it.name&&(it.name.match(config.punctuationReg))||(data[i-1].name&&data[i-1].name.match(config.punctuationReg)))){
      return it;
    }
    if(!it.name){       //主诉现病史病情变化
      return it;
    }
  });
  return arr;
}

// 取消默认行为
function preventDefault(event) {
    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }
}

//ie8添加解除事件兼容
function windowEventHandler(type,func,dom){
    let win = dom?dom:window;
    if(win.addEventListener){
      win.addEventListener(type, func);
    }else{
      win.attachEvent('on'+type,func);
    }
}
function windowRemoveEventHandler(type,func,dom){
    let win = dom?dom:window;
    if(win.addEventListener){
      win.removeEventListener(type, func);
    }else{
      win.detachEvent('on'+type,func);
    }
}
//禁止回车事件
function handleEnter(event){
    event = event?event:window.event;
    if(event.keyCode==13){return false;}
}


// 获取参数value
function formatFormParmas(val,arr){
    let item = arr.length!==0 && arr.find(item=>{
       return item.id === val
    })
    return item.value
}
//获取病例输入的内容
function getEMRParams(){
  const state = store.getState();
  const { curHos } = state.homePage;
  const {message,patInfoData} = state.patInfo;
  const {
    mainSuit,
    currentIll,
    otherHistory,
    checkBody,
    inspect,
    assistCheck,
    diagnosticList,
    marriageHistory,
    pastHistory,
    personalHistory,
    familyHistory,
    menstruationHistory,
    newAdvice,
  } = state;
  const diag = [];
  for(let i = 0; i < diagnosticList.diagnosticList.length; i++) {
    diag.push({"dateValue": "","name": diagnosticList.diagnosticList[i].name,"uniqueName": ""})
  }
  if(diagnosticList.diagnosticList.length>0)diagnosticList.diseaseName.uniqueName = ''
  let templis = (inspect.labelListSmall).concat(inspect.labelListBig)
  templis = templis.filter((item)=>{
    if(!item.check){
      if(item.flg == 1){
        item.detailName = ""
      }
      if(curHos.hosId != -1){
        item.uniqueName = ''
      }
      return item
    }
  })
  let tempLisOrder = inspect.totalOrder
  tempLisOrder = tempLisOrder.filter((item)=>{
    if(item.flg == 1){
      item.detailName = ""
    }
    if(curHos.hosId != -1){
      item.uniqueName = ''
    }
    return item
  })
  let temppacs = assistCheck.assistLabel
  temppacs = temppacs.filter((item)=>{
    if(!item.check){
      if(curHos.hosId != -1){
        item.uniqueName = ''
      }
      return item
    }
  })
  let tempPacOrder = assistCheck.totalOrder
  tempPacOrder = tempPacOrder.filter((item)=>{
    if(curHos.hosId != -1){
      item.uniqueName = ''
    }
    return item
  })
  let tempdrug = newAdvice.labelListBig
  tempdrug = tempdrug.filter((item)=>{
    if(!item.check){
      if(curHos.hosId != -1){
        item.name = item.detailName
        item.uniqueName = ''
      }else{
        item.name = (item.uniqueName+(item.form||''))
      }
      return item
    }
  })
  let tempdrugorder = newAdvice.drugOrder
  tempdrugorder = tempdrugorder.filter((item)=>{
      if(curHos.hosId != -1){
        item.name = item.detailName
        item.uniqueName = ''
      }else{
        item.name = (item.uniqueName+(item.form||''))
      }
      return item
  })
  let tempoperation = newAdvice.labelListSmall
  tempoperation = tempoperation.filter((item)=>{
    if(!item.check){
      if(curHos.hosId != -1){
        item.uniqueName = ''
      }
      return item
    }
  })
  let tempOperationOrder = newAdvice.operationOrder
  tempOperationOrder = tempOperationOrder.filter((item)=>{
    if(curHos.hosId != -1){
      item.uniqueName = ''
    }
    return item
  })
  let tempOperationName = newAdvice.operationName
  if(curHos.hosId != -1&&tempOperationName.name){
    tempOperationName.uniqueName = ''
  }
  let tempblood = newAdvice.labelListBlood||[]
  tempblood = tempblood.filter((item)=>{
    if(!item.check){
      if(curHos.hosId != -1){
        item.uniqueName = ''
      }
      return item
    }
  })  
  let tempTransfusionOrder = newAdvice.transfusionOrder||[]
  tempTransfusionOrder = tempTransfusionOrder.filter((item)=>{
    if(curHos.hosId != -1){
      item.uniqueName = ''
    }
    return item
  })
  let sex = formatFormParmas('patientSex', patInfoData);
  const obj = {
    "hospitalId": curHos.hosId || '',
    "age": formatFormParmas('patientAge', patInfoData),
    "sex": sex,
    "deptName": formatFormParmas('hospitalDeptName', patInfoData),
    "chief": mainSuit.saveText[0]||'',    //主诉
    "symptom": currentIll.saveText[0]||'',  //现病史
    "vital": checkBody.saveText[0]||'',  //查体
    "pasts": pastHistory.saveText[0]||'',  //既往史
    // "pasts": filterDataArr(pastHistory.saveText)||'',  //既往史
    "marriage": '',
    "personal": personalHistory.saveText[0]||'',  //个人史
    "family": familyHistory.saveText[0]||'',  //家族史
    "marital": marriageHistory.saveText[0]||'',  //婚育史
    "menstrual": menstruationHistory.saveText[0]||'',  //月经史
    "diseaseName":diagnosticList.diseaseName,
    "otherIndex":diagnosticList.otherIndex,
    "operationName":tempOperationName,
    "infectious": "",
    "operation": tempoperation,
    "allergy": "",
    "vaccination": "",
    "other": filterDataArr(otherHistory.saveText)||'',
    "lisString": "",
    "pacsString": "",
    "diagString": "",
    "drugString": "",
    "lis": templis,
    "pacs": temppacs||[],
    "diag": diag,
    "lisOrder": tempLisOrder,
    "pacsOrder": tempPacOrder,
    "diagOrder": [],
    "drugOrder": tempdrugorder,
    "operationOrder": tempOperationOrder,
    "otherOrder": [],
    "patientId": message.patientId,
    "drug": tempdrug,
    'transfusion':tempblood,//输血
    'transfusionOrder':tempTransfusionOrder
  }
  if(sex !== 2){
    // 不是女性时,去除月经史
    obj.menstrual = '';
  }
  
  return obj;
};
function getMRInfo() {
  const state = store.getState();
  const {message} = state.patInfo;
  const {mainSuit,currentIll,otherHistory,checkBody,inspect,assistCheck,diagnosticList} = state;
  let diagStr = ""
  for(let i = 0; i < diagnosticList.diagnosticList.length; i++) {
    if(i == 0) {
      diagStr +=diagnosticList.diagnosticList[i].name
    } else {
      diagStr += ',' + diagnosticList.diagnosticList[i].name
    }
  }
  let str = `姓名: ${message.patientName}
            性别：${message.patientSex}
            年龄：${message.patientAge}
            主诉：${filterDataArr(mainSuit.saveText)}
            现病史：${filterDataArr(currentIll.saveText)}
            其他史：${filterDataArr(otherHistory.saveText)}
            查体：${filterDataArr(checkBody.saveText)}
            化验：${inspect.inspectStrPlus}
            辅检：${assistCheck.dataString}
            诊断：${diagStr}
            医师签名：${message.doctorName}`
  //let str = "姓　　名：姜** /r/n性 　 别：女/r/n年    龄：34岁/r/n民    族：汉族/r/n职    业：经商/r/n出 生 地：浙江省长兴县/r/n婚    姻：已婚/r/n联系地址：*** /r/n病史陈述者：患者本人/r/n入院日期：2019-12-04 10:12/r/n /r/n记录日期：2019-12-04 14:37/r/n /r/n主    诉: 腹痛1周 /r/n现 病 史: 患者1周前饮食辛辣食物后出现腹痛，主要为脐以上为主，呈持续性钝痛，无明显恶心呕吐，无肩背部疼痛，无咳嗽咳痰，无腹泻腹痛，无胸闷气促，无头晕头痛，无视物旋转，无异常阴道流血流液等情况，自诉近一周感下腹坠胀感，为求进一步诊治拟\"腹痛待查\"收住入院。/r/n患病来，神志清，精神软，胃纳差，睡眠一步，大小便如常，近期体重无明显改变。 /r/n既 往 史: 否认\"高血压，糖尿病，冠心病\"病史，否认\"肝炎，结核\"等传染病史，否认重大外伤史，否认手术史，否认输血史，既往存在头孢过敏，具体不详，否认长期药物使用史，否认药物成瘾，预防接种史不详。 /r/n个 人 史: 出生并生长于浙江省长兴县，经商，初中文化，否认疫区居住史，否认放射物、毒物、粉尘接触史，否认吸烟，否认饮酒，否认特殊嗜好，否认不洁性交史。 /r/n月 经 史: ，经量中等，颜色正常，无痛经，经期规律；白带量一般，性状无殊。 /r/n婚 育 史: 27岁结婚，否认近亲结婚，配偶健康状况良好，夫妻关系和睦,育有1女，均健康。/r/n家 族 史: 父亲体健，母已故（死因不详），有2哥，均体健，家族中无传染病及遗传病史,否认两系三代内遗传性、家族性疾病史，否认家族中有\"肝炎、结核\"等传染病史，否认两系三代内\"胃癌、肺癌\"等肿瘤病史，否认类似疾病史。 /r/n体格检查（一）/r/n /r/n一般状况：/r/n体温36.3℃，脉搏68次/分，呼吸19次/分，血压133/81mmHg。/r/n意识清晰，自主体位，面容无殊，体重56Kg，身高163cm，查体合作。 /r/n皮    肤：/r/n皮肤色泽正常，弹性好，未见明显水肿，未见皮疹，未见皮下出血，未见肝掌及蜘蛛痣。/r/n淋 巴 结：/r/n未触及明显浅表淋巴结肿大 /r/n头    部：/r/n外形大小正常，无畸形。听力粗测正常。眼睑正常，结膜正常，巩膜无黄染，瞳孔等大等圆，直径3mm，对光反射灵敏。鼻部外形正常，通气顺畅，副鼻窦区无压痛，乳突无压痛。口腔粘膜正常，扁桃体无肿大。/r/n颈　  部：/r/n颈软，无抵抗感，气管位置居中，颈静脉无怒张。/r/n胸　  部：/r/n外形正常，肋间隙正常，双侧乳房正常对称。/r/n肺    部：/r/n呼吸运动正常对称，双肺叩诊呈清音，呼吸音清晰，未闻及干、湿啰音。/r/n心    脏：/r/n心率68次/分，心律齐，心音有力，P2＜A2，各瓣膜听诊区未闻及杂音。 /r/n血    管：/r/n周围血管征阴性。 /r/n腹　　部：/r/n外形正常，未见肠形及蠕动波，腹壁松软，脐以上及下腹存在轻压痛，无反跳痛，/r/n包块未触及，肝脏肋下未触及，胆囊肋下未触及，脾脏肋下未触及，双肾区无叩痛，肠鸣音正常，3～5次/分，移动性浊音阴性。/r/n外生殖器：/r/n未见明显畸形 /r/n直肠肛门：/r/n未见明显畸形 /r/n四肢脊柱：/r/n脊柱无畸形，无压痛叩击痛，无放射痛，活动自如，四肢正常。/r/n神经系统：/r/n四肢肌张力正常，肌力V级，膝腱反射双侧正常，Babinski征双侧阴性。/r/n其    他：/r/n详见专科检查。/r/n/r/n体格检查（二）/r/n补 充 及 专 科 情 况/r/n体温36.3℃，脉搏68次/分，呼吸19次/分，血压133/81mmHg神志清，呼吸平稳，浅表淋巴结未及肿大，两肺呼吸音清，双下肺未闻及湿罗音，心率68次/分，律齐，未闻及病理性杂音，腹平软，脐以上及下腹存在轻压痛，无反跳痛，肝脾肋下未触及，双下肢无浮肿。/r/n /r/n /r/n心脏相对浊音界/r/n /r/n右界cm/r/n肋间/r/n左界cm/r/n/r/n 2/r/nⅡ/r/n 2/r/n/r/n 2/r/nⅢ/r/n 4/r/n/r/n 3/r/nⅣ/r/n 6/r/n/r/n /r/nⅤ/r/n 8/r/n/r/n左锁骨中线距胸骨中线  8 cm/r/n辅助检查: 2019-12-4 心电图未见明显异常。 /r/n /r/n初步诊断：1、腹痛待查 2.盆腔炎/r/n修正诊断：      /r/n       医师签名：李勇   /r/n                          /r/n2019-12-04         /r/n                /r/n补充诊断："
  let label = ["姓名","性别","年龄",
  "主诉","现病史","其他史","查体","化验","辅检",
  "诊断","医师签名"]
  const param = {
    "cid":0,
    "medrec": 
    [
        {
          "content": {
           "content":str
          },
          "label": label,
          "title": "入院记录"
        }
     
    ],
      "token": ""
    }
  
  return param
}

function didPushParamChange(){
  const emrData = getEMRParams();
  const oldParams = storageLocal.get('emrParam');
  
  const newParams = JSON.stringify(emrData);
  if(newParams === oldParams){
      return false;
  }
  return true;
}
//判断模板保存时文本数据是否为空
function isAllClear(jsonStr){
  if (      //结构化和文本数据都为空
    filterDataArr(JSON.parse(jsonStr.chief)) == '' &&
    filterDataArr(JSON.parse(jsonStr.present)) == '' &&
    filterDataArr(JSON.parse(jsonStr.other)) == '' &&           //这里都是filterDataArr不是filterArr，要去符号的
    filterDataArr(JSON.parse(jsonStr.vital)) == '' &&
    jsonStr.diag == '' &&
    jsonStr.lis == '' &&
    jsonStr.pacs == '' &&
    jsonStr.advice == ''
  ) {
    return false;
  }else{
    return true;
  }
}
//判断页面所有数据是否为空，包括空标签
function isAllPartClear(jsonData,jsonStr,baseList){
  if (      //结构化和文本数据都为空
    JSON.stringify(jsonData.advice) == '{}' &&
    jsonData.chief.length < 1 &&
    jsonData.present.length < 1 &&
    // jsonData.other.length < 1 && 
    (jsonData.other.length > 0 ? baseList.otherHistory.isEmpty : true) &&
    //jsonData.vital.length < 1 &&
    (jsonData.vital.length > 0 ? baseList.checkBody.isEmpty : true) &&
    jsonData.diag.length < 1 &&
    jsonData.checkedListImport.length < 1 &&
    jsonData.pacs.length < 1 &&
    jsonData.lis.labelList.length < 1 &&
    jsonData.lis.getExcelDataList.length < 1 &&
    filterDataArr(JSON.parse(jsonStr.chief)) == '' &&
    filterDataArr(JSON.parse(jsonStr.present)) == '' &&
    filterDataArr(JSON.parse(jsonStr.other)) == '' &&           //这里都是filterDataArr不是filterArr，要去符号的
    filterDataArr(JSON.parse(jsonStr.vital)) == ''
  ) {
    return false;
  }else{
    return true;
  }
}
//判断除主诉外页面数据是否为空--慢病模板
function ifOtherClear(jsonData,jsonStr,baseList){
  if (      //结构化和文本数据都为空
    JSON.stringify(jsonData.advice) == '{}' &&
    jsonData.present.length < 1 &&
    (jsonData.other.length > 0 ? baseList.otherHistory.isEmpty : true) &&
    (jsonData.vital.length > 0 ? baseList.checkBody.isEmpty : true) &&
    jsonData.diag.length < 1 &&
    jsonData.pacs.length < 1 &&
    jsonData.lis.labelList.length < 1 &&
    jsonData.lis.getExcelDataList.length < 1 &&
    filterDataArr(JSON.parse(jsonStr.present)) == '' &&
    filterDataArr(JSON.parse(jsonStr.other)) == '' &&           //这里都是filterDataArr不是filterArr，要去符号的
    filterDataArr(JSON.parse(jsonStr.vital)) == ''
  ) {
    return false;
  }else{
    return true;
  }
}
function normalVal(min,max){//添加正常值0处理
  if(!min&&!max){
    return null;
  }else if(min&&max){
      return `正常值：(${min}~${max})`
  }else if(!min && max){
    if(min == 0){
      return `正常值：(${min}~${max})`
    }
    return `正常值：(<${max})`
  }else if(min && !max){
    if(max == 0){
      return `正常值：(${min}~${max})`
    }
      return `正常值：(>${min})`
  }
}
/**
 * 
 * @param {弹窗显示位置是否往下设置} stic 
 */
function getPageCoordinate(event,stic){//获取鼠标点击的位置
    let e = event || window.event;
    var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
    var x = e.pageX || (e.clientX + scrollX);
    var y = (e.pageY+(stic?25:0)) || (e.clientY + scrollY + (stic?25:0));//弹窗位置偏下25
    let obj = {
      boxLeft : x ,
      boxTop : y+18
    }
    return obj;
}
function timestampToTime(timestamp) {     //excel导入2019年5月1日会转换成时间戳
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y+M+D+h+m+s;
}

function timesYMDTime(timestamp) {
  //excel导入2019年5月1日会转换成时间戳
  var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  // var D = date.getDate() ;
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); ;
  return Y + M + D 
}

/**
 * 
 * @param {需要年月日传个true，不需要不传或者false} flg 
 */
function getCurrentDate(flg,con){
  let link = con?con:'-'
  let myDate = new Date();
  let year = myDate.getFullYear();       //获取完整的年份(4位,1970-????)
  let mon = myDate.getMonth()-0+1;       //获取当前月份(0-11,0代表1月)
  let day = myDate.getDate();            //获取当前日(1-31)
  let date = '';           
  if(flg){
    var h = myDate.getHours();
    var m = myDate.getMinutes();
    var s = myDate.getSeconds();
    date = year+link+(mon<10?("0"+mon):mon)+link+(day<10?("0"+day):day)+' '+(h<10?("0"+h):h)+':'+(m<10?("0"+m):m)+':'+(s<10?("0"+s):s);
  }else{
    date = year+link+(mon<10?"0"+mon:mon)+link+(day<10?"0"+day:day);
  }
  return date;
}
function inspectAndAssist(){
  const state = store.getState();
  let mainType = state.typeConfig.mode
  if(mainType == 1){return}//文本模式不放化验辅检的模板
  let tmpAll = state.homePage.allModules;
  let tmpInspected = state.inspect.labelList;
  let tmpAssisted = state.assistCheck.assistLabel;
  let tmpInspect = [],tmpAssist = [],assayArr = [],tmpDetail=[],checkArr = [];
  for(let i = 0;i < tmpAll.length;i++){
    let tmpItem = tmpAll[i];
    if(tmpItem.type == 5){
      tmpInspect = tmpItem.moduleDetailDTOList || []
    }else if(tmpItem.type == 6){
      tmpAssist = tmpItem.moduleDetailDTOList || []
    }
  }
  for(let i = 0;i < tmpInspect.length;i++){//化验数据处理
    let tmpObj = {   //添加化验
      details: [],
      name: '',
      questionId: '',
      showType: 1,
      uniqueName:''
    }
    if (tmpInspect[i].controlType == 0) {
      tmpDetail = tmpInspect[i].questionMapping
    }else if(tmpInspect[i].controlType == 1 || tmpInspect[i].controlType == 6){
      tmpDetail = new Array(tmpInspect[i])
    }
    tmpObj.questionId = tmpInspect[i].id
    tmpObj.name = tmpInspect[i].name
    tmpObj.details = tmpDetail
    tmpObj.uniqueName = tmpInspect[i].uniqueName || ''
    assayArr.push(tmpObj)
  }
  for(let i = 0;i < tmpAssist.length;i++){//辅检数据处理
    let tmpObj = {  //添加辅检
      name: '',
      questionId: '',
      showType: 1,
      time:getCurrentDate(1),
      value:''
    }
    tmpObj.questionId = tmpAssist[i].id
    tmpObj.name = tmpAssist[i].name
    checkArr.push(tmpObj)
  }
  if(assayArr.length>0 && tmpInspected.length == 0){//化验
    store.dispatch(addLabel(assayArr))
  }
  if(checkArr.length > 0 && tmpAssisted.length == 0){//辅检
    store.dispatch(addAssistLabel(checkArr))
  }
}
function readyKeepHistory(){
  let baseList = store.getState();
  const {
    patInfo: { patInfoData },
  } = baseList;
  let jsonStr = getAllDataStringList(baseList);
  let patientName = formatFormParmas('patientName', patInfoData);  // 姓名
  let patientAge = formatFormParmas('patientAge', patInfoData);  // 年龄
  let patientIdNo = formatFormParmas('patientIdNo', patInfoData);  // 卡号
  let hospitalDeptName = formatFormParmas('hospitalDeptName', patInfoData);  // 科室
  let doctorName = formatFormParmas('doctorName', patInfoData);  // 医生
  let recordId = formatFormParmas('recordId', patInfoData);  // 门诊号
  // console.log(patientAge, typeof patientAge,'patientAge================');
  if(filterDataArr(JSON.parse(jsonStr.chief)) == ''){
      return 1;//主诉不能为空
  }
  if(patientName === '') {
    return 2
  }
  if (patientAge === '') {
    return 3;
  }
  if (patientIdNo === '') {
    return 4;
  }
  if (hospitalDeptName === '') {
    return 5;
  }
  if (doctorName === '') {
    return 6;
  }
  if (recordId === '') {
    return 7;
  }

  if (+patientAge > 200) {
    return 8;
  }
  // }else if(!jsonStr.diag || jsonStr.diag.trim().length < 1){
  //     return 2;//诊断不能为空
  // }else{
  //   return 3;
  // }
}
//评估图表数据转换
function parseChartData(indexData){
  let arr=[],obj={},temp={};
  let nameArr=[],nameObj={};
  if(!indexData){
    return [];
  }
  indexData.indexData.map((it)=>{
    temp=indexData.indexConfigData.find((i)=>{return it.uniqueId==i.uniqueId});
    arr=obj[temp.groupType]||[];
    nameArr=nameObj[temp.groupType]||[];
    obj[temp.groupType]=[...arr,it];
    nameObj[temp.groupType]=[...nameArr,it.itemName];
  });
  //nameObj,obj;
  return {nameObj,obj};
}

// 时间戳转换日期
function dateParser(timestamp,link = '-'){
  let time = new Date(timestamp);
  let year = time.getFullYear();
  let month = time.getMonth()+1;
  let date = time.getDate();
  let hour = time.getHours();
  let minute = time.getMinutes();
  let second = time.getSeconds();
  // let result = year+link+month+link+date;
  let result = year+link+(month<10?"0"+month:month)+link+(date<10?"0"+date:date)+' '+(hour<10&&hour!=0?"0"+hour:hour)+':'+(minute<10&&minute!=0?"0"+minute:minute)+':'+(second<10&&second!=0?"0"+second:second);
  return result;
}

//获取组合组件已填文字填入saveText
function getSaveText(data){//console.log(data)
  const hasValue = data.questionMapping.findIndex((it)=>it.value!==undefined)!==-1;   //有值时血压类型中文本标签要加入值
  const arr = data.questionMapping.map((it)=>{
    return it.value?(it.labelPrefix||'')+(it.value||'')+(it.labelSuffix||''):(hasValue&&!notTextLabel(it)?it.name:'');
  });
  return arr.join('');
}

//添加自由文本标签
function notTextLabel(label){
  return +label.tagType!==8;
}
/*
* 给标签组添加自由文本标签
* 入参：arr源数组，
*       noPre是否不添加前置文本标签，默认false即添加
*       noEnd是否不添加后置文本标签，默认false即添加
*  出参：newArr添加自由文本标签后的数据Array,
*        saveText添加自由文本后对应的预览数据Array,
* */
function fullfillText(arr,noPre=false,noEnd=false,boxMark){
  let newArr =[],
    pre={},
    textLabel={},
    notText = true,
    saveText=[],
    tempText = '',
    value = '',
    cNum = 0;
  Array.isArray(arr)&&arr.map((it,i)=>{
    notText = notTextLabel(it);
    cNum = i;
    value = it.value||'';
    textLabel = JSON.parse(config.textLabel);
    //n个显示的标签最后一个标签后面要落关标，所以+1
    if(i===0){
      //第一个标签不是文本标签时在前面添加文本标签
      if(!noPre&&notText){
        newArr.push(textLabel);
        saveText.push('');
      }
      newArr.push(it);
      if(it.tagType == 6||it.tagType == 2){
        tempText = getDefaultedSaveText(it,boxMark);
      }else if(it.tagType == 3){
        tempText = getSaveText(it);
      }else{      //非血压类组合标签
        tempText = value?it.labelPrefix+value+it.labelSuffix:'';
        tempText = notText?tempText:it.value||it.name;
      }
      saveText.push(tempText);
      // 模板只有一个标签时第一项后面也要加空标签
      if(arr.length==1&&notText){
        newArr.push(JSON.parse(config.textLabel));
        saveText.push('');
      }
    }else{
      pre = arr[i-1];
      //如果本身不是文本标签且前面一个也不是文本标签,该标签前面添加文本标签
      if(notTextLabel(pre)&&notText){
        newArr.push(textLabel,it);
        if(it.tagType == 6||it.tagType == 2){
          tempText = getDefaultedSaveText(it,boxMark);
        }else if(it.tagType == 3){
          tempText = getSaveText(it);
        }else{
          tempText = value ? it.labelPrefix + value + it.labelSuffix : '';
        }
        saveText.push("",tempText);
      }else{    //本身是或者前面是文本标签时，前面不添加文本标签
        newArr.push(it);
        if(it.tagType == 6||it.tagType == 2){
          tempText = getDefaultedSaveText(it,boxMark);
        }else if(it.tagType == 3){
          tempText = getSaveText(it);
        } else{
          tempText = value ? it.labelPrefix + value + it.labelSuffix : '';
          tempText = notText ? tempText : (it.value || it.value == "" ? it.value : it.name);
        }
        saveText.push(tempText);
      }
      if(notText&&!noEnd&&i===arr.length-1){//最后一个非文本标签，后面添加一个文本标签
        //不能用上面的变量textLabel，因为上一个if可能也进了，这样就是同一个对象，值改变时会同步
        newArr.push(JSON.parse(config.textLabel));
        saveText.push("");
      }
    }
  });
  return {newArr,saveText};
};

function getDefaultedSaveText(it,boxMark){
  const state = store.getState();
  const {readConfig,typeConfig}=state.typeConfig;
  const hasReadMode = readConfig!==-1;
  const curOtherMode =hasReadMode&&readConfig[2]!==null?readConfig[2]:typeConfig[2];
  const curMode =hasReadMode&&readConfig[1]!==null?readConfig[1]:typeConfig[1];
  const otherDefault=+curOtherMode===1;
  const curDefault=+curMode===1;
  const defaulted = (((boxMark=='2'&&curDefault)||(boxMark=='3'&&otherDefault)))&&it.selFlag=='1'&&it.value===undefined;
  const ext = it.questionMapping.filter((i)=>{
    return +i.exclusionType===1;
  });
  const text = ext.length>0&&defaulted?ext[0].questionDetailList[0].name:'';
  //console.log(state);
  return text;
}

/*
 * 查体添加自由文本标签函数
 * 默认标签直接添加,
 * 前config.showCheckNum个源数据标签默认显示，剩余隐藏收起
 *  入参：arr源数组，
 *       noPre是否不添加前置文本标签，默认false即添加
 *       noEnd是否不添加后置文本标签，默认false即添加
 *  showInCheck是否默认在查体中展开
 *  出参：newArr添加自由文本标签后的数据Array,
 *        saveText添加自由文本后对应的预览数据Array,
 *        checkHiddenDefault查体是否全部标签展开
 *
 * */
function checkFullfillText(arr,noPre=false,noEnd=false){
  let newArr =[],
    pre={},
    textLabel={},
    notText = true,
    saveText=[],
    tempText = '',
    value = '',
    item={},
    checkHiddenDefault=false;
  arr&&arr.map((it,i)=>{
    notText = notTextLabel(it);
    value = it.value||'';
    //textLabel = i==0?JSON.parse(config.textLabel):Object.assign({},JSON.parse(config.textLabel),{showInCheck:true});
    //n个显示的标签最后一个标签后面要落关标，所以+1
    //_textLabel = !ifEmpty&&cNum<config.showCheckNum+1?Object.assign({},JSON.parse(config._textLabel),{showInCheck:true}):JSON.parse(config._textLabel);
    if(i===0){
      textLabel = Object.assign({},JSON.parse(config.textLabel),{showInCheck:true});
      //第一个标签不是文本标签时在前面添加文本标签
      if(!noPre&&notText){
        newArr.push(textLabel);
        saveText.push('');
      }
      item = Object.assign({},it,{showInCheck:true});
      newArr.push(item);
      if(it.tagType != 3){
        tempText = value?it.labelPrefix+value+it.labelSuffix:'';
        tempText = notText?tempText:it.value||it.name;
      }else{
        tempText = getSaveText(it);
      }
      saveText.push(tempText);
      // 模板只有一个标签时第一项后面也要加空标签
      if(arr.length==1&&notText){
        newArr.push(textLabel);
        saveText.push('');
      }
    }else{
      pre = arr[i-1];
      item = i<config.showCheckNum?Object.assign({},it,{showInCheck:true}):it;
      //判断单选项是否有默认选中，位置在隐藏区域时，查体所有标签展示
      if(!checkHiddenDefault&&i>config.showCheckNum&&+it.tagType===1&&(+it.controlType===0||+it.controlType===1)){
        if(it.questionDetailList.find((it)=>it.defaultSelect=='1')){
          checkHiddenDefault=true;
        }
      }
      //如果本身不是文本标签且前面一个也不是文本标签,该标签前面添加文本标签
      if(notTextLabel(pre)&&notText){
        textLabel = Object.assign(JSON.parse(config._textLabel),{showInCheck:i-1<config.showCheckNum?true:false});
        newArr.push(textLabel,item);

        if(it.tagType != 3) {
          tempText = value ? it.labelPrefix + value + it.labelSuffix : '';
        }else{
          tempText = getSaveText(it);
        }
        saveText.push("",tempText);
      }else{    //本身是或者前面是文本标签时，前面不添加文本标签
        newArr.push(item);
        if(it.tagType != 3) {
          tempText = value ? it.labelPrefix + value + it.labelSuffix : '';
          tempText = notText ? tempText : (it.value || it.value == "" ? it.value : it.name);
        }else{
          tempText = getSaveText(it);
        }
        saveText.push(tempText);
      }
      if(notText&&!noEnd&&i===arr.length-1){//最后一个非文本标签，后面添加一个文本标签
        const _text = Object.assign(JSON.parse(config.textLabel),{showInCheck:arr.length>config.showCheckNum?false:true});
        newArr.push(_text);
        saveText.push("");
      }
    }
  });
  return {newArr,saveText,checkHiddenDefault};
}


//获取标签index,入参：病例项index+标签index+标签内index
function getLabelIndex(index){
  let ikey = index.split('-')[1];
  return ikey;
};

function getWindowInnerHeight(){
  if(window.innerHeight!=undefined){
    return window.innerHeight;
  }else{
    let by = document.body, ele = document.documentElement;
    return Math.min(by.clientHeight,ele.clientHeight);
  }
};
function getWindowInnerWidth(){
  let width = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth
  return width
};

function getIds(data){
  let ids = [];
  data&&data.forEach((it,i)=>{
    ids.push(it.id);
  })
  return ids;
}
/**
 * 
 * @param {日期相关} info 
 * @param {时间是否包含时分秒} flg 
 * @param {连接符} con 
 */
function getCalendarDate(info) {
  let conect = '-';
  let date = info.year + conect + (info.month < 10 ? '0' + info.month : info.month) + conect + (info.day < 10 ? '0' + info.day : info.day) + ' '+ (info.hour != 0&&(info.hour).toString().length<2 ? '0' + info.hour : info.hour)+':'+ (info.minute != 0&&(info.minute).toString().length<2 ? '0' + info.minute : info.minute)+':'+ (info.second&&(info.second).toString().length<2 ? '0' + info.second : info.second);
  return date;
}

// 导出
function downloadExportedData(data, fileName) {
    // var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //type表示xlsx类型
    var blob = new Blob([data], {type: 'application/vnd.ms-excel;charset=UTF-8'}); //type表示xlsx类型
    var href = window.URL.createObjectURL(blob);//创建下载的链接
    // 为兼容FF26 （不支持a标签的模拟点击事件）
     if (navigator.userAgent.indexOf("Firefox") > -1){
        //window.open(requestUrl);
        window.location.href = href;
     }else {
        var downloadElement = document.createElement('a');
        downloadElement.href = href;
        downloadElement.download = fileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href);
     }
    
}

function getStatusImg(type,val,status){
  if(type == 0){//正常
    return <span>{val} </span>
  }else if(type == 1){//异常（表单输入的话非数字显示为异常）
    return <span className={'red'}>{val} </span>
  }
  if(status == 1){
    if(type == 2){
      return <span style={{color:'#FF5D5D'}}>{val}<img src={up} alt=""/> </span>
    }else if(type == 3){
      return <span style={{color:"#D949FF"}}>{val}<img src={down} alt=""/> </span>
    }
  }else{
    if(type == 2){
      return <span>{val}<img src={up} alt=""/> </span>
    }else if(type == 3){
      return <span>{val}<img src={down} alt=""/> </span>
    }
  }
}
function getDomUpDown(min,max,value){
  let dom = '';
  if(min == null&&max == null||min == undefined&&max == undefined||min == ''&&max == ''){
    dom = getStatusImg(0, value, 1)
  }else if (!isNaN(min) && !isNaN(max) &&min!=null&&max!=null) {//有最大值最小值
    if (isNaN(value)) {//输入的不是数据
      dom = getStatusImg(1, value, 1)
    } else if (value <= min) {//下降
      dom = getStatusImg(3, value, 1)
    } else if (value >= max) {//上升
      dom = getStatusImg(2, value, 1)
    } else {//正常
      dom = getStatusImg(0, value, 1)
    }
  } else if (min==null && !isNaN(max)&&max!=null) {//有最大值无最小值
    if (value >= max) {//上升
      dom = getStatusImg(2, value, 1)
    } else if(isNaN(value)){
      dom = getStatusImg(1, value, 1)
    }else {//正常
      dom = getStatusImg(0, value, 1)
    }
  } else if (!isNaN(min) && max==null&&min!=null) {//有最小值无最大值
    if (value <= min) {//下降
      dom = getStatusImg(3, value, 1)
    } else if(isNaN(value)){
      dom = getStatusImg(1, value, 1)
    }else {//正常
      dom = getStatusImg(0, value, 1)
    }
  } else {//无最大最小值(中文))
    dom = getStatusImg(1, value, 1)
  }
  return dom;
}
function getArrow(min,max,value){//1下降2上升3正常4标红
  let dom = 3;
  if(min == null&&max == null||min == undefined&&max == undefined||min == ''&&max == ''||value == null||value == undefined){
    dom = 3
  }else if (!isNaN(min) && !isNaN(max) &&min!=null&&max!=null) {//有最大值最小值
    if (isNaN(value)) {//输入的不是数据
      dom = 4
    } else if (value <= min) {//下降
      dom = 1
    } else if (value >= max) {//上升
      dom = 2
    } else {//正常
      dom = 3
    }
  } else if (min==null && !isNaN(max)&&max!=null) {//有最大值无最小值
    if (value >= max) {//上升
      dom = 2
    } else if(isNaN(value)){
      dom = 4
    }else {//正常
      dom = 3
    }
  } else if (!isNaN(min) && max==null&&min!=null) {//有最小值无最大值
    if (value <= min) {//下降
      dom = 1
    } else if(isNaN(value)){
      dom = 4
    }else {//正常
      dom = 3
    }
  } else {//无最大最小值(中文))
    dom = 3
  }
  return dom;
}
//键值对转换
function parseNameVal(arr){
  let obj = {};
  Array.isArray(arr)&&arr.map((it)=>{
    obj[it.code]=it.value;
  });
  return obj;
}
//化验数据处理
function getStringPlus(dataList){
  let strPlus = '';
  dataList && dataList.map((item)=>{
    if(item.detailName){
      let strTmp = item.name + ','+ item.detailName + ',' + (item.otherValue ? item.otherValue : (item.value + item.units)) +';'
      // let strTmp = item.name + ','+(item.inpValue?(item.inpValue+','):'') + item.detailName + ',' + (item.otherValue ? item.otherValue : (item.value + item.units)) +';'
      strPlus += strTmp;
    }else{
      // let strTmp = item.name+ (item.inpValue?(','+item.inpValue):';')
      let strTmp = item.name+ ';'
      strPlus += strTmp;
    }
  })
  return strPlus;
}
/**
 * 
 * @param {data1}  excel导入的数据 getExcelDataList
 * @param {data2}  填写单数据 labelList
 */
function getPushList(data1,data2){     //推送数据
    let tmpArr1 = [];
    let tmpArr2 = [];
    let totalTmpArr = [];
    const now = dateParser(new Date());
    data1.length>0 && data1.map((items)=>{    //excel导入的数据拼接
        items.lisExcelRes.map((item)=>{
            item.lisExcelItem.map((part)=>{
                let tmpObj = {};
                tmpObj.name = part.mealName || '';//套餐名
                tmpObj.detailName = part.itemName || '';//化验项名
                tmpObj.uniqueName = part.uniqueName || '';//公表名称
                tmpObj.source = '1';//数据来源
                tmpObj.maxValue = part.max || ''; 
                tmpObj.minValue = part.min || '';
                tmpObj.dateValue = part.time ||now;
                tmpObj.units = part.unit || '';//单位
                tmpObj.value = (part.value-0) === (part.value-0) ? part.value:'';//值
                tmpObj.otherValue = (part.value-0) === (part.value-0) ?'':part.value; //阴性阳性
                tmpArr1.push(tmpObj);
            })
        })
    })
    data2.length>0 && data2.map((item)=>{        //填写单数据拼接
      item.details && item.details.map((val)=>{
            if(val.value != undefined && val.value != ''){
                let tmpObj = {};
                tmpObj.name = item.name || '';
                tmpObj.detailName = val.name || '';
                tmpObj.uniqueName = val.uniqueName || '';//公表名称
                tmpObj.source = '0';     //数据来源
                tmpObj.maxValue = val.maxValue ? val.maxValue : '';
                tmpObj.minValue = val.minValue ? val.minValue : '';
                tmpObj.dateValue = val.time || now;
                tmpObj.units = val.labelSuffix || '';
                tmpObj.value = (val.value-0) === (val.value-0) ? val.value:'';
                tmpObj.otherValue = (val.value-0) === (val.value-0) ?'':val.value;
                tmpArr2.push(tmpObj);
            }
        })
    })
    totalTmpArr = tmpArr1.concat(tmpArr2);
    return totalTmpArr;
}
function getPushLists(data1,data2){     //推送数据
    let tmpArr1 = [];
    let tmpArr2 = [];
    let totalTmpArr = [];
    data1.length>0 && data1.map((items)=>{    //excel导入的数据拼接
        items.lisExcelRes.map((item)=>{
            item.lisExcelItem.map((part)=>{
                let tmpObj = {};
                tmpObj.name = part.mealName || '';//套餐名
                tmpObj.detailName = part.itemName || '';//化验项名
                tmpObj.uniqueName = part.uniqueName || '';//公表名称
                tmpObj.source = '1';//数据来源
                tmpObj.maxValue = part.max || ''; 
                tmpObj.minValue = part.min || '';
                tmpObj.units = part.unit || '';//单位
                tmpObj.value = (part.value-0) === (part.value-0) ? part.value:'';//值
                tmpObj.otherValue = (part.value-0) === (part.value-0) ?'':part.value; //阴性阳性
                tmpArr1.push(tmpObj);
            })
        })
    })
    data2.length>0 && data2.map((item)=>{        //填写单数据拼接
      if(item.show){
          item.details.map((val)=>{
            if(val.value != undefined && val.value != ''){
                let tmpObj = {};
                tmpObj.name = item.name || '';
                tmpObj.inpValue = item.inpValue || '';//套餐名
                tmpObj.detailName = val.name || '';
                tmpObj.uniqueName = val.uniqueName || '';//公表名称
                tmpObj.source = '0';     //数据来源
                tmpObj.maxValue = val.maxValue ? val.maxValue : '';
                tmpObj.minValue = val.minValue ? val.minValue : '';
                tmpObj.units = val.labelSuffix || '';
                tmpObj.value = (val.value-0) === (val.value-0) ? val.value:'';
                tmpObj.otherValue = (val.value-0) === (val.value-0) ?'':val.value;
                tmpArr2.push(tmpObj);
            }
        })
      }else{
        let tmpObj = {};
        tmpObj.name = item.name;
        tmpObj.inpValue = item.inpValue;
        tmpArr2.push(tmpObj);
      }
    })
    totalTmpArr = tmpArr1.concat(tmpArr2);
    return totalTmpArr;
}

function getAllString(checkedListImport,assistLabel,flg){
  let tmpImportLis = [],tmpString='',tmpArr=[],tmpObj={};
  for(let i = 0;i < checkedListImport.length;i++){
    for(let j = 0;j < checkedListImport[i].length;j++){
      tmpImportLis.push(checkedListImport[i][j])
    }
  }
  let tempArr = tmpImportLis.concat(assistLabel)
  for (let i = 0; i < tempArr.length; i++) {
    let tmpVal = tempArr[i].value ? tempArr[i].value.trim() : tempArr[i].value;
    let obj = {
      "dateValue": tempArr[i].time||"",
      "name": "",
      "uniqueName": tempArr[i].name||"",
      "desc": tempArr[i].value||"",
      "result": tempArr[i].value||"",
    }
    tmpArr.push(obj)
    // tmpString += (tempArr[i].name + (tmpVal ? ('：' + tmpVal) + ', ' : '：') + (tempArr[i].time ? '报告日期：' + tempArr[i].time : '') + '^;')
    tmpString += (tempArr[i].name + (tmpVal ? ('：' + tmpVal) + ', ' : '：') + (tempArr[i].time ? tempArr[i].time : '') + '^;')
  }
  return tmpObj = {
    arr:tmpArr,
    str:tmpString
  }
  // if(flg){
  //   return tmpArr;
  // }else{
  //   return tmpString;
  // }
}

// 模板中处理tagType==4的数据
function resetTagtype(data){
  let newDataArr = [];
  if(data&&data.length>0){
    for(let i=0; i<data.length;i++){
      if(data[i].tagType==4){
        newDataArr.push(...data[i].questionMapping);
      }else{
        newDataArr.push(data[i]);
      }
    }
  }
  return newDataArr;
}

//记录最近3次被删除的标签
function handleLocalDelTag(mark,index,tag){
  const deledTag =  localStorage.getItem('deletedTags')?JSON.parse(localStorage.getItem('deletedTags')):[];
  if(tag.tagType){
    deledTag.unshift(Object.assign({},tag,{delIndex:mark+'-'+index}));
  }else{
    deledTag.unshift({tags:tag,delIndex:mark+'-'+index});
  }
  deledTag.length = deledTag.length>config.recoverTagNum?config.recoverTagNum:deledTag.length;
  localStorage.setItem('deletedTags',JSON.stringify(deledTag));
}

//删除被恢复的标签
function shiftLocalDelTag(){
  const deledTags = localStorage.getItem('deletedTags')?JSON.parse(localStorage.getItem('deletedTags')):[];
  deledTags.shift();
  localStorage.setItem('deletedTags',JSON.stringify(deledTags));
}
//弹窗显示问题
function setPosition (e,dom,setHighter){
  const isBlock = store.getState().typeConfig.typeConfig[0]===2;    //自由模式
  setTimeout(()=>{
    const contHt =$(dom).height();
    const $dom = isBlock?$("#EmrBlockContainer"):$("#EmrContainer");
    const wrapHt = $dom.height();//滚动区域高度
    const clickHt = getPageCoordinate(e).boxTop;//点击高度
    const scrollHt = Math.abs(parseFloat(document.documentElement.scrollTop || document.body.scrollTop)) //滚动的距离
    let btmHt = $(window).height()-(clickHt-scrollHt);//点击位置距离底部的距离
    // console.log('滚动区域高度:',wrapHt,' 点击高度:',clickHt,' 滚动区滚动的距离',scrollHt,'点击距离底部',btmHt,$(e.target).html())
    if(btmHt<300){
      if(btmHt<200&&$(e.target).html()=='添加检验项'){
        setHighter&&setHighter(48);
      }else{
        setHighter&&setHighter(400-btmHt);
      }
      $(e.target)[0].scrollIntoView();
    }else{
      setHighter&&setHighter(48);       //标签填写单连续点击弹出，未超出需要恢复
    }
  },10);
}

function moveEnd(obj,flg) {
  if(window.getSelection){//ie11 10 9 ff safari
    setTimeout(() => {
      obj.focus(); //解决ff不获取焦点无法定位问题
      var range = window.getSelection();//创建range
      range.selectAllChildren(obj);//range 选择obj下所有子内容
      if(flg){
        range.collapseToStart();//光标移至开头
      }else{
        range.collapseToEnd();//光标移至最后
      }
    }, 0);
  }
  else if (document.selection) {//ie10 9 8 7 6 5
    var range = document.selection.createRange();//创建选择对象
    range.moveToElementText(obj);//range定位到obj
    if(flg){
      range.collapse(true);//光标移至开头
    }else{
      range.collapse(false);//光标移至最后
    }
    range.select();
  }
}
/**
 * 获取样式类名
 * largeFontSize 18px      middleFontSize 16px（暂无）       simpleFontSize 14px
 * flg  1标准字体时颜色加深，可以让选中的字体加粗
 *      2体征颜色单独处理不需要设置
 */
const setFontColorSize = (flg,pacs) => {
    const classNameSelect = ['largeFontSize','middleFontSize','simpleFontSize','simpleLightColor','simpleColor','selectColor']
    const state = store.getState();
    let readConfig = state.typeConfig.readConfig
    let mainType = readConfig==-1?state.typeConfig.typeConfig:readConfig;
    let font = mainType[3],colour = mainType[4],classStr = '';
    if(font == 1&&colour == 1){//字体加大颜色加深
      if(flg == 2){
        if(pacs == 1){
          classStr = `largeFontSize pdright`
        }else if(pacs == 2){
          classStr = `largeFontSize widthChangeed`
        }else if(pacs == 3){
          classStr = `largeFontSize middleImg`
        }else if(pacs == 4){
          classStr = `largeFontSize titleWidth`
        }else if(pacs == 5){
          classStr = `largeFontSize specialSize`
        }else if(pacs == 6){
          classStr = `largeFontSize selectColor`
        }else if(pacs == 7){
          classStr = `largeFontSize fontWeight selectColor`
        }else if(pacs == 8){
          classStr = `largeFontSize selectColor`
        }else{
          classStr = `largeFontSize`
        }
      }else if(flg == 1){
        classStr = `selectColor largeFontSize`
      }else{
        classStr = `selectColor largeFontSize`
      }
    }else if(font == 0&&colour == 1){//标准字体颜色加黑
      if(flg == 2){
        if(pacs == 6){
          classStr = `simpleFontSize selectColor`
        }else if(pacs == 7){
          classStr = `simpleFontSize fontWeight selectColor`
        }else if(pacs == 8){
          classStr = `simpleFontSize selectColor`
        }else{
          classStr = `simpleFontSize`
        }
      }else if(flg == 1){
        classStr = `selectColor simpleFontSize`
      }else{
        classStr = `selectColor simpleFontSize`
      }
    }else if(font == 1&&colour == 0){//大字体标准颜色
      if(flg == 2){
        if(pacs == 1){
          classStr = `largeFontSize pdright`
        }else if(pacs == 2){
          classStr = `largeFontSize widthChangeed`
        }else if(pacs == 3){
          classStr = `largeFontSize middleImg`
        }else if(pacs == 4){
          classStr = `largeFontSize titleWidth`
        }else if(pacs == 5){
          classStr = `largeFontSize specialSize`
        }else if(pacs == 6){
          classStr = `largeFontSize`
        }else if(pacs == 8){
          classStr = `simpleColor largeFontSize`
        }else if(pacs == 7){
          classStr = `largeFontSize fontWeight`
        }else{
          classStr = `largeFontSize`
        }
      }else if(flg == 1){
        classStr = `simpleLightColor largeFontSize`
      }else{
        classStr = `simpleColor largeFontSize`
      }
    }else{//都是标准的
      if(flg == 2){
        if(pacs == 7){
          classStr = `simpleFontSize fontWeight`
        }else if(pacs == 6){
          classStr = `simpleFontSize`
        }else if(pacs == 8){
          classStr = `simpleColor simpleFontSize`
        }else if(pacs == 7){
          classStr = `simpleFontSize fontWeight`
        }else{
          classStr = `simpleFontSize`
        }
      }else if(flg == 1){
        classStr = `simpleLightColor simpleFontSize`
      }else{
        classStr = `simpleColor simpleFontSize`
      }
    }
    return classStr;
}

//获取生命体征或非生命体征标签  
function getLifeLabels(arr,flag){     //flag=true获取非生命体征
  const newArr = arr.filter((it)=>{
    return flag?+it.specFlag!==4:+it.specFlag===4;
  });
  return newArr;
}

//获取已选中的标签
function getValuedLabels(arr){
  const newArr = arr.filter((it)=>{
    if(it.tagType=='3'){      //血压类型
      if(+it.specFlag!==4&&it.questionMapping.findIndex((i)=>i.value!==undefined)!==-1){
        return true;
      }
      return false;
    }
    return +it.specFlag!==4&&it.value;
  });
  return newArr;
}

//对象数组去重
function removeRepeat(arr1,arr2){     //arr1被完全保留的数组
  const arr = arr2.reduce(function(newArr,item,inx){
    const it = newArr.findIndex((i)=>i.id===item.id);
    const firstInx = arr2.findIndex((i)=>i.id===item.id);
    //旧体征标签比新体征标签多出的标签，已填值的保留，未填值的舍弃
    if(it!==-1){
      //多个相同标签，保留已填值的
      if(firstInx!==inx&&(item.value!==undefined||(item.tagType=='3'&&item.questionMapping.findIndex((i)=>i.value!==undefined)!==-1))){     //重复的已填值标签
        newArr.splice(inx-firstInx+it,0,item);
      }
      if(firstInx===inx){
        newArr.splice(it,1,item);
      }
    }else if(item.value!==undefined||(it.tagType=='3'&&it.questionMapping.findIndex((i)=>i.value!==undefined)!==-1)){
      newArr.push(item);
    }
    return newArr;
  },[...arr1]);
  return arr;
}

function handleMouseUp(param){
  const {select_start,i,boxMark}= param;
  if(select_start!==undefined){
    store.dispatch({
      type:SET_SELECTED_AREA,
      data:{i,boxMark,dir:'end'}
    });
    //清空搜索结果以关闭搜索弹窗
    const map = {
      '1':CLEAR_SEARCH,
      '2':CURRENT_CLEAR,
      '3':OTHERHIS_CLEAR,
      '4':CHECKBODY_CLEAR
    };
    store.dispatch({
      type:map[boxMark]
    });
    window.getSelection().empty();
  }
}

//判断不同科室内容是否相同
function checkDeptContent(jsonStr,tmpLis){
  for(let i = 0;i <tmpLis.length;i++){
    let dataStr = tmpLis[i].preview;
    if(
      filterDataArr(JSON.parse(jsonStr.chief)) == filterDataArr(eval('('+JSON.parse(dataStr).chief+')')) &&
      filterDataArr(JSON.parse(jsonStr.present)) == filterDataArr(eval('('+JSON.parse(dataStr).present+')')) &&
      filterDataArr(JSON.parse(jsonStr.other)) == filterDataArr(eval('('+JSON.parse(dataStr).other+')')) &&
      filterDataArr(JSON.parse(jsonStr.vital)) == filterDataArr(eval('('+JSON.parse(dataStr).vital+')')) &&
      jsonStr.lis == JSON.parse(dataStr).lis &&
      jsonStr.pacs == JSON.parse(dataStr).pacs &&
      jsonStr.diag == JSON.parse(dataStr).diag &&
      jsonStr.advice == JSON.parse(dataStr).advice
    ){
      // Notify.info('该模板已保存');
      return false;
    }
  }
}

module.exports = {
  getIds,
  getWindowInnerWidth,
  getWindowInnerHeight,
  getLabelIndex,
  fullfillText,
  checkFullfillText,
  dateParser,
  isNotNull,
  isNull,
  deepClone,
  isIE,
  storageLocal,
  getUrlArgObject,
  getAllDataList,
  getAllDataStringList,
  pushAllDataList,
  filterArr,
  filterDataArr,
  filterOtherDataArr,
  preventDefault,
  handleEnter,
  didPushParamChange,
  getEMRParams,
  getMRInfo,
  windowEventHandler,
  isAllClear,
  normalVal,
  getPageCoordinate,
  windowRemoveEventHandler,
  timestampToTime,
  formatContinueDots,
  inspectAndAssist,
  getCurrentDate,
  ifOtherClear,
  readyKeepHistory,
  parseChartData,
  getCalendarDate,
  downloadExportedData,
  getStatusImg,
  parseNameVal,
  getStringPlus,
  getPushLists,
  getPushList,
  getAllString,
  resetTagtype,
  handleLocalDelTag,
  shiftLocalDelTag,
  setPosition,
  isAllPartClear,
  getDomUpDown,
  setFontColorSize,
  moveEnd,
  getLifeLabels,
  getValuedLabels,
  removeRepeat,
  handleMouseUp,
  checkDeptContent,
  formatTextInfo,
  getArrow,
  formatFormParmas,
  pushHistoryDataList,
  timesYMDTime,
  delHistoryDataList,
};