import store from '@store';
import {CLEAR_MAIN_SUIT} from '@store/types/mainSuit';
import {CLEAR_CURRENT_ILL} from '@store/types/currentIll';
import {CLEAROTHERHISTORY} from '@store/types/otherHistory';
import {CLEARCHECKBODY} from '@store/types/checkBody';
import {clearAssistData,addAssistLabel} from '@store/actions/assistCheck';
import {clearAllLabel,addLabel} from '@store/actions/inspect';
import {CLEAR_ALL_DIAG} from '@store/types/diagnosticList';
import {CLEAR_ALL_PUSH_MESSAGE, SET_TIPS} from '@store/types/pushMessage';
import {ISREAD, SETREADDITEMS} from "../store/types/homePage";
import {CLEAR_FIRST_MAIN_DIAG} from "../store/types/treat";
import {tabChange} from '@store/actions/tabTemplate';
import config from '@config/index.js';

/***
 * 工具函数
 *
 * ***/
const ARR = "Array";
const NUMBER = "Number";
const STRING = "String";
const OBJECT = "Object";
const UNDEFINED = "Undefined";
const NULL = "Null";
const BOOLEAN = "Boolean";
const qs = require('qs');

//  数据类型判断
const Type = {
    typeConstant: {
        'array': ARR,
        'number': NUMBER,
        'string': STRING,
        'object': OBJECT,
        'undefined': UNDEFINED,
        'null': NULL,
        'boolean': BOOLEAN
    },
    tolower: (str)=> {
        if(typeof str !== "string") {
            return "";
        }
        return str.toLowerCase();
    },
    checkType: (el, type)=> {
        type = Type.tolower(type);
        type = Type.typeConstant[type];
        return Object.prototype.toString.call(el) === "[object "+ type +"]";
    }
}

// 计算字符串长度，该长度将一个中文字算作2个字符长度
const regexp = {
    ch: (str)=> {//匹配中文
        if(typeof str !== "string") {
            return "";
        }
        return str.match(/[\u4e00-\u9fa5]/g) || "";
    },
    chLen: function (str) {//中文长度
        return regexp.ch(str).length;
    },
    strLen: function (str) {//字符串长度(一个中文当作两个英文字母)
        if(typeof str !== "string") {
            return 0;
        }
        return str.length + regexp.chLen(str);
    }
}

//判断是否空对象或未定义
const isUndefined = function (str) {
    if(str === 0 || str === "") {
        return false;
    }
    return (Type.checkType(str, 'null') || Type.checkType(str, 'undefined'));
   
}
//sessionStorage方法封装
const Storage = {
    session: {
        get: function (name) {
            return JSON.parse(sessionStorage.getItem(name));
        },
        set: function (name, data) {
            sessionStorage.setItem(name, JSON.stringify(data));
        },
        remove: function (name) {
            sessionStorage.removeItem(name);
        },
        clear: function () {
            sessionStorage.clear();
        }
    }
};

//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 nullFn = ()=>{};

//是否为空
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 args=new Object();  
    let query=window.location.href;//获取查询串  
    let pairs,arr;
    if(query.indexOf("?") != -1){
      pairs=query.split("?")[1].split("&");
      for(let i=0;i<pairs.length;i++){  
         let pos=pairs[i].indexOf('=');//查找name=value  
         if(pos==-1){//如果没有找到就跳过  
             continue;  
         }  
         let argname=pairs[i].substring(0,pos);//提取name  
         let value=decodeURIComponent(pairs[i].substring(pos+1));//提取value  
         args[argname]=unescape(value);//存为属性  
     }  
    }*/
    let query = window.location.search;
    let args = qs.parse(query.substr(1));
    return args[parm];//返回对象  
} 
const getAllDataList =(baseList) =>{           //获取所有模块结构化的数据
    let jsonData = {};
    //月经史公式
    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.pacs = baseList.assistCheck.assistLabel;     //辅检
    jsonData.diag = baseList.diagnosticList.diagnosticList;      //诊断
    jsonData.advice = baseList.pushMessage.advice;       //医嘱
    jsonData.mainSuitSelecteds = baseList.mainSuit.selecteds;      //主诉选中状态保存
    jsonData.currentIllSelecteds = baseList.currentIll.selecteds;      //主诉选中状态保存
    jsonData.otherHistorySelecteds = baseList.otherHistory.selecteds;      //主诉选中状态保存
    jsonData.checkBodySelecteds = baseList.checkBody.selecteds;      //主诉选中状态保存
    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;      //治疗方案
    // console.log(jsonData,'结构化数据获取')
    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
    }
    //console.log(jsonDataString,'文本模式数据获取')
    return jsonDataString;
}
/**
 * 
 * @param {回读数据} reData 
 * @param {回读数据是历史病历'history'，还是模板'template'} type 
 * @param {什么操作，回读'push'还是清空'clear'} action 
 * @param {引用的话是保存时候的文本类型，编辑的时候是当前页面设置的文本类型} whichSign 
 */
const pushAllDataList =(whichSign,action,reData,type) =>{           //回读清空所有的数据
    if(action == 'clear'){     //清空
      const block = Object.assign(JSON.parse(config.textLabel),{full:true});//空白时保留一个自由文本标签
      store.dispatch({type: CLEAR_MAIN_SUIT,data:[],saveText:[],selecteds:[],editClear:true,mainIds:[],clearAction:true,symptomFeature:[],chronicDesease:{}});
        store.dispatch({type: CLEAR_CURRENT_ILL,data:[],saveText:[],selecteds:[],editClear:true,symptomIds:[]});
        store.dispatch({type: CLEAROTHERHISTORY,data:[block],isEmpty:true,saveText:[],selecteds:[],editClear:true,yjs_1:'',yjs_2:'',yjs_3:'',yjs_4:''});
        store.dispatch({type: CLEARCHECKBODY,data:[block],isEmpty:true,saveText:[],selecteds:[]});
        store.dispatch(clearAssistData([],''));
        store.dispatch(clearAllLabel([],[],''));
        store.dispatch({
            type: SET_TIPS,
            tips: {}
          })
        store.dispatch({
            type: CLEAR_ALL_DIAG,
            data:[],
            saveText:'',
            mainSuitStr: '',
            chronicMagItem:{}
        });
        store.dispatch({
            type: CLEAR_ALL_PUSH_MESSAGE,
            data:{},
            saveText:'',
        });
        store.dispatch({
          type:CLEAR_FIRST_MAIN_DIAG,
          flag:true
        });
        storageLocal.remove('emrParam');
       // Notify.success('页面已清空')
    }else{
        if (whichSign == 0) {
          let dataJson = JSON.parse(reData.dataJson);
          //其他史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_MAIN_SUIT,
                    data:dataJson.chief,
                    selecteds:dataJson.mainSuitSelecteds?dataJson.mainSuitSelecteds:[],
                    saveText:JSON.parse(dataJsonStr.chief),
                    mainIds:dataJson.mainsuitIds?dataJson.mainsuitIds:[],
                    chronicDesease:dataJson.mainChronicDesease,
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:dataJson.present,
                    selecteds:dataJson.currentIllSelecteds?dataJson.currentIllSelecteds:[],
                    saveText:JSON.parse(dataJsonStr.present),
                    symptomIds:dataJson.currentIds?dataJson.currentIds:[]
                });
                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,
                    selecteds:dataJson.otherHistorySelecteds?dataJson.otherHistorySelecteds:[],
                    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,
                    selecteds:dataJson.checkBodySelecteds?dataJson.checkBodySelecteds:[],
                    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));
                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 dataJson = JSON.parse(reData.dataJson);*/
                let dataJsonStr = reData.detailList;
              // console.log(dataJson,dataJsonStr,'结构化历史病历回读')
                // console.log(dataJson.mainSuitSelecteds,7887)
                store.dispatch({
                    type: CLEAR_MAIN_SUIT,
                    data:dataJson.chief,
                    selecteds:dataJson.mainSuitSelecteds?dataJson.mainSuitSelecteds:[],
                    saveText:dataJsonStr[0].content ? JSON.parse(dataJsonStr[0].content) :[],
                    mainIds:dataJson.mainsuitIds?dataJson.mainsuitIds:[],
                    chronicDesease:dataJson.mainChronicDesease,
                });
                store.dispatch({
                    type: CLEAR_CURRENT_ILL,
                    data:dataJson.present,
                    selecteds:dataJson.currentIllSelecteds?dataJson.currentIllSelecteds:[],
                    saveText:dataJsonStr[1].content ? JSON.parse(dataJsonStr[1].content):[],
                    symptomIds:dataJson.currentIds?dataJson.currentIds:[]
                });
                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,
                    selecteds:dataJson.otherHistorySelecteds?dataJson.otherHistorySelecteds:[],
                    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,
                    selecteds:dataJson.checkBodySelecteds?dataJson.checkBodySelecteds:[],
                    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:''
                ));
                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,
                    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));
                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,
                    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:''
                ));
                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){   //数据处理
    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){
  return str.replace(config.punReg,function(word){
    return word.substr(0,1);
  }).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;}
}

//获取病例输入的内容
function getEMRParams(){
  const state = store.getState();
  const {message} = state.patInfo;
  const {mainSuit,currentIll,otherHistory,checkBody,inspect,assistCheck,diagnosticList} = state;
  const main = filterDataArr(mainSuit.saveText)||'',
    current=filterDataArr(currentIll.saveText)||'',
    other = filterDataArr(otherHistory.saveText)||'',
    vital = filterDataArr(checkBody.saveText)||'',
    lis = inspect.pushItem,    //化验推送所需数据
    pacs = assistCheck.dataString||'',
    dis=diagnosticList.diagnosticStrNoType||'',
    advice = '',
    diseaeId = [];
  const age = message.patientAge;
  const sex = message.sex;
  const patientId = message.patientId //病人id，取上次用药
  return {main,current,other,vital,lis,pacs,dis,advice,diseaeId,sex,age, patientId};
};

function didPushParamChange(){
  const emrData = getEMRParams();
  const oldParams = storageLocal.get('emrParam');
  const newParams = JSON.stringify({
    age: emrData.age,
    featureType: "4,5,6,7,22",
    diag: emrData.dis,
    lis: emrData.lis,
    other: emrData.other,
    pacs: emrData.pacs,
    sex: emrData.sex,
    vital:emrData.vital,
    symptom: emrData.current + emrData.main
  });
  if(newParams == oldParams){
      return false;
  }
  return true;
}
//判断页面所有数据是否为空
function isAllClear(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.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){
  if((min-0) && (max-0)){
      return `正常值: (${min}~${max})`
  }else if((min-0) && !(max-0)){
      return `正常值: (>=${min})`
  }else if(!(min-0) && (max-0)){
      if(min == '' || min == null){
          return `正常值: (<=${max})`
      }else{
          return `正常值: (${min}~${max})`
      }
  }else{
      return null;
  }
}
function getPageCoordinate(event){
    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+25) || (e.clientY + scrollY + 25);
    let obj = {
      boxLeft : x ,
      boxTop : y
    }
    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() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y+M+D+h+m+s;
}
function getPageLength(event) {     //兼容ie8获取页面距离左和上的距离，包括滚动距离
  let e = event || window.event;
  let scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  let scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  let x = e.pageX || e.clientX + scrollX;
  let y = e.pageY || e.clientY + scrollY;
  let page = {
    pageX:x,
    pageY:y
  }
  return page;
}
function dragBox(domWrap,domDrag){
  // console.log(domWrap,domDrag,'拖拽')
  let drag = document.getElementById(domDrag);//拖拽区域
  let wrap = document.getElementById(domWrap);//被拖拽的元素
  let wrapHeight = wrap.offsetHeight;//被拖拽的元素高度
  let wrapWidth = wrap.offsetWidth;//被拖拽的元素宽度
  let width = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;//屏幕宽度
  let height = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;//屏幕高度
  let mouseX = 0,mouseY = 0,dragX = 0,dragY = 0,isDrag = false,isMove = false;
  windowEventHandler('mousedown',function(event){    //鼠标位置获取，计算点击位置到拖拽元素左边的距离
    let page = getPageLength(event);
    mouseX = page.pageX - wrap.offsetLeft      //鼠标到拖拽元素的左边界的距离
    mouseY = page.pageY - wrap.offsetTop       //鼠标到拖拽元素的上边界的距离
    isDrag = true
    // isMove = false
  },drag)
  // windowEventHandler('mousemove',handleMove,document)
  windowEventHandler('mousemove',handleMove,document)
  windowEventHandler('mouseup',()=>{
    // if(isMove){ //有move就设置位置没有移动就不处理
    //   console.log(dragX)
    //   wrap.style.left = dragX + 'px'
    //   wrap.style.top = dragY + 'px'
    // }
    isDrag = false
    return false
  },document)

  function handleMove(event){      //移动的
    let dragDes = document.getElementById('treatDescBox');//展開区域
    let page = getPageLength(event);
    let maxDragX = 0,dragDesWidth = 0;
    let maxDragY = height - wrapHeight;//最大可拖拽y方向距离
    wrapHeight = wrap.offsetHeight;
    wrapWidth = wrap.offsetWidth;
    if(domDrag == 'dragTreatTitle'){//最大可推拽x方向距离
      if(dragDes != null){
        dragDesWidth = dragDes.offsetWidth
      }else{
        dragDesWidth = 0
      }
      maxDragX = width - wrapWidth - dragDesWidth
    }else{
      maxDragX = width - wrapWidth
    }
    if(isDrag){
      dragX = page.pageX - mouseX          //鼠标可拖拽到左边的最大距离
      dragY = page.pageY - mouseY          //鼠标可拖拽到上边的最大距离
      if(dragX < 0){      //不能超出左边界
        dragX = 0
      }
      if(dragY < 0){      //不能超出上边界
        dragY = 0
      }
      if(domDrag == 'dragTreatTitle'){
        if(width-dragX-dragDesWidth < wrapWidth){    //不能超出右边界
          dragX = maxDragX
        }
      }else{
        // console.log(width,dragX,maxDragX,wrapWidth)
        if(width-dragX < wrapWidth){    //不能超出右边界
          dragX = maxDragX
        }
      }
      if(height-dragY < wrapHeight){     //不能超出下边界
        dragY = maxDragY
      }
      // isMove = true
      wrap.style.left = dragX + 'px'
      wrap.style.marginLeft = 0 + 'px'
      wrap.style.top = dragY + 'px'
    }
  }
}

function getCurrentDate(){
  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 = year+'-'+(mon<10?'0'+mon:mon)+'-'+(day<10?'0'+day:day);
  return date;
}
function inspectAndAssist(){
  const state = store.getState();
  let mainType = state.typeConfig.typeConfig
  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,
    }
    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
    assayArr.push(tmpObj)
  }
  for(let i = 0;i < tmpAssist.length;i++){//辅检数据处理
    let tmpObj = {  //添加辅检
      name: '',
      questionId: '',
      showType: 1,
      time:getCurrentDate(),
      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();
  let jsonStr = getAllDataStringList(baseList);
  if(filterDataArr(JSON.parse(jsonStr.chief)) == ''){
      return 1;//主诉不能为空
  }else if(!jsonStr.diag || jsonStr.diag.trim().length < 1){
      return 2;//诊断不能为空
  }else{
    return 3;
  }
}
module.exports = {
    checkType: Type.checkType,
    regexp,
    isUndefined,
    Storage,
    nullFn,
    isNotNull,
    isNull,
    deepClone,
    isIE,
    storageLocal,
    getUrlArgObject,
    getAllDataList,
    getAllDataStringList,
    pushAllDataList,
    filterArr,
    filterDataArr,
    filterOtherDataArr,
    preventDefault,
    handleEnter,
    didPushParamChange,
    getEMRParams,
    windowEventHandler,
    isAllClear,
    normalVal,
    getPageCoordinate,
    windowRemoveEventHandler,
    timestampToTime,
    getPageLength,
    dragBox,
    formatContinueDots,
    inspectAndAssist,
    getCurrentDate,
    ifOtherClear,
    readyKeepHistory,
};