import { json } from "@utils/ajax";
// import { SET_TREAT } from '@store/types/diagnosticList';
import { ADD_DIAGNOSTIC, GET_DIAGNOSTIC_STR,SET_TREAT} from '@store/types/diagnosticList';
import { SET_COMMONTREATMENT } from '@store/types/pushMessage'
import { SET_DRUG_INFO, SET_TREATMENT, SET_TREAT_INFO, SET_RECOMMEND_BASIC, SET_DRUG_INFO_LIST, IS_FIRST_MAIN_DIAG, SET_ADVERSE_REACTIONS, SET_ALL_ADVERSE_REACTIONS, SET_FOLLOW_UP, DEL_FOLLOW_UP, SET_ALL_FOLLOW_UP } from '@store/types/treat';
import {storageLocal,getEMRParams} from '@utils/tools';
import { isAddMainSuit } from '@store/async-actions/diagnosticList';
import { SAVE_FOLLOW_UP } from "@store/types/pushMessage";
import {MODI_LOADING} from '@store/types/homePage.js';
import { SHOW_TREAT} from '@store/types/treat.js';

const api={
    push:'/push/pushInner',
    textPush:'/push/pushText'
}

export const addDiagnostic = (item) => {
        return (dispatch, getState) => {
            const state = getState();
            let url = api.push;
            if(+state.typeConfig.confirmType===1){
                url=api.textPush;
            }
            const emrData = getEMRParams();
            const diagnosticList = state.diagnosticList.diagnosticList;
            let diag = '';
            if(diagnosticList) {
                for (let i = 0; i < diagnosticList.length; i++ ) {
                    if(i ===0 ) {
                        diag = diag + diagnosticList[i].name;
                    } else {
                        diag = diag + ',' + diagnosticList[i].name;
                    }

                }
            }
            if (item.type === 1) {
                diag = diag + ',' + item.name
            } else {
                diag = diag + ',' + item.name
            }
            const params = {
                "age": emrData.age,
                "featureType": "8",
                "diag": diag,
                "diseaseId":  item.id,
                "lis": emrData.lis,
                "other": emrData.other,
                "pacs": emrData.pacs,
                "sex": emrData.sex,
                "symptom": emrData.current + emrData.main,
                "vital": emrData.vital,
                "patientId": emrData.patientId,
            };
            //判断是否走慢病系统
            const isChronic = state.diagnosticList.chronicMagItem && state.diagnosticList.chronicMagItem.name||state.mainSuit.chronicDesease && state.mainSuit.chronicDesease.name;
            // const isChronic = true
            if (isChronic) {
                let chronicList = JSON.parse(storageLocal.get('chronic'));
                if(!chronicList){
                    getChronic().then(() =>{
                    chronicList = JSON.parse(storageLocal.get('chronic'));
                        for(let i=0; i<chronicList.length; i++){
                            if(chronicList[i].id==item.id&&chronicList[i].name==item.name){ //判断某个病是否为慢病
                                params.disType = 1
                            }
                        }
                        hasTreatment(dispatch, state,item,url,params)

                    });
                } else {
                    for(let i=0; i<chronicList.length; i++){
                        if(chronicList[i].id==item.id&&chronicList[i].name==item.name){
                            params.disType = 1
                        }
                    }
                    hasTreatment(dispatch, state, item,url,params)
                }
            } else {
                hasTreatment(dispatch, state, item,url,params)
            }
            
            
        }

}

//判断是否存在治疗方案
function hasTreatment(dispatch, state,item,url, params) {
    json(url, params).then((data) =>{
        if (data.data.data) {
            item.treat = data.data.data.treat
            dispatch({
                type: ADD_DIAGNOSTIC,
                item: item
            })
        } else {
            item.treat = null
            dispatch({
                type: ADD_DIAGNOSTIC,
                item: item
            })
        }
        dispatch({
            type: GET_DIAGNOSTIC_STR
        });
        dispatch(isAddMainSuit())

    }).catch((e) =>{
        console.log(e)
    })
}

export const getTreatResult = (item) =>{
    return (dispatch, getState) => {
        dispatch({
            type: SET_TREAT_INFO,
            treatItem: item
        })
        const state = getState();
        let url = api.push;
        if(+state.typeConfig.confirmType===1){
            url=api.textPush;
        }

        const emrData = getEMRParams();
        const diagnosticList = state.diagnosticList.diagnosticList;
        let diag = '';
        if(diagnosticList) {
            for (let i = 0; i < diagnosticList.length; i++ ) {
                if(i === 0 ) {
                    diag = diag + diagnosticList[i].name;
                } else {
                    diag = diag + ',' + diagnosticList[i].name;
                }
                
            }
        }
        const params = {
            "age": emrData.age,
            "featureType": "8",
            "diag": diag,
            "diseaseId":  item.id,
            "lis": emrData.lis,
            "other": emrData.other,
            "pacs": emrData.pacs,
            "sex": emrData.sex,
            "symptom": emrData.current + emrData.main,
            "vital": emrData.vital,
            "patientId": emrData.patientId,
        };
        // const params = {
        //         "age": 20,
        //         "diag": ",糖尿病",
        //         "disType": 1,
        //         "diseaseId":21773,
        //         "featureType": "8",
        //         "lis": [
                  
        //         ],
        //         "sex": 3,
        //         "symptom": "恶心，呕吐",
        //         "vital": ""
        // }
        const isChronic = state.diagnosticList.chronicMagItem && state.diagnosticList.chronicMagItem.name||state.mainSuit.chronicDesease && state.mainSuit.chronicDesease.name;
        // const isChronic = true
        if (isChronic) {
            let chronicList = JSON.parse(storageLocal.get('chronic'));
            if(!chronicList){
                getChronic().then(() =>{
                    chronicList = JSON.parse(storageLocal.get('chronic'));
                    for(let i=0; i<chronicList.length; i++){
                        if(chronicList[i].id==item.id&&chronicList[i].name==item.name){
                            params.disType = 1
                        }
                    }
                    getTreatment(item, dispatch, state, url,params, isChronic)

                });
            } else {
                for(let i=0; i<chronicList.length; i++){
                    if(chronicList[i].id==item.id&&chronicList[i].name==item.name){
                        params.disType = 1
                    }
                }
                getTreatment(item, dispatch, state,url,params, isChronic)
            }
        } else {
            getTreatment(item, dispatch, state,url,params, isChronic)
        }
        
    }
    
} 

//获取治疗方案
function getTreatment(item, dispatch, state,url,params, isChronic) {
    json(url, params).then((data) =>{
        dispatch({type:MODI_LOADING,flag:false});
        dispatch({type: SHOW_TREAT})
        let treat;
        if(data.data.data) {
             treat = data.data.data.treat || {}
        }
        if(treat) {
           let { treatment, commonTreatment, surgeryTreatment, drugHistory, adverseReactions, followUp} = treat
           dispatch({
                type: SET_TREATMENT,
                treatment: treatment,
                generalTreat: commonTreatment,
                surgeryTreat: surgeryTreatment,
                drugHistory: drugHistory,
            })
            if (adverseReactions) { //如何之前存过不良反应，则替换成之前的不良反应
                const allAdversReactionList = state.treat.allAdversReactionList
                if(allAdversReactionList) {
                    for(let i = 0; i < allAdversReactionList.length; i++) {
                        if(item.id == allAdversReactionList[i].id) {    //判断是否存过不良反应
                            for (let j = 0; j < adverseReactions.length; j++) { //判断不良反应是否有相同的不良反应，如果有，替换
                                for(let z = 0; z < allAdversReactionList[i].adversReactionList.length; z++) {
                                    if(adverseReactions[j].id == allAdversReactionList[i].adversReactionList[z].id) {
                                        adverseReactions[j] = allAdversReactionList[i].adversReactionList[z]
                                    }
                                }
                            }
                        }
                    }
                }
                
            } else {
                adverseReactions = []
            }
            if(isChronic) {
                let chronicList = JSON.parse(storageLocal.get('chronic'));
                for(let i=0; i<chronicList.length; i++){
                    if(chronicList[i].id==item.id&&chronicList[i].name==item.name){ //判断某个病是否为慢病
                        followUp = '2周';
                    }
                }
                
            }
            if(followUp) {  
                const followUpList = state.treat.followUpList
                if(followUpList) {  //判断之前有没有报存过的回访时间，如果有替换掉
                    for(let i = 0; i < followUpList.length; i++) {
                        if(item.id == followUpList[i].id) {
                            followUp = followUpList[i].followUp
                        }
                    }
                }
                dispatch({
                    type: SET_FOLLOW_UP,
                    // followUp: treat.followUp,
                    followUp: followUp,
                    hasFollowUp: true
                })
            } else {
                dispatch({
                    type: DEL_FOLLOW_UP,
                    delItem: item,
                })
            }
            dispatch({
                type: SET_ADVERSE_REACTIONS,
                adversReactionList: adverseReactions
            })
           
        }
        
}).catch((e) =>{
    console.log(e)
})
}

//保存全部不良反应
export const saveAllAdverseReactions = (item) => {
    return (dispatch, getState) => {
        const state = getState()
        const adversReactionList = state.treat.adversReactionList
        dispatch({
            type: SET_ALL_ADVERSE_REACTIONS,
            adversReactionList: {
                'id': item.id,
                'adversReactionList': adversReactionList
            }
        })
    }
}


//保存全部诊断的回访时间
export const setAllFollowUp = (item) => {
    return (dispatch, getState) => {
        const state = getState()
        const followUp = state.treat.followUp
        dispatch({
            type: SET_ALL_FOLLOW_UP,
            followUp: {
                'id': item.id,
                'followUp': followUp
            }
        })
    }
}

export const getInstroduce = (item, type, position)=>{

    return (dispatch, getState) =>{
        const url = '/introduceInfo/getByQuestionId';
        const params = {
            questionId: item.id,
            type: type,
            position: position
        }
        json(url, params)
        .then((data)=>{
                if(data.data.data) {
                    dispatch({
                        type: SET_DRUG_INFO,
                        instroduce: data.data.data.introduceDetailList,
                        name: type ==8 ?item.medicitionName : type == 10 ? item.tagName : ''
                    })
                } else {
                    dispatch({
                        type: SET_DRUG_INFO,
                        instroduce: [],
                        name: item.medicitionName
                    })
                }
                
        }).catch((e) => {
            console.log(e)
        })

    }

}

export const  getInstroduceMore = (drugIdList) =>{
    return (dispatch, getState) =>{
        let drugInfoList = [];
        for (let i = 0; i < drugIdList.drugIdList.length; i++ ) {
            const url = '/introduceInfo/getByQuestionId';
            const params = {
                questionId: drugIdList.drugIdList[i],
                type: 8,
                position: 5
            }
            json(url, params)
            .then((data)=>{
                    if(data.data.data) {
                        drugInfoList.push(data.data.data)
                        dispatch({
                            type: SET_DRUG_INFO_LIST,
                            drugInfoList: drugInfoList,
                        })
                    } else {
                        drugInfoList.push([])
                        dispatch({
                            type: SET_DRUG_INFO_LIST,
                            drugInfoList: drugInfoList,
                        })
                    }
                    
            }).catch((e) => {
                console.log(e)
            })




        }
        

    }
}

//一般治疗添加到医嘱
export const commonTreatAddToAdvice = () => {
    return (dispatch, getState) => {
        const state = getState();
        const followUp = state.treat.followUp
        if(state.treat.treatItem.id === state.diagnosticList.diagnosticList[0].id && state.treat.isFirstMainDiag) {
            dispatch({
                type: IS_FIRST_MAIN_DIAG
            })
            dispatch({
                type: SET_COMMONTREATMENT,
                commontreatment: state.treat.treatItem.treat.commonTreatment.text
            })
            console.log('state.treat.followUp', state.treat.followUp)
            dispatch({
                type: SAVE_FOLLOW_UP,
                followUp: state.treat.followUp
            })
        } else {
            return
        }
    }
}

//其他推荐推荐依据不用展示
// export const getRecommendBasic = (item)=>{
    
//     return (dispatch, getState) =>{
//         const url = '/api/icss/introduceInfo/getByQuestionId';
//         const params = {
//             questionId: item.id,
//             type: 9,
//             position: 2
//         }
//         json(url, params)
//         .then((data)=>{
//             if (data.status === 200) {
//                 if(data.data.data) {
//                     dispatch({
//                         type: SET_RECOMMEND_BASIC,
//                         recommendBasic: data.data.data.introduceDetailList,
//                     })
//                 } else {
//                     dispatch({
//                         type: SET_RECOMMEND_BASIC,
//                         recommendBasic: [],
//                     })
//                 }
                
//             }
//         }).catch((e) => {
//             console.log(e)
//         })

//     }
// }