import {json,expJson} from '@utils/ajax';
import {SET,PRESET} from '@types/checkBody';
import {SETDATA} from '@store/types/otherHistory';
import store from '@store';
import {getEMRParams,didPushParamChange,inspectAndAssist,fullfillText,checkFullfillText,deepClone,filterDataArr,pushAllDataList} from '@utils/tools';
import  Notify from '@commonComp/Notify';
import {billing} from '@store/async-actions/pushMessage';
import {SETOTHERHISTORY,ISREAD} from "../types/homePage";
import config from "@config/index";
import {CURRENT_CHRONIC} from '@store/types/currentIll';
import {MODI_LOADING} from '@store/types/homePage';
import {GET_ALL_HIS,FILTER_ALL_HIS} from '@store/types/emergencyHis';
import {SET_IMPORT_CHECKBODY_LABEL} from "../types/checkBody";
import {getBigPush} from '@utils/utils';

const api={
  // getSpreadModule:'/questionInfo/getByIds',
  getSpreadModule:'/questionInfo/getByIds2',//优化
  getModule:'/questionInfo/getById',
  searchURL: '/retrieval/getTagInfos',
  getOtherHisRecord: '/inquiryInfo/getLastOther',
  saveMode:'/doctorPageMode/saveDoctorPageModes',
  getSymptomFeature:'/feature/getSymptomFeature',
  getAssess:'/evaluationModuleMapping/getEvaluationModules',    //获取管理评估-慢病
  getIndexData:'/indexData/getIndexDatas',    //获取指标数据-图表-慢病
  // getFormulaResult:'/push/calculate',  // 计算接口
  getFormulaResult:'/calc/calculate',  // 计算接口
  getAssessHis:'/inquiryInfo/getEvaluations',   //历史评估记录
  getAllHisURL:'/inquiryInfo/hisInquirysForJz',   //全科历史病历
  downloadURL:'/inquiryInfo/exportInquirys',   //全科历史病历--导出
  addSecondDia:'/inquiryInfo/addDiagnoseSecond',   //全科历史病历--添加二次诊断
  getMedicalTypes:'/dictionaryInfo/getList',       //获取医学知识搜索分类
};

export const getFeature = (item)=>{
  const datas = json(api.getSymptomFeature+'?text='+encodeURIComponent(item),{});
  return datas;
}

//获取医学知识搜索分类
export const getMedicalFilters = ()=>{
  return json(api.getMedicalTypes,{});
};

//获取模板，多个
export const getModules = (ids)=>{
  const {patInfo} = store.getState();
  const param = {
    "age": patInfo.message.patientAge,
    "ids": ids,
    "sexType": patInfo.message.sex
  };
  const modules = json(api.getSpreadModule,param);
  return modules;
};
//获取单个模板
export const getModule = (id)=>{
  const {patInfo} = store.getState();
  const param = {
    "age": patInfo.message.patientAge,
    "id": id,
    "sexType": patInfo.message.sex
  };
  return json(api.getModule,param);
};
//搜索接口
export const getSearch = (param)=>{
  const {patInfo} = store.getState();
    const {inpStr,boxMark,mainIds,itemType} = param;
    let params = {};
    if(itemType==0){//主诉，仅限症状
      params = {
        "age": patInfo.message.patientAge,
        "inputIds":mainIds&&mainIds.length>0?mainIds:[],//主诉去重
        "inputStr": inpStr.trim(),
        "sexType": patInfo.message.sex,
        "type": boxMark, //1为主诉现病史
        "itemType":itemType
      };
    }else{
      params = {
        "age": patInfo.message.patientAge,
        "inputIds":mainIds&&mainIds.length>0?mainIds:[],//主诉去重
        "inputStr": inpStr.trim(),
        // "inputStr": inpStr,
        "sexType": patInfo.message.sex,
        "type": boxMark //1为搜症状
      };
    }
    return json(api.searchURL,params);
};

//其他史最近记录获取
export const getOtherHisRecord = ()=>{
  return (dispatch,getStore)=>{
    const state = getStore();
    const {message} =state.patInfo;
    const param = {
      hospitalCode:message.hospitalCode,
      patientCode:message.patientCode,
    };
    json(api.getOtherHisRecord,param).then((res)=>{
      if(res.data.code=='0'){
        const data = res.data.data;
        const obj = JSON.parse(data.dataJson||'{}');
        const objStr = JSON.parse(data.otherStr||'[]');
        let arr = [];//console.log(obj)
        if((!obj||!obj.other||obj.other.length==0)&&!objStr[0]){        //无其他史历史记录用默认模板
          /*if(mode=='1'){      //文本模式
            dispatch({
              type:SETOTHERHISTORY,
              data:[],
              selecteds:[],
              save:[]
            });
          }*/
        }else{
          const text = filterDataArr(objStr);
          dispatch({
            type:SETOTHERHISTORY,
            data:[{tagType:8,name:'',controlType:0,value:text}],
            /*period:{
              yjs_1: obj.yjs_1,
              yjs_2: obj.yjs_2,
              yjs_3: obj.yjs_3,
              yjs_4: obj.yjs_4,
            },
            selecteds:obj.otherHistorySelecteds,*/
            save:[text]
          });
        }
      }
    });
  }
};

//预取查体模板数据-现病史触发推送时获取
export function pregetCheckbodyData(flag){     //flag=true获取到数据后立即显示
  return (dispatch)=>{
    if(flag){
      dispatch({type:MODI_LOADING,flag:true});
    }

    getBigPush("1,42,41,7").then((res)=>{
      if(+res.data.code === 0){
        const obj = res.data.data;
        const data = obj&&obj.moduleVital;
        const vitalIds = obj&&obj.vitalIds;
        //查体高亮标签
        dispatch({
          type:SET_IMPORT_CHECKBODY_LABEL,
          labels:vitalIds
        });
        dispatch({
          type:PRESET,
          data:data
        });
        if(flag){
          const arr = checkFullfillText(data).newArr;
          const block = Object.assign(JSON.parse(config.textLabel),{full:true});//空白时保留一个自由文本标签
          dispatch({
            type:SET,
            data:arr.length?arr:[block],
            isEmpty:false
          });
          dispatch({type:MODI_LOADING,flag:false});
        }
      }else{
        dispatch({type:MODI_LOADING,flag:false});
        Notify.error(res.data.msg);
      }
    });
  }
}

//查体模板数据获取
export function getInitData(){
  return (dispatch,getStore)=>{
    const state =  getStore();
    const preData = [...state.checkBody.preData||[]];
    if(!preData||preData.length==0){
      dispatch(pregetCheckbodyData(true));
    }
      const arr = checkFullfillText(preData).newArr;
      dispatch({
        type:SET,
        data:arr,
        isEmpty:false
      });
  }
}

//其他史模板填充-先取最近记录，无则用模板
export function setOtherHisModule(){
  return (dispatch, getStore) => {
    const state = getStore();
    const initData = state.homePage.initData;
    const otherModel = initData.otherHisModel;
    const block = Object.assign(JSON.parse(config.textLabel),{full:true});
    const readMode = state.typeConfig.readMode;     //数据实际模式
    const mode = readMode!==-1&&readMode!==null?readMode:state.typeConfig.mode;
    const model = otherModel&&otherModel.length>0?deepClone(otherModel):[block];     //其他史模板，没有模板数据则显示一个空文本标签
    const arr = deepClone(initData.otherHis);        //最近其他史数据
    const arrSave = deepClone(initData.otherHisSave);    //最近其他史saveText
    const isHis = initData.otherIsHis;     //是否是历史数据
    const onlyOneText = arr && arr.length == 1 && arr[0].tagType == 8 && !arr[0].value;    //是否只有一个空的自由文本标签
    //是历史数据且不为空则显示历史数据，否则显示模板
    const listObj = isHis && (mode == 1 || (!onlyOneText && mode == 0)) ? {
      newArr: arr,
      saveText: arrSave || []
    } : fullfillText(model);
    dispatch({
      type: SETDATA,
      data: listObj.newArr,
      period: initData.period,
      save: listObj.saveText,
      isEmpty: false
    });
    dispatch({
      type: ISREAD
    });

    //右侧推送
    setTimeout(function () {      //延迟待确定后的数据更新后推送，避免获取的参数还是旧的
      if (didPushParamChange()) {     //操作后内容有变化才推送
        dispatch(billing());
      }
    }, 500);
  }
}

//转换设置传参
function parseConfigParam(configs){
  let arr = [];
  for(let key in configs){
    arr.push({
      modeClassify:key.replace("config",''),
      modeValue:configs[key]
    })
  }
  return arr;
}
//保存切换模式
export function saveMode(mode){
  return (dispatch,getStore)=>{
    const {patInfo} = getStore();
    const param = {
      doctorId:patInfo.message.doctorId,
      doctorPageMode: parseConfigParam(mode)
    };
    return json(api.saveMode,param);
  }
}

//慢病-获取管理评估
export function getAssessData(disId,disName){
  //return ()=>{
    const emrData = getEMRParams();
    const param = {
      diseaseId:disId,
      disType:1,
      diag:disName,
      diseaseName:disName,
      featureType:'11',
      ruleType:config.ruleTypeMap['11'],
      lis:emrData.lis,
      other: emrData.other,
      pasts: emrData.other,
      sex:emrData.sex,
      age:emrData.age,
      pacs:emrData.pacs,
      vital:emrData.vital,
      symptom:emrData.current + emrData.main
    };
    return json(api.getAssess,param);
  //}
}

//慢病-获取管理评估历史单条记录
export function getAssessHis(id){
  return (dispatch,getStore)=>{
    const param = {
      inquiryId:id,
    };
    return json(api.getAssessHis,param);
  }
}
//获取评估中图表数据
export function getIndexData(range,disName){
  return (dispatch,getStore)=>{
    const {patInfo} = getStore();
    const param = {
      diseaseName:disName,
      startTime:range[0],
      endTime:range[1]+" 23:23:59",
      patientId:patInfo.message.patientId,
    };
    return json(api.getIndexData,param);
  }
}

export const getFormulaResult = (item)=>{
  // type:1-量表 2-计算公式
  const type = item.type;
  let param = {
      type:type,
      data:item.data
    }
  return json(api.getFormulaResult,param);
}

// 自动分发模板
export function autoFillModules (){
  return (dispatch,getStore)=>{
    const state = getStore();
    const initData = state.homePage.initData;
    const block = Object.assign(JSON.parse(config.textLabel),{full:true});
    const cbody = initData.checkbody?[...initData.checkbody]:[block];
    dispatch({type: CURRENT_CHRONIC})//现病史
    //其他史模板填充-先去历史，无历史用模板
    inspectAndAssist()//化验辅检
    dispatch(setOtherHisModule());
    //查体模板填充
    dispatch({
      type: SET,
      data: cbody,
      isEmpty:false
    });
  }
}

// 获取全科历史病历
export function getAllHis(item){
  return (dispatch,getStore)=>{
    const state = getStore();
    const {message} = state.patInfo;
    const {params} = state.emergencyHis;
    let param = {};
    if(JSON.stringify(params) == '{}'){
      /*param = {
        "current": item.current,
        "hospitalDeptId": message.hospitalDeptId,
        "hospitalId": message.hospitalId,
        "size": 6,
      }*/
      param = Object.assign({},item,{hospitalDeptId:message.hospitalDeptId,hospitalId:message.hospitalId,size:6})
    }else{
      param = Object.assign({},params,{current:item.current})
    }

    json(api.getAllHisURL,param).then((res)=>{
      const result = res.data;
      if(result.code == 0){
        dispatch({
          type:GET_ALL_HIS,
          data:result.data.inquiryList,
          total:result.data.total,
          params:param,
        })
      }
    })
  } 
}
// 筛选全科历史病历
export function getFilterHis(obj){
  return (dispatch,getStore)=>{
    const state = getStore();
    const {message} = state.patInfo;
    const {params} = state.emergencyHis;
    let newParam = {};
    if(obj.flag == 999){//时间筛选
      newParam = Object.assign(params,{startDate:obj.startDate,endDate:obj.endDate,current:1})
    }else{
      /*if(obj.flag==-1){
        newParam = Object.assign(params,{current:1})
      }else{
        newParam = Object.assign({},params,{isHasSecond:obj.flag,current:1})
      }*/
      newParam = Object.assign({},params,{isHasSecond:obj.flag,current:1})
    }

    json(api.getAllHisURL,newParam).then((res)=>{
      const result = res.data;
      if(result.code == 0){
        dispatch({
          type:FILTER_ALL_HIS,
          data:result.data.inquiryList,
          total:result.data.total,
          // params:Object.assign(params,{current:1}),
          params:Object.assign(newParam,{current:1}),
        })
      }
    })
  } 
}

// 全科病历导出
export function downloadData (ids){
  const param = {
    "inquiryIds":ids
  }
  return expJson(api.downloadURL,param);
}
// 添加二次诊断
export function addSecondDiag(item){
  const state = store.getState();
  const {message} = state.patInfo;
  const param = {
    "diagnoseSecond": item.name,
    "doctorId": message.doctorId,
    "inquiryId": item.id
  }
  return json(api.addSecondDia,param)
}

