package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.client.TranServiceClient;
import com.diagbot.dto.GetDiseaseIcdDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.vo.GetDiseaseIcdVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: wangyu
 * @time: 2019/2/14 15:25
 */
@Component
public class TranDiseaseIcdFacade {

    @Autowired
    TranServiceClient tranServiceClient;
    @Autowired
    QuestionFacade questionFacade;

    /**
     * 根据医院编号和诊断ids获取各自的icd编码
     *
     * @param getDiseaseIcdVO
     * @return
     */
    public List<GetDiseaseIcdDTO> getDiseaseIcds(GetDiseaseIcdVO getDiseaseIcdVO) {
        RespDTO<List<GetDiseaseIcdDTO>> getDiseaseIcdsList =  tranServiceClient.getDiseaseIcds(getDiseaseIcdVO);
        if (getDiseaseIcdsList == null
                || !CommonErrorCode.OK.getCode().equals(getDiseaseIcdsList.code)) {
            throw new CommonException(CommonErrorCode.RPC_ERROR,
                    "获取icd编码失败");
        }
        List<String> questionNames = getDiseaseIcdsList.data.stream().map(getDiseaseIcdDTO -> getDiseaseIcdDTO.getIcssQuestionName()).collect(Collectors.toList());
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
            .in("name",questionNames);
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);
        for (GetDiseaseIcdDTO getDiseaseIcdDTO: getDiseaseIcdsList.data) {
            for (QuestionInfo questionInfo: questionInfoList) {
                if(getDiseaseIcdDTO.getIcssQuestionName().equals(questionInfo.getName())){
                    getDiseaseIcdDTO.setQuestionId(questionInfo.getId());
                }
            }
        }
        return getDiseaseIcdsList.data;
    }
}
