import {get, post, json} from "../../utils/ajax";
import {GET_PATIENT_MESSAGE,GET_HOSPITAL_MESSAGE} from "../types/patInfo";
import {CONFIRM_TYPE} from "../types/typeConfig";
import {getInfos} from '@store/actions/getInfoByUuid';
import {getUrlArgObject,pushAllDataList,getAllDataList,storageLocal} from '@utils/tools';
import {getInitModules,getCommonList} from '@store/async-actions/homePage.js';
import store from '@store'
import {ISREAD,MODI_LOADING,SETPRE,SETPREDATA,SETADMIN} from "../types/homePage";
import { initItemList } from '@store/async-actions/tabTemplate';
import config from '@config/index';
import {Notify} from '@commonComp';
import {SHOW_LOADING} from '@store/types/copyRight.js';
import {getMRAnalyse,embedPush} from '@store/async-actions/pushMessage';



const api = {
    getPatInfo: '/patientInfo/getTopPatientInfo',
    getPatBaseInfo: '/patientInfo/getPatientInfo',
    getHospitalInfo:'/hospitalInfo/getHospitalInfo',
    getPreMsg:'/api/prec/inquiryInfo/getInquiryDetail',
    getPreMsgLis:'/api/prec/inquiryInfo/hisInquirys',
    getDoctorConfig:'/doctorPageMode/getDoctorPageModes',       //获取医生设置
    getAdminCheckout:'/sysSet/getAdminCheckout',     //获取管理员身份
};

//获取预问诊信息
export const getPreMsg = (dispatch, getState) => {
    // let baseList = getState();
    // let state = baseList.patInfo.message;
    const inCode = config.preIcss.recordIdVal===-1?getUrlArgObject("recordId"):config.preIcss.recordIdVal;
    json(api.getPreMsgLis, {
        "hospitalCode": getUrlArgObject('hospitalId'),
        "inquiryCode":inCode,
        "isHaveDetail":1,
        "patientCode": getUrlArgObject("patientNo"),
        "dayLimit":config.preIcss.deadline===-1?undefined:config.preIcss.deadline
    },true).then((res) => {
        const data = res.data;
        if (data.code == 0) {
            let result = data.data;
            let preIcss = {
              chief:result.chiefComplaint?new Array(result.chiefComplaint):[],
              current:result.xbs?new Array(result.xbs):[],
              other:result.qts?new Array(result.qts):[],
              checkBody:result.supplement?result.supplement:''
            }
            // dispatch({type:SETPRE,show:true});
            dispatch({type:SETPREDATA,preData:preIcss});
           
        } else {
            // console.log(res)
        }
    })
}
//获取管理员身份
export const getAdminCheckout = (val1,val2,dispatch) => {
    json(api.getAdminCheckout, {
      "doctorId": val1,
      "hospitalId": val2
    }).then((res) => {
        const data = res.data;
        if (data.code == 0) {
            dispatch({
              type: SETADMIN,
              admin:data.data
            });
            dispatch(initItemList(1,''));        //模板列表没有就获取模板列表用于保存时做数据对比是否保存过
        } else {
            //console.log(res)
        }
    })
}
//获取医院id
export const initHospitalInfo = (dispatch, getState) => {
    let baseList = getState();
    let state = baseList.patInfo.message;
    json(api.getHospitalInfo, {
        "hospitalCode": getUrlArgObject('hospitalId'),
    }).then((res) => {
        const data = res.data;
        if (data.code == 0) {
            dispatch({
              type: GET_HOSPITAL_MESSAGE,
              data:data.data.sysSetInfoData||[]
            });
        } else {
            console.log(res)
        }
    })
}
//参数转换
export const initPersonInfo = (dispatch, getState) => {
    // json('/tranFieldInfo/getInfoByUuid', {
    //     "uuid": getUrlArgObject('hospitalId'),
    // }).then((res) => {
    //     const data = res.data;
    //     if (data.code == 0) {
    //         dispatch(getInfos(data.data));
    //         getPatientMessage(dispatch, getState);
    //     } else {
    //         console.log(res)
    //     }
    // })
}

//默认回读
export const initHistoryDetails = (dispatch) => {
    let baseList = store.getState();
    let state = baseList.patInfo.message;
    storageLocal.remove('emrParam');
    return (dispatch) => {
        json('/inquiryInfo/readInquiry', {
            "doctorId": state.doctorId,
            "hospitalDeptId": state.hospitalDeptId,
            "hospitalId": state.hospitalId,
            "patientId": state.patientId, //患者id
            "inquiryCode": state.recordId,
        }).then((res) => {
            const data = res.data;
            // let pre = baseList.homePage.sysConfig.connect_prec;
            if (data.code == 0) {
                const detail = data.data;
                if(detail.dataJson){
                  pushAllDataList(detail.sign,'push',detail,'history');
                }else{
                  // let pre = baseList.homePage.sysConfig.connect_prec;
                  // (pre==1)&&getPreMsg(dispatch)
                }
                dispatch(getMRAnalyse())
                dispatch({
                  type:ISREAD
                });
                dispatch({type:MODI_LOADING,flag:false});
            } else {
                dispatch({type:MODI_LOADING,flag:false});
                // console.log(res)
            }
        })
    }
};
//转换设置存值
function parseDoctorCon(arr){
  let obj = {};
  let it;
  if(!arr){
    return null;
  }
  for(let i=0;i<arr.length;i++){
    it = arr[i];
    obj[it.modeClassify] = it.modeValue;
  }
  return obj;
}

//获取医生设置信息
function getDoctorConfig(id,dispatch){
  json(api.getDoctorConfig,{doctorId:id}).then((res)=>{
    if(res.data.code==='0'){
      const configs = parseDoctorCon(res.data.data);
      if(!configs||Object.keys(configs).length===0){
        return ;
      }
      dispatch({
        type:CONFIRM_TYPE,
        confirmType:configs
      })
    }else{
      Notify.info(res.data.msg);
    }
  });
}

//技术部需求，先获取第一个接口再去第二个
export async function getPatientMessage(dispatch, getState){
  const state = getState();
  const urlDatas = state.getInfoByUuid;
  const params = {
    hospitalCode:urlDatas.hospitalId,
    hospitalDeptCode: urlDatas.deptNo,
    doctorCode: urlDatas.doctorNo,
    patientCode:urlDatas.patientNo,
    recordId:urlDatas.recordId
  };

  let res1 = await json(api.getPatInfo, params);
  /*console.log(res1);
  console.log(1);*/
  let res2 = await json(api.getPatBaseInfo, params);
  /*console.log(res2);
  console.log(2);*/
  let data1 = {},data2 = {},docMode=-1;
  if(res1.data.code=='0'){
    data1 = res1.data.data;
    if(data1.doctorId){   //获取医生配置
      let docConfigs = await json(api.getDoctorConfig,{doctorId:data1.doctorId});
      //getDoctorConfig();
      if(docConfigs.data.code=='0'){
        const configs = parseDoctorCon(docConfigs.data.data);
        docMode=configs[0];
        if(!configs||Object.keys(configs).length===0){
          return ;
        }
        dispatch({
          type:CONFIRM_TYPE,
          confirmType:configs
        })
      }else{
        Notify.info(docConfigs.data.msg);
      }
    }
    //getDoctorConfig(data1.doctorId,dispatch);
  }else{
    dispatch({type:MODI_LOADING,flag:false});
    dispatch({type:SHOW_LOADING,flag:true,text:res1.data.msg,lType:'warning'});
    return;
  }
  if(res2.data.code=='0'){
    data2 = res2.data.data;
    dispatch({type:MODI_LOADING,flag:false});
  }else{
    dispatch({type:MODI_LOADING,flag:false});
    dispatch({type:SHOW_LOADING,flag:true,text:res2.data.msg,lType:'warning'});
    return;
  }
  //患者或医生信息有误，禁止操作
  if(Object.keys(data1).length>0&&Object.keys(data2).length>0&&data1.doctorId){
    dispatch({type:SHOW_LOADING,flag:false});
  }else{
    dispatch({type:MODI_LOADING,flag:false});
    dispatch({type:SHOW_LOADING,flag:true,text:"获取医生信息失败",lType:'warning'});
    return;
  }
  getAdminCheckout(data1.doctorId,data1.hospitalId,dispatch);
  dispatch({
    type: GET_PATIENT_MESSAGE,
    data:Object.assign(data1,data2)
  });
  /*localStorage.removeItem('deletedTags');
  if(docMode!==2){
    dispatch(getInitModules);     //确保病人信息获取以后再获取模板等数据，否则参数为空
    dispatch(initHistoryDetails());      //历史病历回读
  }else{*/
    dispatch(embedPush({mode:1}));      //默认空白情况，刷新右侧
  //}
  //dispatch(getInitModules);     //确保病人信息获取以后再获取模板等数据，否则参数为空
  dispatch(getCommonList(5));     //获取常用检验标签列表
  dispatch(getCommonList(6));     //获取常用检查标签列表if(allModules.length == 0){//模板为空才回读
  //dispatch(initHistoryDetails());      //历史病历回读
}


//  获取病历信息
export async function getPatInfoData(dispatch,getState) {
  
}
