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} from '@store/actions/assistCheck';
import {clearAllLabel} 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";

/***
 * 工具函数
 *
 * ***/
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))
};

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 = {};
    jsonData.lis = {};
    jsonData.chief = baseList.mainSuit.data;      //主诉
    jsonData.present = baseList.currentIll.data;    //现病史
    jsonData.other = baseList.otherHistory.data;      //其他史
    jsonData.vital = baseList.checkBody.data;    //查体
    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.currentIds = baseList.currentIll.symptomIds;      //现病史去重
    // 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
    }

    if(baseList.otherHistory.saveText.length == 1 && baseList.otherHistory.saveText[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) =>{           //回读清空所有的数据
      store.dispatch({
        type:ISREAD
      });
    if(action == 'clear'){     //清空
        store.dispatch({type: CLEAR_MAIN_SUIT,data:[],saveText:[],selecteds:[],editClear:true,mainIds:[]});
        store.dispatch({type: CLEAR_CURRENT_ILL,data:[],saveText:[],selecteds:[],editClear:true,symptomIds:[]});
        store.dispatch({type: CLEAROTHERHISTORY,data:[],saveText:[],selecteds:[],editClear:true});
        store.dispatch({type: CLEARCHECKBODY,data:[],saveText:[],selecteds:[]});
        store.dispatch(clearAssistData([],''));
        store.dispatch(clearAllLabel([],[],''));
        store.dispatch({
            type: SET_TIPS,
            tips: {}
          })
        store.dispatch({
            type: CLEAR_ALL_DIAG,
            data:[],
            saveText:'',
            mainSuitStr: '',
        });
        store.dispatch({
            type: CLEAR_ALL_PUSH_MESSAGE,
            data:{}
        });
       // Notify.success('页面已清空')
    }else{
        if (whichSign == 0) {
            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:dataJson.chief,
                    selecteds:dataJson.mainSuitSelecteds?dataJson.mainSuitSelecteds:[],
                    saveText:JSON.parse(dataJsonStr.chief),
                    mainIds:dataJson.mainsuitIds?dataJson.mainsuitIds:[],
                });
                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,
                    selecteds:dataJson.otherHistorySelecteds?dataJson.otherHistorySelecteds:[],
                    saveText:JSON.parse(dataJsonStr.other),
                    editClear:dataJson.other.length>0?false:true
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    selecteds:dataJson.checkBodySelecteds?dataJson.checkBodySelecteds:[],
                    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
                });
            }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:[]
                });
                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,
                    selecteds:dataJson.otherHistorySelecteds?dataJson.otherHistorySelecteds:[],
                    saveText:dataJsonStr[2].content ? JSON.parse(dataJsonStr[2].content):[],
                    editClear:dataJson.other.length>0?false:true
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    selecteds:dataJson.checkBodySelecteds?dataJson.checkBodySelecteds:[],
                    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
              });
            }
        } 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:[],
                    saveText:JSON.parse(dataJsonStr.other)
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    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
              });
            }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:[],
                    saveText:dataJsonStr[2].content ? JSON.parse(dataJsonStr[2].content) :[]
                });
                store.dispatch({
                    type: CLEARCHECKBODY,
                    data:dataJson.vital,
                    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
              });
            }
        }
    }  
}

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

function filterDataArr(arr){   //数据处理
    let tmpArr = [];
    for(let i = 0;i < arr.length;i++){
        if(arr[i] && arr[i].indexOf('undefined') == -1){
            if(tmpArr[tmpArr.length-1] != '，' ){
                tmpArr.push(arr[i])
            }
            else if(tmpArr[tmpArr.length-1] == '，' && arr[i] != '，') {
              if(arr[i] == '。'){
                tmpArr.pop();
                tmpArr.push(arr[i]);
              }else{
                tmpArr.push(arr[i]);
              }
            }
        }
    }
    return (tmpArr.join('')).replace(/,^|，^|,$|，$/gi,"");
}
// 取消默认行为
function preventDefault(event) {
    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }
}

//ie8添加解除事件兼容
function windowEventHandler(type,func){
    if(window.addEventListener){
      window.addEventListener(type, func);
    }else{
      window.attachEvent('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.diagnosticStr||'',
    advice = '',
    diseaeId = [];
  const age = message.patientAge;
  const sex = message.sex;
  return {main,current,other,vital,lis,pacs,dis,advice,diseaeId,sex,age};
};

function didPushParamChange(){
  const emrData = getEMRParams();
  const oldParams = storageLocal.get('emrParam');
  const newParams = JSON.stringify({
    age: emrData.age,
    featureType: "5,6,7",
    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;
}

module.exports = {
    checkType: Type.checkType,
    regexp,
    isUndefined,
    Storage,
    nullFn,
    isNotNull,
    isNull,
    deepClone,
    isIE,
    storageLocal,
    getUrlArgObject,
    getAllDataList,
    getAllDataStringList,
    pushAllDataList,
    filterArr,
    filterDataArr,
    preventDefault,
    handleEnter,
    didPushParamChange,
    getEMRParams,
    windowEventHandler
};