import { json } from "@utils/ajax";
// import { SET_TREAT } from '@store/types/diagnosticList';
import { ADD_DIAGNOSTIC, GET_DIAGNOSTIC_STR,SET_TREAT,SHOW_LOADING,ADD_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';
import Notify from '@commonComp/Notify';
import {getChronic} from '@store/async-actions/homePage.js';
import config from "@config/index";

const api={
    pushTreatment:'/push/pushTreatment',
    getConceptDetail:'/conceptDetail/getConceptDetail'
}

export const getTreatResult = (item) =>{
    return (dispatch, getState) => {
        dispatch({
            type: SET_TREAT_INFO,
            treatItem: item
        })
        const state = getState();
        let url = api.pushTreatment;
        

        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",
            "ruleType":config.ruleTypeMap["8"],
            "diag": diag,
            "diseaseName":  item.name,
            "lis": emrData.lis,
            "other": emrData.other,
            "pasts": emrData.other,
            "pacs": emrData.pacs,
            "sex": emrData.sex,
            "symptom": emrData.current + emrData.main,
            "vital": emrData.vital,
            "patientId": emrData.patientId,
            "hosCode": emrData.hosCode
        };
        // const params = {
        //     "disType":"1",
        //     "age":28,
        //     "diag":"2型糖尿病性肾病,1型糖尿病,糖尿病肾病",
        //     "diseaseName":"2型糖尿病",
        //     "featureType":"8",
        //     "hosCode":"A001",
        //     "lis":[
        //         {
        //             "name":"糖化血红蛋白测定",
        //             "detailName":"糖化血红蛋白(HbA1c)",
        //             "uniqueName":"糖化血红蛋白测定--糖化血红蛋白(HbA1c)",
        //             "source":"0",
        //             "minValue":4,
        //             "otherValue":"",
        //             "maxValue":6,
        //             "units":"%",
        //             "value":"5"
        //         },
        //         {
        //             "name":"空腹葡萄糖测定",
        //             "detailName":"葡萄糖(GLU)",
        //             "uniqueName":"空腹葡萄糖测定--葡萄糖(GLU)",
        //             "source":"0",
        //             "minValue":3.9,
        //             "otherValue":"",
        //             "maxValue":6.1,
        //             "units":"mmol/L",
        //             "value":"5"
        //         },
        //         {
        //             "name":"肝功能测定",
        //             "detailName":"谷丙转氨酶(ALT)",
        //             "uniqueName":"肝功能测定--谷丙转氨酶(ALT)",
        //             "source":"0",
        //             "minValue":5,
        //             "otherValue":"",
        //             "maxValue":40,
        //             "units":"U/L",
        //             "value":"180"
        //         }
        //     ],
        //     "lisOrder":"",
        //     "lisString":"",
        //     "other":"",
        //     "otherOrder":"",
        //     "pacs":"",
        //     "pacsOrder":"",
        //     "sex":1,
        //     "symptom":"患者患有2型糖尿病近来出现泡沫尿",
        //     "vital":"体温40℃"
        // }
        const isChronic = state.diagnosticList.chronicMagItem ||state.mainSuit.chronicDesease;
        // 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].conceptId==item.conceptId&&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].conceptId==item.conceptId&&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) =>{
        if(data.data.code == '0') {
            // dispatch({type:MODI_LOADING,flag:false});
            // dispatch({type:SHOW_LOADING,flag:false});
           
            let treat;
            if(data.data.data) {
                treat = data.data.data || {}
            }
            if(treat) {
                let { treatmentPlan, commonTreatment, surgeryTreatment, drugHistory, adverseEvent, followUp} = treat
                if(!(commonTreatment || surgeryTreatment ||
                    ( treatmentPlan &&treatmentPlan.length >0 ||
                        drugHistory&&drugHistory.length >0 || 
                        adverseEvent&&adverseEvent.length >0 ||
                        !!followUp ||treatmentPlan&&treatmentPlan.length >0))) {
                            Notify.info('暂无数据'); 
                            return
                } 
                dispatch({type: SHOW_TREAT})
                dispatch({
                     type: SET_TREATMENT,
                     treatment: treatmentPlan,
                     generalTreat: commonTreatment,
                     surgeryTreat: surgeryTreatment,
                     drugHistory: drugHistory,
                 })
                 if (adverseEvent) { //如何之前存过不良反应，则替换成之前的不良反应
                     const allAdversReactionList = state.treat.allAdversReactionList
                     if(allAdversReactionList) {
                         for(let i = 0; i < allAdversReactionList.length; i++) {
                             if(item.conceptId == allAdversReactionList[i].conceptId) {    //判断是否存过不良反应
                                 for (let j = 0; j < adverseEvent.length; j++) { //判断不良反应是否有相同的不良反应，如果有，替换
                                     for(let z = 0; z < allAdversReactionList[i].adversReactionList.length; z++) {
                                         if(adverseEvent[j].conceptId == allAdversReactionList[i].adversReactionList[z].conceptId && adverseEvent[j].name == allAdversReactionList[i].adversReactionList[z].name) {
                                             for(let x = 0; x < allAdversReactionList[i].adversReactionList[z].details.length; x++) {
                                                 for(let y = 0; y < adverseEvent[j].details.length; y++) {//判断每一项是否选择过
                                                     if(allAdversReactionList[i].adversReactionList[z].details[x].name == adverseEvent[j].details[y].name && allAdversReactionList[i].adversReactionList[z].details[x].select) {
                                                        adverseEvent[j].details[y].select = allAdversReactionList[i].adversReactionList[z].details[x].select
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     
                 } else {
                    adverseEvent = []
                 }
                 if(isChronic) {
                     let chronicList = JSON.parse(storageLocal.get('chronic'));
                     for(let i=0; i<chronicList.length; i++){
                         if(chronicList[i].conceptId==item.conceptId&&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.conceptId == followUpList[i].conceptId) {
                                 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: adverseEvent
                 })
            } else {
                Notify.info('暂无数据');
            }
        }else {
            Notify.info('暂无数据');
        }
    }).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: {
                'conceptId': item.conceptId,
                'adversReactionList': adversReactionList
            }
        })
    }
}


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

export const getInstroduce = (item, type, position)=>{
    console.log(item,type)
    return (dispatch, getState) =>{
        const params = {
            name: item.name,
            type: item.type,
            position: item.position
        }
        json(api.getConceptDetail, params)
        .then((data)=>{
                if(data.data.code == '0') {
                    dispatch({
                        type: SET_DRUG_INFO,
                        instroduce: data.data.data.introduceDetailList,
                        name: item.name,
                        tagType: item.type
                    })
                } else {
                    dispatch({
                        type: SET_DRUG_INFO,
                        instroduce: [],
                        name: item.name,
                        tagType: item.type
                    })
                }
                
        }).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 = '/conceptDetail/getConceptDetail';
//             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.conceptId === state.diagnosticList.diagnosticList[0].conceptId && state.treat.isFirstMainDiag) {
            dispatch({
                type: IS_FIRST_MAIN_DIAG
            })
            dispatch({
                type: SET_COMMONTREATMENT,
                commontreatment: state.treat.generalTreat&&state.treat.generalTreat.content
            })
            if(followUp) {
                dispatch({
                    type: SAVE_FOLLOW_UP,
                    followUp: followUp,
                    hasFollowUp: true
                })
            }
            if(state.treat.generalTreat&&state.treat.generalTreat.content || followUp) { //如果一般治疗和回访时间存在，定位到医嘱
                document.getElementById("adviceBox").scrollIntoView(true)
            }
            
        } 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)
//         })

//     }
// }