package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.client.TranServiceClient;
import com.diagbot.dto.EMRIntroduceDetailDTO;
import com.diagbot.dto.IntroduceDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.IntroduceDetail;
import com.diagbot.entity.IntroduceInfo;
import com.diagbot.entity.IntroduceMap;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.QuestionTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.IntroduceInfoServiceImpl;
import com.diagbot.util.ArrayUtil;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.RespDTOUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.EMRIntroduceVO;
import com.diagbot.vo.HosCodeVO;
import com.diagbot.vo.IntroduceByQuestionVO;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2018/11/16 9:27
 */
@Component
public class IntroduceInfoFacade extends IntroduceInfoServiceImpl {
    @Autowired
    IntroduceMapFacade introduceMapFacade;
    @Autowired
    IntroduceDetailFacade introduceDetailFacade;
    @Autowired
    QuestionFacade questionFacade;
    @Autowired
    TranServiceClient tranServiceClient;
    @Autowired
    LisMappingFacade lisMappingFacade;

    /**
     * 根据标签id获取提示信息
     *
     * @param introduceByQuestionVO
     * @return
     */
    public IntroduceDTO getByQuestionId(IntroduceByQuestionVO introduceByQuestionVO) {
        Long questionId = introduceByQuestionVO.getQuestionId();
        if (questionId == null) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL, "请输入标签id");
        }
        QuestionInfo questionInfo = questionFacade.getById(questionId);
        if (questionInfo == null) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL, "未找到标签");
        }
        QueryWrapper<IntroduceMap> introduceMapQueryWrapper = new QueryWrapper<>();
        introduceMapQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("question_id", introduceByQuestionVO.getQuestionId()).
                eq("type", introduceByQuestionVO.getType());
        IntroduceMap introduceMap = introduceMapFacade.getOne(introduceMapQueryWrapper);
        if (introduceMap == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "提示信息未维护");
        }

        IntroduceDTO introduceDTO = this.getRecordByIdAndPosition(introduceMap.getIntroduceId(), introduceByQuestionVO.getPosition());
        introduceDTO.setTagName(questionInfo.getTagName());
        return introduceDTO;
    }

    /**
     * 根据标签名称获取提示信息
     *
     * @param introduceByQuestionVO
     * @return
     */
    public IntroduceDTO getByQuestionName(IntroduceByQuestionVO introduceByQuestionVO) {
        if (StringUtil.isBlank(introduceByQuestionVO.getTagName())) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL, "请输入标签名称");
        }
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("tag_name", introduceByQuestionVO.getTagName())
                .eq("type", QuestionTypeEnum.Disease.getKey());
        QuestionInfo questionInfo = questionFacade.getOne(questionInfoQueryWrapper);
        if (questionInfo == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "标签不存在");
        }

        QueryWrapper<IntroduceMap> introduceMapQueryWrapper = new QueryWrapper<>();
        introduceMapQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("question_id", questionInfo.getId()).
                eq("type", introduceByQuestionVO.getType());
        IntroduceMap introduceMap = introduceMapFacade.getOne(introduceMapQueryWrapper);
        if (introduceMap == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "提示信息未维护");
        }

        IntroduceDTO introduceDTO = this.getRecordByIdAndPosition(introduceMap.getIntroduceId(), introduceByQuestionVO.getPosition());
        introduceDTO.setTagName(questionInfo.getTagName());
        return introduceDTO;
    }

    /**
     * 获取指定位置提示信息
     *
     * @param id
     * @param position
     * @return
     */
    public IntroduceDTO getRecordByIdAndPosition(Long id, Integer position) {
        IntroduceDTO introduceDTO = new IntroduceDTO();
        IntroduceInfo introduceInfo = this.getById(id);
        if (introduceInfo == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "提示信息未维护");
        } else if (introduceInfo.getIsDeleted().equals(IsDeleteEnum.Y.getKey())) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "提示信息已删除");
        }
        BeanUtil.copyProperties(introduceInfo, introduceDTO);


        QueryWrapper<IntroduceDetail> introduceDetailQueryWrapper = new QueryWrapper<>();
        //展示位置
        if (position != null) {
            introduceDetailQueryWrapper.apply("find_in_set({0},position)", position);
        }
        introduceDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("introduce_id", introduceInfo.getId()).
                orderByAsc("order_no");
        List<IntroduceDetail> introduceDetailList = introduceDetailFacade.list(introduceDetailQueryWrapper);
        introduceDTO.setIntroduceDetailList(introduceDetailList);
        return introduceDTO;
    }

    /**
     * 根据id获取提示信息
     *
     * @param id
     * @return
     */
    public IntroduceDTO getRecordById(Long id) {
        return getRecordByIdAndPosition(id, null);
    }

    /**
     * 获取电子病历评级提示信息
     *
     * @param emrIntroduceVO
     * @return
     */
    public List<EMRIntroduceDetailDTO> getIntroduceByEMR(EMRIntroduceVO emrIntroduceVO) {
        Boolean isDocking = tranServiceClient.isDocking().data;
        //入参处理
        HosCodeVO hosCodeVO = new HosCodeVO();
        hosCodeVO.setHosCode(emrIntroduceVO.getHosCode());
        //公表转换
        String uniqueName = "";
        Integer type = emrIntroduceVO.getType();
        if (type.equals(QuestionTypeEnum.Lis.getKey())) {
            if (StringUtil.isNotBlank(emrIntroduceVO.getName())) {
                if (StringUtil.isNotBlank(emrIntroduceVO.getDetailName())) {
                    Map<String, Map<String, String>> lisConfigMap = new LinkedHashMap<>();
                    if (isDocking) {
                        RespDTO<Map<String, Map<String, String>>> respLisConfigMap = tranServiceClient.getLisConfigByHosCode_NotEmptyItemName(hosCodeVO);
                        if (RespDTOUtil.respIsNG(respLisConfigMap)) {
                            throw new CommonException(CommonErrorCode.RPC_ERROR);
                        }
                        lisConfigMap = respLisConfigMap.data;
                    } else {
                        lisConfigMap = lisMappingFacade.getLisMapping_NotEmptyItemName();
                    }

                    uniqueName = lisConfigMap.get(emrIntroduceVO.getName()).get(emrIntroduceVO.getDetailName());
                } else {
                    Map<String, String> lisConfigMap_emptyItemName = new LinkedHashMap<>();
                    if (isDocking) {
                        RespDTO<Map<String, String>> respLisConfigMap_emptyItemName = tranServiceClient.getLisConfigByHosCode_EmptyItemName(hosCodeVO);
                        if (RespDTOUtil.respIsNG(respLisConfigMap_emptyItemName)) {
                            throw new CommonException(CommonErrorCode.RPC_ERROR);
                        }
                        lisConfigMap_emptyItemName = respLisConfigMap_emptyItemName.data;
                    } else {
                        lisConfigMap_emptyItemName = lisMappingFacade.getLisConfig_EmptyItemName();
                    }
                    uniqueName = lisConfigMap_emptyItemName.get(emrIntroduceVO.getName());
                }
            }
        } else if (type.equals(QuestionTypeEnum.Pacs.getKey())) {
            if (isDocking) {
                RespDTO<Map<String, String>> respPacsConfigMap = tranServiceClient.getPacsConfigByHosCode(hosCodeVO);
                if (RespDTOUtil.respIsNG(respPacsConfigMap)) {
                    throw new CommonException(CommonErrorCode.RPC_ERROR);
                }
                Map<String, String> pacsConfigMap = respPacsConfigMap.data;
                uniqueName = pacsConfigMap.get(emrIntroduceVO.getName());
            } else {
                uniqueName = emrIntroduceVO.getName();
            }
        } else if (type.equals(QuestionTypeEnum.Disease.getKey())) {
            if (isDocking) {
                RespDTO<Map<String, String>> respDisMap = tranServiceClient.getDiseaseIcdByHosCode(hosCodeVO);
                if (RespDTOUtil.respIsNG(respDisMap)) {
                    throw new CommonException(CommonErrorCode.RPC_ERROR);
                }
                Map<String, String> disMap = respDisMap.data;
                uniqueName = disMap.get(emrIntroduceVO.getName());
            } else {
                uniqueName = emrIntroduceVO.getName();
            }
        }

        //未找到映射标签名称
        if (uniqueName == null || StringUtil.isBlank(uniqueName)) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "项目未找到");
        }

        String[] titles = emrIntroduceVO.getTitles();
        //对接标题映射
        Map<String, String> titleMapping = new LinkedHashMap<>();
        List<String> uniqueTitleList = Lists.newLinkedList();
        if (ArrayUtil.isNotEmpty(titles)) {
            if (isDocking) {
                RespDTO<Map<String, String>> respTitleMappingMap = tranServiceClient.getTitleMappingHosCode(hosCodeVO);
                if (RespDTOUtil.respIsNG(respTitleMappingMap)) {
                    throw new CommonException(CommonErrorCode.RPC_ERROR);
                }
                Map<String, String> titleMappingMap = respTitleMappingMap.data;
                for (String title : titles) {
                    String uniqueTitle = titleMappingMap.get(title);
                    titleMapping.put(title, uniqueTitle);
                    if (StringUtil.isNotBlank(uniqueTitle)) {
                        uniqueTitleList.add(uniqueTitle);
                    }
                }
            } else {
                uniqueTitleList = Arrays.asList(titles);
            }
        }

        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("tag_name", uniqueName)
                .eq("type", type);
        QuestionInfo questionInfo = questionFacade.getOne(questionInfoQueryWrapper);
        if (questionInfo == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "公表标签不存在");
        }


        QueryWrapper<IntroduceMap> introduceMapQueryWrapper = new QueryWrapper<>();
        introduceMapQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("type", type).
                eq("question_id", questionInfo.getId());
        IntroduceMap introduceMap = introduceMapFacade.getOne(introduceMapQueryWrapper);
        if (introduceMap == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "提示信息未维护");
        }

        QueryWrapper<IntroduceDetail> introduceDetailQueryWrapper = new QueryWrapper<>();
        introduceDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("introduce_id", introduceMap.getIntroduceId()).
                orderByAsc("order_no");
        //如果标题列表未传，全部返回
        if (ArrayUtil.isNotEmpty(emrIntroduceVO.getTitles())) {
            if (ListUtil.isNotEmpty(uniqueTitleList)) {
                introduceDetailQueryWrapper.in("title", uniqueTitleList);
            } else {
                //标题未匹配上，不返回数据,加一个不成立的条件
                introduceDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.Y.getKey());
            }
        }
        List<IntroduceDetail> introduceDetailList = introduceDetailFacade.list(introduceDetailQueryWrapper);
        List<EMRIntroduceDetailDTO> retList = Lists.newLinkedList();
        if (ArrayUtil.isNotEmpty(emrIntroduceVO.getTitles())) {
            //对接模式，返回原标题
            if (isDocking) {
                for (Map.Entry<String, String> entry : titleMapping.entrySet()) {
                    EMRIntroduceDetailDTO detailDTO = new EMRIntroduceDetailDTO();
                    detailDTO.setTitle(entry.getKey());
                    if (StringUtil.isNotBlank(entry.getValue())) {
                        for (IntroduceDetail introduceDetail : introduceDetailList) {
                            if (entry.getValue().equals(introduceDetail.getTitle())) {
                                detailDTO.setText(introduceDetail.getText());
                            }
                        }
                    }
                    retList.add(detailDTO);
                }
            } else {
                retList = BeanUtil.listCopyTo(introduceDetailList, EMRIntroduceDetailDTO.class);
            }
        } else {
            retList = BeanUtil.listCopyTo(introduceDetailList, EMRIntroduceDetailDTO.class);
        }
        return retList;
    }
}