package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.client.TreatServiceClient;
import com.diagbot.client.bean.Medicition;
import com.diagbot.client.bean.MedicitionClass;
import com.diagbot.entity.IntroduceDetail;
import com.diagbot.entity.IntroduceMap;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IntroducePositionEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.QuestionTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.FastJsonUtils;
import com.diagbot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2018/12/17 13:41
 */
@Component
public class TreatmentFacade {
    @Autowired
    QuestionFacade questionFacade;
    @Autowired
    IntroduceDetailFacade introduceDetailFacade;
    @Autowired
    TreatServiceClient treatServiceClient;
    @Autowired
    IntroduceMapFacade introduceMapFacade;

    /**
     * 获取治疗方案
     *
     * @param
     * @return
     */
    public Map<String,Object> getTreatment(Map<String,String> treatmentMap,Long diseaseId) {
        Map<String, Object> retMap = new LinkedHashMap<>();
        QuestionInfo disease=questionFacade.getById(diseaseId);
        if(disease==null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "诊断不存在");
        }
        if(!treatmentMap.containsKey(disease.getTagName())){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "诊断名称和id不匹配");
        }

        //一般治疗
        List<IntroduceDetail> commonTreatmentDetailList = getIntroduceDetailList(diseaseId, IntroducePositionEnum.CommonTreatment.getKey());
        retMap.put("commonTreatment", commonTreatmentDetailList.size() > 0 ? commonTreatmentDetailList.get(0).getContent() : "");

        //手术治疗
        List<IntroduceDetail> surgeryTreatmentDetailList = getIntroduceDetailList(diseaseId, IntroducePositionEnum.SurgeryTreatment.getKey());
        retMap.put("surgeryTreatment", surgeryTreatmentDetailList.size() > 0 ? surgeryTreatmentDetailList.get(0).getContent() : "");

        //获取知识图谱治疗方案
        String treatment=treatmentMap.get(disease.getTagName());
        if (StringUtil.isBlank(treatment)) {
            return retMap;
        }

        List<MedicitionClass> drugsList = FastJsonUtils.getJsonToListByKey(treatment, "treatment", MedicitionClass.class);

        List<String> classNameList = drugsList.stream().map(drugs -> drugs.getDrugsName()).collect(Collectors.toList());
        List<QuestionInfo> drugClassList = getTopQuestionList(classNameList, QuestionTypeEnum.DrugClass.getKey());
        Map<String, QuestionInfo> drugClassMap = EntityUtil.makeEntityMap(drugClassList, "tagName");
        List<Long> drugClassIds = drugClassList.stream().map(drugClass -> drugClass.getId()).collect(Collectors.toList());
        List<IntroduceMap> introduceMapList = getIntroduceMapList(drugClassIds, QuestionTypeEnum.DrugClass.getKey());
        Map<Long, IntroduceMap> introduceMapMap = EntityUtil.makeEntityMap(introduceMapList, "questionId");

        for (MedicitionClass medicitionClass : drugsList) {
            QuestionInfo drugClass = drugClassMap.get(medicitionClass.getDrugsName());
            if (drugClass != null) {
                medicitionClass.setId(drugClass.getId());
                if (introduceMapMap.get(drugClass.getId()) != null) {
                    medicitionClass.setShowInfo("1");
                }
            }
            LinkedList<Medicition> medicitionList = medicitionClass.getMedicitionsList();
            List<String> drugNameList = medicitionList.stream().map(medicition -> medicition.getMedicitionName()).collect(Collectors.toList());
            List<QuestionInfo> drugList = getTopQuestionList(drugNameList, QuestionTypeEnum.Drug.getKey());
            Map<String, QuestionInfo> drugMap = EntityUtil.makeEntityMap(drugList, "tagName");
            List<Long> drugIds = drugList.stream().map(drug -> drug.getId()).collect(Collectors.toList());
            List<IntroduceMap> drugIntroduceMapList = getIntroduceMapList(drugIds, QuestionTypeEnum.Drug.getKey());
            Map<Long, IntroduceMap> drugIntroduceMapMap = EntityUtil.makeEntityMap(drugIntroduceMapList, "questionId");
            for (Medicition medicition : medicitionList) {
                QuestionInfo drug = drugMap.get(medicition.getMedicitionName());
                if (drug != null) {
                    medicition.setId(drug.getId());
                    if (drugIntroduceMapMap.get(drug.getId()) != null) {
                        medicition.setShowInfo("1");
                    }
                }
            }
            medicitionClass.setMedicitionsList(medicitionList);
        }

        retMap.put("treatment", drugsList);
        return retMap;
    }


    /**
     * 根据展示位置获取提示信息明细列表
     *
     * @param diseaseId
     * @param position
     * @return
     */
    public List<IntroduceDetail> getIntroduceDetailList(Long diseaseId, Integer position) {
        QueryWrapper<IntroduceDetail> introduceDetailQueryWrapper = new QueryWrapper<>();
        String sql = "select introduce_id from icss_introduce_map where question_id=" + diseaseId + " and type=" + QuestionTypeEnum.Disease.getKey();
        introduceDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .apply("find_in_set({0},position)", position)
                .inSql("introduce_id", sql)
                .orderByAsc("introduce_id", "order_no");
        List<IntroduceDetail> introduceDetailList = introduceDetailFacade.list(introduceDetailQueryWrapper);
        return introduceDetailList;
    }

    /**
     * 获取顶级标签
     *
     * @param tagNameList
     * @param type
     * @return
     */
    public List<QuestionInfo> getTopQuestionList(List<String> tagNameList, Integer type) {
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .in("tag_name", tagNameList)
                .eq("sub_type", 0)
                .eq("type", type);
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);
        return questionInfoList;
    }

    /**
     * 获取标签提示信息映射
     *
     * @param questionIdList
     * @param type
     * @return
     */
    public List<IntroduceMap> getIntroduceMapList(List<Long> questionIdList, Integer type) {
        QueryWrapper<IntroduceMap> introduceMapQueryWrapper = new QueryWrapper<>();
        introduceMapQueryWrapper.in("question_id", questionIdList)
                .eq("type", type)
                .eq("is_deleted", IsDeleteEnum.N.getKey());
        List<IntroduceMap> introduceMapList = introduceMapFacade.list(introduceMapQueryWrapper);
        return introduceMapList;
    }
}