import {json} from '@utils/ajax.js';
import {SET} from '@types/checkBody.js';
import {fullfillText,_fullfillText} from '@common/js/func';
import {SETDATA} from '@store/types/otherHistory';
import store from '@store';
import {getEMRParams,didPushParamChange,inspectAndAssist} from '@utils/tools.js';
import {Notify} from '@commonComp';
import {billing} from '@store/async-actions/pushMessage';
import {SETOTHERHISTORY,ISREAD} from "../types/homePage";
import {SAVE_TABLE_RESULT,SET_CHRONIC_PUSHS} from "../types/pushMessage";
import config from "@config/index";
import {CURRENT_CHRONIC} from '@store/types/currentIll';
import {MODI_LOADING} from '@store/types/homePage.js';

const api={
  getSpreadModule:'/questionInfo/getByIds',
  getModule:'/questionInfo/getById',
  searchURL: '/retrieval/getTagInfos',
  getOtherHisRecord: '/inquiryInfo/getLastOther',
  getBigPush:'/push/pushInner',
  saveMode:'/doctorPageMode/saveDoctorPageModes',
  getSymptomFeature:'/feature/getSymptomFeature',
  getAssess:'/evaluationModuleMapping/getEvaluationModules',    //获取管理评估-慢病
  getIndexData:'/indexData/getIndexDatas',    //获取指标数据-图表-慢病
  // getFormulaResult:'/push/calculate',  // 计算接口
  getFormulaResult:'/calc/calculate',  // 计算接口
  getAssessHis:'/inquiryInfo/getEvaluations',   //历史评估记录
};

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

//获取模板，多个
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 mode = state.typeConfig.typeConfig;
    const param = {
      hospitalCode:message.hospitalCode,
      patientCode:message.patientCode,
      sign:mode
    };
    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:[]
            });
          }

          //console.log('其他史最近数据无')
          //arr = state.homePage.initData.otherHis;
        }else{
          arr = obj.other;
          if(mode =='1'){     //文本模式
            dispatch({
              type:SETOTHERHISTORY,
              data:[],
              selecteds:[],
              save:[objStr[0]]
            });
          }else{
            dispatch({
              type:SETOTHERHISTORY,
              data:arr,
              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:objStr
            });
          }
        }
      }
    });
  }
};

//查体模板数据获取
export function getInitData(){
  return (dispatch)=>{
    const emrData = getEMRParams();
    const param = {
      age: emrData.age,
      featureType: "1,4,7",
      diag: emrData.dis,
      lis: emrData.lis,
      other: emrData.other,
      pacs: emrData.pacs,
      sex: emrData.sex,
      vital:emrData.vital,
      symptom: emrData.current+emrData.main
    };
    json(api.getBigPush,param).then((res)=>{
      if(+res.data.code === 0){
        dispatch({type:MODI_LOADING,flag:false});
        const data = res.data.data&&res.data.data.vital;
        const str = JSON.stringify(data);
        const arr = fullfillText(JSON.parse(str),false,false,false).newArr;
        dispatch({
          type:SET,
          data:arr,
          isEmpty:false
        });
      }else{
        dispatch({type:MODI_LOADING,flag:false});
        const block = Object.assign(JSON.parse(config.textLabel),{full:true});      //无数据时保留一个自由文本标签可输入
        dispatch({
          type:SET,
          data:[block],
          isEmpty:true
        });
        Notify.error(res.data.msg);
      }
    });
  }
}

//其他史模板填充-先取最近记录，无则用模板
export function setOtherHisModule(){
  return (dispatch, getStore) => {
    const state = getStore();
    const initData = state.homePage.initData;
    const block = Object.assign(JSON.parse(config.textLabel),{full:true});
    const mode = state.typeConfig.typeConfig;
    const model = JSON.parse(JSON.stringify(initData.otherHisModel || null))||[block];     //查体模板
    const arr = JSON.parse(JSON.stringify(initData.otherHis || null));        //最近其他史数据
    const arrSave = JSON.parse(JSON.stringify(initData.otherHisSave || null));    //最近其他史saveText
    const selects = JSON.parse(JSON.stringify(initData.otherSelecteds || null));  //其他史杂音类选中项
    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,
      selecteds: selects,
      period: initData.period,
      save: listObj.saveText,
      isEmpty: false
    });
    dispatch({
      type: ISREAD
    });

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

//保存切换模式
export function saveMode(mode){
  return (dispatch,getStore)=>{
    const {patInfo} = getStore();
    const param = {
      doctorId:patInfo.message.doctorId,
      modeClassify:0,
      modeValue:mode
    };
    return json(api.saveMode,param);
  }
}

//慢病-获取管理评估
export function getAssessData(){
  return (dispatch,getStore)=>{
    const {patInfo} = getStore();
    const param = {
      diseaseId:21773,
      disType:1,
      diag:'糖尿病',
      featureType:11,
      lis:[],
      sex:patInfo.message.sex,
      age:patInfo.message.patientAge
    };
    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){
  return (dispatch,getStore)=>{
    const {patInfo} = getStore();
    const param = {
      diseaseId:21773,
      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 (dispatch,getState) => {
    const state = getState();
    json(api.getFormulaResult,param).then((res)=>{
      if(+res.data.code==0){
        if(type==1){//量表
          dispatch({
            type:SAVE_TABLE_RESULT,
            // id:item.pId, //外层疾病id
            id:item.id,  //量表id
            data:Object.assign({},res.data.data,{pIndex:item.pIndex})
          })
        }else if(type==2){//计算公式
          const data = state.pushMessage.chronicPushItems
          data[item.ppIndex].details[item.pIndex].content.result =  res.data.data.result
          dispatch({
            type: SET_CHRONIC_PUSHS,
            data: JSON.parse(JSON.stringify(data))
          })
          console.log('resss', res)
        }
        
      }else{
        Notify.error(res.data.msg);
      }
    })
  }
}*/
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
    });
  }
}
