import {post,json} from '@utils/ajax.js';
import {SETINITDATA,MODI_LOADING,GET_ASSIST_LIST,GET_INSPECT_LIST,SETALLMODULES} from '@store/types/homePage.js';
import {SET_CURRENT} from '@store/types/currentIll';
import {SET_MAINSUIT} from '@store/types/mainSuit';
import config from '@config/index.js';
import store from '@store';
import {fullfillText} from '@common/js/func';
import {formatContinueDots} from '@utils/tools';
import {getOtherHisRecord,getInitData} from '@store/async-actions/fetchModules.js';
import {initHistoryDetails} from '@store/async-actions/patInfo';
import {storageLocal} from '@utils/tools';

const api = {
  getModules:'/moduleInfo/getAll',
  clickCount:'/buriedSomeStatistical/saveBuriedSomeStatisticals', //埋点统计
  getChronic:'/disType/getDisType', //慢病列表
  getQuestionUsual:'/questionUsual/getQuestionUsual' //化验常用标签
};

function modulesParseJson(data){
  let json = {},obj={},saveTextJson={},moduleName={};
  data.map((it)=>{
    moduleName[config.moduleCP[it.type]] = it.name;//添加病情变化/病程变化子模板需要使用模板名称
    obj = it.type==4?fullfillText(it.moduleDetailDTOList,false,false,false):fullfillText(it.moduleDetailDTOList);
    json[config.moduleCP[it.type]] = formatContinueDots(obj.newArr);
    saveTextJson[config.moduleCP[it.type]] = obj.saveText;
  });
  return {json,saveTextJson,moduleName};
}

export const getInitModules= (dispatch,getStore)=>{
  const state = getStore();
  const {message} = state.patInfo;
  const {allModules} = state.homePage;
  const chronicMagItem = state.diagnosticList.chronicMagItem;//诊断入口
  // const chronicId = chronicMagItem?chronicMagItem.id:'';
  const chronicDesease = state.mainSuit.chronicDesease; //主诉入口
  const chronicId = chronicDesease&&chronicDesease.id||chronicMagItem&&chronicMagItem.id||'';
  const param = {
    age:message.patientAge,
    sexType:message.sex,
    mouduleType:chronicId?2:(message.selfDeptId?1:0),//慢病2  科室1 其他0
    // relationId:chronicId?chronicId:(message.hospitalDeptId?message.hospitalDeptId:0), //慢病id  科室id  其他0
    relationId:chronicId?chronicId:(message.selfDeptId?message.selfDeptId:0), //慢病id  科室id  其他0
  }
  // return json(api.getModules,{age:message.patientAge,sexType:message.sex}).then((res) => {
  return json(api.getModules,param).then((res) => {
      if (res.data.code == '0') {
        const newObj = modulesParseJson(res.data.data);
        const initData = newObj.json;
        const initSaveText = newObj.saveTextJson;
        const initModuleName = newObj.moduleName;
        // 将所有模板缓存，方便根据id取子模板
        dispatch({
          type: SETALLMODULES,
          data: res.data.data,
        });
        dispatch({
          type: SETINITDATA,
          data: initData
        });
        if(!chronicId){//普通病
          dispatch({
            type:SET_MAINSUIT,
            data:fullfillText(initData.mainSuit).newArr,
            addSymptom:fullfillText(initData.addSymptom).newArr,
            save:initSaveText.mainSuit
          });
          dispatch({
            type:SET_CURRENT,
            data:formatContinueDots(initData.current),
            save:initSaveText.current,
            processModule:formatContinueDots(initData.process),//病程变化
            saveProcess:initSaveText.process,
            emptyData:formatContinueDots(initData.currentEmpty),//现病史空模板
            saveEmpty:initSaveText.currentEmpty,
          });
        }else{//慢病--没有主诉模板
          dispatch({
            type:SET_CURRENT,
            data:formatContinueDots(initData.current),
            save:initSaveText.current,
            processModule:formatContinueDots(initData.process),//病程变化
            // saveProcess:initSaveText.process,
            // 慢病现病史没有空模板
          });
        }
        dispatch(getOtherHisRecord());          //获取其他史最近记录
      }
    })
};

// 埋点事件，点击保存时调用
export const saveClickNum = (dispatch,getState)=>{
  const state = getState();
  const patientInfo = state.patInfo.message;
  const data = state.homePage.clickData;//所有点击事件储存
  const params = {
    "doctorId": patientInfo.doctorId,         //医生id
    "hospitalDeptId":patientInfo.hospitalDeptId ,   //部门ID
    "hospitalId": patientInfo.hospitalId,       //医院id
    "inquiryCode": patientInfo.recordId,//门诊号
    "patientId": patientInfo.patientId,        //病人ID
    "taggeds": data
  }

 return json(api.clickCount,params).then((res) => {
    if (res.data.code == '0') {
      console.log("埋点请求成功");
      // 重置clickData
    }else{
      console.log("埋点请求失败",res);
    } 
  }) 
}

// 请求慢病列表
export const getChronic = (dispatch,getState)=>{
 return json(api.getChronic,{}).then((res) => {
    const result = res.data;
    if (result.code == '0') {
      const chronic = JSON.stringify(result.data.chronic);
      storageLocal.set('chronic',chronic);
    }else{
      console.log("请求失败",res);
    }
  })
}
// 请求化验辅检常用标签
export const getCommonList = (val)=>{
  return (dispatch,getState) => {
    const state = getState();
    const patientInfo = state.patInfo.message;
    const params = {
      "age":patientInfo.patientAge ,   //年龄
      "deptId": patientInfo.hospitalDeptId,       //科室id
      "sexType": patientInfo.sex,        //性别
      "type": val
    }
    json(api.getQuestionUsual,params).then((res) => {
      const result = res.data;
      if (result.code == '0') {
        if(val == 5){
          dispatch({
            type:GET_INSPECT_LIST,
            data:result.data
          })
        }else{
          dispatch({
            type:GET_ASSIST_LIST,
            data:result.data
          })
        }
      }else{
        console.log("请求失败",res);
      }
    })
  }
}