package com.ywt.outpatient.service.web;

import com.ywt.biz.common.constant.YwtCommonRespCode;
import com.ywt.biz.common.exception.YwtCommonException;
import com.ywt.biz.common.util.Checker;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.user.GetMedicalCardListRequest;
import com.ywt.gapi.user.GetMedicalCardListResponse;
import com.ywt.gapi.user.MedicalCard;
import com.ywt.gapi.user.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

@Service
public class MedicalCardService {
    private static final Logger logger = LoggerFactory.getLogger(MedicalCardService.class);

    @DubboReference
    private UserService userServiceBlockingStub;

    /**
     * 判断当前用户使用的 hisPatientId 是否本人绑定的卡号
     *
     * @param userId       用户 id
     * @param hospitalId   医院 id，如果小于等于 0 表示查询所有医院的绑定卡
     * @param hisPatientId 查询使用的 hisPatientId
     * @throws YwtCommonException 查询异常或非本人诊疗卡会抛异常，调用方可以根据 message 自行处理前端返回提示
     */
    public void verifyMedicalCard(int userId, int hospitalId, String hisPatientId, int type) throws YwtCommonException {
        if (userId <= 0) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "请登录后操作");
        try {
            GetMedicalCardListRequest getMedicalCardListRequest = GetMedicalCardListRequest.newBuilder()
                    .setHospitalId(hospitalId)
                    .setUserId(userId)
                    .setType(type)
                    .build();
            GetMedicalCardListResponse getMedicalCardListResponse = userServiceBlockingStub.getMedicalCardList(getMedicalCardListRequest);
            Result result = getMedicalCardListResponse.getResult();
            if (result.getCode() == ResultCode.SUCCEED) {
                boolean isHisPatientIdPersonal = getMedicalCardListResponse.getMedicalCardsList().stream()
                        .map(MedicalCard::getHisPatientId)
                        .collect(Collectors.toList())
                        .contains(hisPatientId);
                if (!isHisPatientIdPersonal) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "当前诊疗卡非本人绑定卡");
            } else {
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "获取本人诊疗卡数据失败：" + result.getInfo());
            }
        } catch (Exception e) {
            logger.error("MedicalCardService#verifyMedicalCard(userId={} , hospitalId={} , hisPatientId={} ):\n {}", userId, hospitalId, hisPatientId, e.getMessage(), e);
            throw new YwtCommonException(YwtCommonRespCode.P_ERR, "查询诊疗卡绑定关系出错：" + Checker.getStringValue(e.getMessage()));
        }
    }

    /**
     * 判断当前用户使用的 hisPatientId 是否本人绑定的卡号
     *
     * @param userId       用户 id
     * @param hospitalId   医院 id，如果小于等于 0 表示查询所有医院的绑定卡
     * @param medicalCardId 查询使用的 medicalCardId
     * @throws YwtCommonException 查询异常或非本人诊疗卡会抛异常，调用方可以根据 message 自行处理前端返回提示
     */
    public void verifyMedicalCard(int userId, int hospitalId, int medicalCardId) throws YwtCommonException {
        if (userId <= 0) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "请登录后操作");
        try {
            GetMedicalCardListRequest getMedicalCardListRequest = GetMedicalCardListRequest.newBuilder()
                    .setHospitalId(hospitalId)
                    .setUserId(userId)
                    .build();
            GetMedicalCardListResponse getMedicalCardListResponse = userServiceBlockingStub.getMedicalCardList(getMedicalCardListRequest);
            Result result = getMedicalCardListResponse.getResult();
            if (result.getCode() == ResultCode.SUCCEED) {
                boolean isHisPatientIdPersonal = getMedicalCardListResponse.getMedicalCardsList().stream()
                        .map(MedicalCard::getCardId)
                        .collect(Collectors.toList())
                        .contains(medicalCardId);
                if (!isHisPatientIdPersonal) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "当前诊疗卡非本人绑定卡");
            } else {
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "获取本人诊疗卡数据失败：" + result.getInfo());
            }
        } catch (Exception e) {
            logger.error("MedicalCardService#verifyMedicalCard(userId={} , hospitalId={} , medicalCardId={} ):\n {}", userId, hospitalId, medicalCardId, e.getMessage(), e);
            throw new YwtCommonException(YwtCommonRespCode.P_ERR, "查询诊疗卡绑定关系出错：" + Checker.getStringValue(e.getMessage()));
        }
    }
}