package com.ywt.outpatient.controllers.taihe;

import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.DateUtil;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.taihe.outpaitent.GetMedicalCardInfoByPatientIdRequest;
import com.ywt.gapi.taihe.outpaitent.GetMedicalCardInfoByPatientIdResponse;
import com.ywt.gapi.taihe.outpaitent.TaiheOutpatientService;
import com.ywt.gapi.third.cloudfilm.*;
import com.ywt.gapi.third.taihe.*;
import com.ywt.gapi.user.UserService;
import com.ywt.outpatient.api.req.CreateCloudFilmOrderReq;
import com.ywt.outpatient.api.req.GetCloudFilmReportInfoReq;
import com.ywt.outpatient.api.resp.BaseResponse2;
import com.ywt.outpatient.api.resp.CreateCloudFilmOrderResp;
import com.ywt.outpatient.api.resp.GetCloudFilmConfigResp;
import com.ywt.outpatient.api.resp.GetCloudFilmReportInfoResp;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.utils.BizUtil;
import com.ywt.outpatient.core.Constant;
import com.ywt.outpatient.service.web.MedicalCardService;
import com.ywt.outpatient.core.WebAppContext;
import com.ywt.outpatient.service.web.taihe.TaiheUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 太和东华检验检查
 * 由于目前东华接口还可能变动，所以是直接读东华的接口，不是读数据库。
 *
 * @author Walker
 * Created on 2020/2/19
 */
@SuppressWarnings("javadoc")
@RestController("/taihe/dh/inspection")
@RequestMapping(value = {"/taihe/dh/inspection"})
public class DHInspectionController {
    private final Logger logger = LoggerFactory.getLogger(getClass().getName());

    @DubboReference
    private TaiheService taiheServiceBlockingStub;
    @DubboReference
    private TaiheOutpatientService taiheOutpatientServiceBlockingStub;
    @DubboReference
    private UserService userServiceBlockingStub;
    @Autowired
    private TaiheUserService userService;
    @DubboReference
    private CloudfilmService cloudfilmServiceBlockingStub;
    @Autowired
    private MedicalCardService medicalCardService;

    /**
     * 获取检查结果报告列表
     *
     * @return
     */
    @RequestMapping({"/getInspectionReportList"})
    public @ResponseBody
    BaseResponse getInspectionReportList(@RequestParam(name = "patientId") String patientId,
                                         @RequestParam(name = "hospitalId", required = false) Integer hId) {
        BaseResponse response = new BaseResponse();
        List<Map<String, Object>> lst = new LinkedList<>();

        if (Checker.isNone(patientId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "患者Id不存在");
        }
        try {
            int userId = userService.getCurrentUserIdWrapped();
            int hospitalId = Checker.getIntegerValue(hId);
            medicalCardService.verifyMedicalCard(userId, hospitalId, patientId, 0);

            // 从数据库查找诊疗卡信息，不指定医院默认是太和的
            GetMedicalCardInfoByPatientIdRequest req = GetMedicalCardInfoByPatientIdRequest.newBuilder()
                    .setUserId(userId)
                    .setHisPatientId(patientId)
                    .setHospitalId(hospitalId)
                    .build();
            GetMedicalCardInfoByPatientIdResponse resp = taiheOutpatientServiceBlockingStub.getMedicalCardInfoByPatientId(req);
            if (resp.getCode() != ResultCode.SUCCEED_VALUE) {
                return response.failed(BaseResponse.APP_ERROR, "找不到诊疗卡信息");
            }
            hospitalId = resp.getHospitalId();
            switch (hospitalId) {
                case Constant.NFYY_HOSPITAL_ID:
                    com.ywt.gapi.user.GetInspectionReportListRequest nfyyReq = com.ywt.gapi.user.GetInspectionReportListRequest.newBuilder()
                            .setMedicalCardId(resp.getCardId())
                            .setUserId(userService.getCurrentUserIdWrapped())
                            .build();
                    com.ywt.gapi.user.GetInspectionReportListResponse nfyyRes = userServiceBlockingStub.getInspectionReportList(nfyyReq);
                    Result result = nfyyRes.getResult();
                    if (result.getCode() == ResultCode.SUCCEED) {
                        for (com.ywt.gapi.user.InspectionReport report : nfyyRes.getReportList()) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", report.getId());
                            map.put("title", report.getReportTitle());
                            map.put("reportId", report.getReportId());
                            map.put("reportDate", DateUtil.convertTimestampToDateString(report.getReportDate(), "yyyy年MM月dd日"));
                            map.put("hospitalId", Constant.NFYY_HOSPITAL_ID);
                            lst.add(map);
                        }
                        Map<String, Object> data = new HashMap<>();
                        data.put("list", lst);
                        return response.succeed(data);
                    }
                    return response.failed(BaseResponse.APP_ERROR, result.getInfo());
                default:
                case Constant.TAIHE_HOSPITAL_ID:
                case Constant.NFYYBYFY_HOSPITAL_ID:
                    // 需求改动
                    // v3.3.5 太和返回数据库查询的数据 + HIS 接口查询的数据，不去重
                    // 南方医科大学南方医院白云分院v2.1.7（查询优化） 太和只返回HIS接口查询的数据
                    GetInspectionListRequest getInspectionListRequest = GetInspectionListRequest.newBuilder()
                            .setPatientId(patientId)
                            .setHospitalId(hospitalId)
                            .build();
                    GetInspectionListResponse res = taiheServiceBlockingStub.getInspectionList(getInspectionListRequest);

                    if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                        for (InspectionReport report : res.getInspectionReportList()) {
                            String nowDateStr = DateUtil.formatDate(new Date(), "");
                            long diffDay = DateUtil.getDaySubByYMDMS(report.getAuditDate(), nowDateStr);
                            if (diffDay > 180) {
                                continue;
                            }
                            Map<String, Object> map = new HashMap<>();
                            //map.put("id", report.getId());
                            map.put("id", "");
                            map.put("title", report.getReportTitle());
                            map.put("reportId", report.getReportId());
                            map.put("reportDate", report.getAuditDate());
                            map.put("hospitalId", hospitalId);
                            map.put("reportType", report.getReportType());
                            map.put("reportNum", report.getReportNum());
                            lst.add(map);
                        }

                    } else {
                        logger.error("DHInspectionController#getInspectionReportList(patientId={} ):\n" +
                                "taiheServiceBlockingStub#getInspectionList HIS 查询数据失败:{}", patientId, res.getMsg());
                    }
                    /*
                    // 继续查询数据库数据
                    com.ywt.gapi.user.GetInspectionReportListRequest girlReq = com.ywt.gapi.user.GetInspectionReportListRequest.newBuilder()
                            .setMedicalCardId(resp.getCardId())
                            .setUserId(userService.getCurrentUserIdWrapped())
                            .setHospitalId(hospitalId)
                            .build();
                    com.ywt.gapi.user.GetInspectionReportListResponse girlResp = userServiceBlockingStub.getInspectionReportList(girlReq);
                    if (girlResp.getResult().getCode() == ResultCode.SUCCEED) {
                        for (com.ywt.gapi.user.InspectionReport report : girlResp.getReportList()) {
                            String nowDateStr = DateUtil.formatDate(new Date(), "");
                            long diffDay = DateUtil.getDaySubByYMDMS(DateUtil.convertTimestampToDateString(report.getReportDate()), nowDateStr);
                            if (diffDay > 180){
                                continue;
                            }
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", report.getId());
                            map.put("title", report.getReportTitle());
                            map.put("reportId", report.getReportId());
                            map.put("reportDate", DateUtil.convertTimestampToDateString(report.getReportDate(), "yyyy年MM月dd日"));
                            map.put("hospitalId", report.getHospitalId());
                            map.put("reportType", report.getReportType());
                            map.put("reportNum", report.getReportNum());
                            lst.add(map);
                        }
                    } else {
                        logger.error("DHInspectionController#getInspectionReportList(patientId={} ):\n" +
                                "userServiceBlockingStub.getInspectionReportList 失败：{}", patientId, girlResp.getResult().getInfo());
                    }
                     */
                    Map<String, Object> data = new HashMap<>();
                    data.put("list", lst);
                    return response.succeed(data);
            }
        } catch (Exception e) {
            logger.error("RegisterController#getInspectionReportList(patientId={} ):\n {}", patientId, e.getMessage(), e);
            return response.error(e.getMessage());
        }
    }

    /**
     * 获取检查结果报告详情
     *
     * @param reportId
     * @return
     */
    @RequestMapping({"/getInspectionReportDetail"})
    public @ResponseBody
    BaseResponse getInspectionReportDetail(@RequestParam(name = "reportId") String reportId,
                                           @RequestParam(name = "hospitalId", required = false) Integer hospitalId) {
        BaseResponse response = new BaseResponse();
        if (StringHelper.isNullOrWhiteSpace(reportId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误");
        }
        try {
            switch (Checker.getIntegerValue(hospitalId)) {
                case Constant.NFYY_HOSPITAL_ID:
                    com.ywt.gapi.user.GetInspectionReportDetailRequest nfyyReq = com.ywt.gapi.user.GetInspectionReportDetailRequest.newBuilder()
                            .setReportId(reportId)
                            .setHospitalId(hospitalId)
                            .build();
                    com.ywt.gapi.user.GetInspectionReportDetailResponse nfyyRes = userServiceBlockingStub.getInspectionReportDetail(nfyyReq);
                    Result result = nfyyRes.getResult();
                    if (result.getCode() == ResultCode.SUCCEED) {
                        com.ywt.gapi.user.InspectionReportDetail detail = nfyyRes.getReport();
                        Map<String, Object> map = new HashMap<>();
                        map.put("Id", detail.getId());
                        map.put("reportId", detail.getReportId());
                        map.put("deptName", detail.getDeptName());
                        map.put("appDocName", detail.getAppDocName());
                        map.put("checkParts", detail.getCheckParts());
                        map.put("examination", detail.getExamination());
                        map.put("diagnosis", detail.getDiagnosis());
                        map.put("checkDoctorName", detail.getCheckDoctorName());
                        map.put("examinationDate", DateUtil.convertTimestampToDateString(detail.getExaminationDate(), "yyyy年MM月dd日 HH:mm:ss"));
                        return response.succeed(map);
                    }
                    return response.failed(BaseResponse.APP_ERROR, result.getInfo());
                case Constant.TAIHE_HOSPITAL_ID:
                case Constant.NFYYBYFY_HOSPITAL_ID:
                default:
                    GetInspectionDetailRequest req = GetInspectionDetailRequest.newBuilder()
                            .setReportId(reportId)
                            .setHospitalId(hospitalId)
                            .build();
                    GetInspectionDetailResponse res = taiheServiceBlockingStub.getInspectionDetail(req);
                    if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                        InspectionDetail detail = res.getDetail();
                        Map<String, Object> map = new HashMap<>();
                        map.put("Id", "");
                        map.put("reportId", reportId);
                        map.put("deptName", detail.getDeptName());
                        map.put("appDocName", detail.getDoctorName());
                        map.put("checkParts", detail.getInspectionPart());
                        map.put("examination", detail.getInspectionResult());
                        map.put("diagnosis", detail.getDiagnose());
                        map.put("checkDoctorName", detail.getInspectionDoctor());
                        map.put("examinationDate", detail.getInspectionDate());
                        return response.succeed(map);
                    } else {
                        // HIS 接口查不到数据，尝试从本地数据库读取
                        com.ywt.gapi.user.GetInspectionReportDetailRequest girdReq = com.ywt.gapi.user.GetInspectionReportDetailRequest.newBuilder()
                                .setReportId(reportId)
                                .setHospitalId(hospitalId)
                                .build();
                        com.ywt.gapi.user.GetInspectionReportDetailResponse girdResp = userServiceBlockingStub.getInspectionReportDetail(girdReq);
                        if (girdResp.getResult().getCode() == ResultCode.SUCCEED) {
                            com.ywt.gapi.user.InspectionReportDetail detail = girdResp.getReport();
                            Map<String, Object> map = new HashMap<>();
                            map.put("Id", detail.getId());
                            map.put("reportId", detail.getReportId());
                            map.put("deptName", detail.getDeptName());
                            map.put("appDocName", detail.getAppDocName());
                            map.put("checkParts", detail.getCheckParts());
                            map.put("examination", detail.getExamination());
                            map.put("diagnosis", detail.getDiagnosis());
                            map.put("checkDoctorName", detail.getCheckDoctorName());
                            map.put("examinationDate", DateUtil.convertTimestampToDateString(detail.getExaminationDate(), "yyyy年MM月dd日 HH:mm:ss"));
                            return response.succeed(map);
                        } else {
                            return response.failed(BaseResponse.APP_ERROR, girdResp.getResult().getInfo());
                        }
                    }
            }
        } catch (Exception e) {
            logger.error("getInspectionReportDetail({}): {}", reportId, e.getMessage(), e);
            return response.error(e.getMessage());
        }
    }

    /**
     * 获取化验结果报告列表
     *
     * @return
     */
    @RequestMapping({"/getLaboratoryReportList"})
    public @ResponseBody
    BaseResponse getLaboratoryReportList(@RequestParam(name = "patientId") String patientId,
                                         @RequestParam(name = "hospitalId", required = false) Integer hId) {
        BaseResponse response = new BaseResponse();
        List<Map<String, Object>> lst = new LinkedList<>();

        if (Checker.isNone(patientId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "患者Id不存在");
        }

        try {
            int userId = userService.getCurrentUserIdWrapped();
            int hospitalId = Checker.getIntegerValue(hId);
            medicalCardService.verifyMedicalCard(userId, hospitalId, patientId, 0);
            // 从数据库查找诊疗卡信息，不指定医院默认是太和的
            GetMedicalCardInfoByPatientIdRequest req = GetMedicalCardInfoByPatientIdRequest.newBuilder()
                    .setUserId(userId)
                    .setHisPatientId(patientId)
                    .setHospitalId(hospitalId)
                    .build();
            GetMedicalCardInfoByPatientIdResponse resp = taiheOutpatientServiceBlockingStub.getMedicalCardInfoByPatientId(req);
            if (resp.getCode() != ResultCode.SUCCEED_VALUE) {
                return response.failed(BaseResponse.APP_ERROR, "找不到诊疗卡信息");
            }
            hospitalId = resp.getHospitalId();
            switch (hospitalId) {
                case Constant.NFYY_HOSPITAL_ID:
                    // 南方医院的数据从数据库查询
                    com.ywt.gapi.user.GetLaboratoryReportListRequest nfyyReq = com.ywt.gapi.user.GetLaboratoryReportListRequest.newBuilder()
                            .setMedicalCardId(resp.getCardId())
                            .setUserId(userService.getCurrentUserIdWrapped())
                            .build();
                    com.ywt.gapi.user.GetLaboratoryReportListResponse res = userServiceBlockingStub.getLaboratoryReportList(nfyyReq);
                    Result result = res.getResult();
                    if (result.getCode() == ResultCode.SUCCEED) {
                        for (com.ywt.gapi.user.LaboratoryReport report : res.getReportList()) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", report.getId());
                            map.put("title", report.getInspectionName());
                            map.put("inspectionId", report.getInspectionId());
                            map.put("reportDate", DateUtil.convertTimestampToDateString(report.getInspectionDate(), "yyyy年MM月dd日"));
                            map.put("hospitalId", Constant.NFYY_HOSPITAL_ID);
                            lst.add(map);
                        }
                        Map<String, Object> data = new HashMap<>();
                        data.put("list", lst);
                        return response.succeed(data);
                    }
                    return response.failed(BaseResponse.APP_ERROR, result.getInfo());
                default:
                case Constant.TAIHE_HOSPITAL_ID:
                case Constant.NFYYBYFY_HOSPITAL_ID:
                    GetLaboratoryListRequest request = GetLaboratoryListRequest.newBuilder()
                            .setPatientId(patientId)
                            .setHospitalId(hospitalId)
                            .build();
                    GetLaboratoryListResponse thRes = taiheServiceBlockingStub.getLaboratoryList(request);
                    if (thRes.getCode() == ResultCode.SUCCEED_VALUE) {
                        for (LaboratoryReport report : thRes.getReportList()) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", report.getReportId());
                            map.put("title", report.getReportTitle());
                            map.put("inspectionId", report.getReportId());
                            map.put("reportDate", report.getAuditDate());
                            map.put("hospitalId", hospitalId);
                            lst.add(map);
                        }
                    } else {
                        logger.error("DHInspectionController#getLaboratoryReportList(patientId={} ):\n" +
                                "taiheServiceBlockingStub#getLaboratoryList HIS 查询数据失败：{}", patientId, thRes.getMsg());
                    }
                    /*
                    // 继续查询数据库
                    com.ywt.gapi.user.GetLaboratoryReportListRequest glrlReq = com.ywt.gapi.user.GetLaboratoryReportListRequest.newBuilder()
                            .setMedicalCardId(resp.getCardId())
                            .setUserId(userService.getCurrentUserIdWrapped())
                            .setHospitalId(hospitalId)
                            .build();
                    com.ywt.gapi.user.GetLaboratoryReportListResponse glrlResp = userServiceBlockingStub.getLaboratoryReportList(glrlReq);
                    if (glrlResp.getResult().getCode() == ResultCode.SUCCEED) {
                        for (com.ywt.gapi.user.LaboratoryReport report : glrlResp.getReportList()) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("id", report.getId());
                            map.put("title", report.getInspectionName());
                            map.put("inspectionId", report.getInspectionId());
                            map.put("reportDate", DateUtil.convertTimestampToDateString(report.getInspectionDate(), "yyyy年MM月dd日"));
                            map.put("hospitalId", report.getHospitalId());
                            lst.add(map);
                        }
                    } else {
                        logger.error("DHInspectionController#getLaboratoryReportList(patientId={} ):\n" +
                                "userServiceBlockingStub.getLaboratoryReportList 失败：{}", patientId, glrlResp.getResult().getInfo());
                    }
                     */
                    Map<String, Object> data = new HashMap<>();
                    data.put("list", lst);
                    return response.succeed(data);
            }
        } catch (Exception e) {
            logger.error("RegisterController#getLaboratoryReportList(patientId={} ):\n {}", patientId, e.getMessage(), e);
            return response.error(e.getMessage());
        }
    }

    /**
     * 获取检查结果报告详情
     *
     * @param inspectionId
     * @return
     */
    @RequestMapping({"/getLaboratoryReportDetail"})
    public @ResponseBody
    BaseResponse getLaboratoryReportDetail(@RequestParam(name = "inspectionId") String inspectionId,
                                           @RequestParam(name = "hospitalId", required = false) Integer hospitalId) {
        BaseResponse response = new BaseResponse();
        if (StringHelper.isNullOrWhiteSpace(inspectionId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "参数错误");
        }

        try {
            switch (Checker.getIntegerValue(hospitalId)) {
                case Constant.NFYY_HOSPITAL_ID:
                    com.ywt.gapi.user.GetLaboratoryReportDetailRequest nfyyReq = com.ywt.gapi.user.GetLaboratoryReportDetailRequest.newBuilder()
                            .setInspectionId(inspectionId)
                            .setHospitalId(hospitalId)
                            .build();
                    com.ywt.gapi.user.GetLaboratoryReportDetailResponse nfyyRes = userServiceBlockingStub.getLaboratoryReportDetail(nfyyReq);
                    Result result = nfyyRes.getResult();

                    if (result.getCode() == ResultCode.SUCCEED) {
                        String specimenNo = "";
                        List<Map<String, Object>> lst = new LinkedList<>();
                        for (com.ywt.gapi.user.LaboratoryReportDetail detail : nfyyRes.getDetailList()) {
                            if (!StringHelper.isNullOrWhiteSpace(detail.getSpecimType())) {
                                specimenNo = detail.getSpecimType();
                            }
                            Map<String, Object> itemMap = new LinkedHashMap<>();
                            itemMap.put("itemId", detail.getItemId());
                            itemMap.put("itemName", detail.getItemName());
                            itemMap.put("itemRef", detail.getItemRef());
                            itemMap.put("orderNo", detail.getOrderNo());
                            itemMap.put("resultFlag", detail.getResultFlag());
                            itemMap.put("specimType", detail.getSpecimType());
                            itemMap.put("testDate", DateUtil.convertTimestampToDateString(detail.getTestDate(), "yyyy-MM-dd HH:mm:ss"));
                            itemMap.put("testEngName", detail.getTestEngName());
                            itemMap.put("testResult", detail.getTestResult());
                            itemMap.put("unit", detail.getUnit());
                            lst.add(itemMap);
                        }
                        Map<String, Object> data = new LinkedHashMap<>();
                        data.put("title", nfyyRes.getInspectionName());
                        data.put("reportDate", DateUtil.convertTimestampToDateString(nfyyRes.getInspectionDate()));
                        data.put("status", nfyyRes.getStatus() == 0 ? "未审核" : "已审核");
                        data.put("checkDoctorName", nfyyRes.getCheckDoctorName());
                        data.put("specimenNo", specimenNo);
                        data.put("count", lst.size());
                        data.put("list", lst);
                        return response.succeed(data);
                    }
                    return response.failed(BaseResponse.APP_ERROR, result.getInfo());
                case Constant.TAIHE_HOSPITAL_ID:
                case Constant.NFYYBYFY_HOSPITAL_ID:
                default:
                    GetLaboratoryDetailRequest req = GetLaboratoryDetailRequest.newBuilder()
                            .setInspectionId(inspectionId)
                            .setHospitalId(hospitalId)
                            .build();
                    GetLaboratoryDetailResponse res = taiheServiceBlockingStub.getLaboratoryDetail(req);
                    if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                        String specimenNo = "";
                        List<Map<String, Object>> lst = new LinkedList<>();
                        for (LaboratoryDetail detail : res.getDetailList()) {
                            if (!StringHelper.isNullOrWhiteSpace(detail.getSpecimType())) {
                                specimenNo = detail.getSpecimType();
                            }
                            Map<String, Object> itemMap = new LinkedHashMap<>();
                            itemMap.put("itemId", detail.getItemId());
                            itemMap.put("itemName", detail.getItemName());
                            itemMap.put("itemRef", detail.getItemRef());
                            itemMap.put("orderNo", detail.getOrderNo());
                            itemMap.put("resultFlag", detail.getResultFlag());
                            itemMap.put("specimType", detail.getSpecimType());
                            itemMap.put("testDate", detail.getTestDate());
                            itemMap.put("testEngName", detail.getTestEngName());
                            itemMap.put("testResult", detail.getTestResult());
                            itemMap.put("unit", detail.getUnit());
                            lst.add(itemMap);
                        }
                        Map<String, Object> data = new LinkedHashMap<>();
//                data.put("title", res.getInspectionName());
//                data.put("reportDate", DateUtil.convertTimestampToDateString(res.getInspectionDate()));
//                data.put("status", res.getStatus() == 0 ? "未审核" : "已审核");
//                data.put("checkDoctorName", res.getCheckDoctorName());
                        data.put("title", res.getTitle());
                        data.put("reportDate", res.getTime());
                        data.put("status", "");
                        data.put("checkDoctorName", res.getDoctor());
                        data.put("specimenNo", res.getSpecimenNo());
                        data.put("count", lst.size());
                        data.put("list", lst);
                        return response.succeed(data);
                    } else {
                        // HIS 没有返回数据，尝试从数据库读取
                        com.ywt.gapi.user.GetLaboratoryReportDetailRequest glrdReq = com.ywt.gapi.user.GetLaboratoryReportDetailRequest.newBuilder()
                                .setInspectionId(inspectionId)
                                .setHospitalId(hospitalId)
                                .build();
                        com.ywt.gapi.user.GetLaboratoryReportDetailResponse glrdResp = userServiceBlockingStub.getLaboratoryReportDetail(glrdReq);
                        if (glrdResp.getResult().getCode() == ResultCode.SUCCEED) {
                            String specimenNo = "";
                            List<Map<String, Object>> lst = new LinkedList<>();
                            for (com.ywt.gapi.user.LaboratoryReportDetail detail : glrdResp.getDetailList()) {
                                if (!StringHelper.isNullOrWhiteSpace(detail.getSpecimType())) {
                                    specimenNo = detail.getSpecimType();
                                }
                                Map<String, Object> itemMap = new LinkedHashMap<>();
                                itemMap.put("itemId", detail.getItemId());
                                itemMap.put("itemName", detail.getItemName());
                                itemMap.put("itemRef", detail.getItemRef());
                                itemMap.put("orderNo", detail.getOrderNo());
                                itemMap.put("resultFlag", detail.getResultFlag());
                                itemMap.put("specimType", detail.getSpecimType());
                                itemMap.put("testDate", DateUtil.convertTimestampToDateString(detail.getTestDate(), "yyyy-MM-dd HH:mm:ss"));
                                itemMap.put("testEngName", detail.getTestEngName());
                                itemMap.put("testResult", detail.getTestResult());
                                itemMap.put("unit", detail.getUnit());
                                lst.add(itemMap);
                            }
                            Map<String, Object> data = new LinkedHashMap<>();
                            data.put("title", glrdResp.getInspectionName());
                            data.put("reportDate", DateUtil.convertTimestampToDateString(glrdResp.getInspectionDate()));
                            data.put("status", glrdResp.getStatus() == 0 ? "未审核" : "已审核");
                            data.put("checkDoctorName", glrdResp.getCheckDoctorName());
                            data.put("specimenNo", specimenNo);
                            data.put("count", lst.size());
                            data.put("list", lst);
                            return response.succeed(data);
                        } else {
                            return response.failed(BaseResponse.APP_ERROR, glrdResp.getResult().getInfo());
                        }
                    }
            }
        } catch (Exception e) {
            logger.error("getLaboratoryReportDetail({}): {}", inspectionId, e.getMessage(), e);
            return response.error(e.getMessage());
        }
    }

    /**
     * 创建云胶片 3D 订单
     *
     * @param reqData
     * @return
     */
    @RequestMapping(value = {"/cloudFilm/createOrder"}, method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse2<CreateCloudFilmOrderResp> createCloudFilmOrder(@RequestBody CreateCloudFilmOrderReq reqData) {
        BaseResponse2<CreateCloudFilmOrderResp> baseResponse = new BaseResponse2<>();
        try {
            CreateOrderRequest request = CreateOrderRequest.newBuilder()
                    .setCheckResultId(Checker.getStringValue(reqData.getCheckResultId()))
                    .setMedicalCardId(Checker.getIntegerValue(reqData.getMedicalCardId()))
                    .setReportNum(Checker.getStringValue(reqData.getReportNum()))
                    .setReportType(Checker.getStringValue(reqData.getReportType()))
                    .setTerminal(WebAppContext.current().getTerminal())
                    .build();
            CreateOrderResponse response = cloudfilmServiceBlockingStub.createOrder(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                CreateCloudFilmOrderResp resp = new CreateCloudFilmOrderResp();
                resp.setOrderId(response.getOrderId());
                resp.setOrderNo(response.getOrderNo());
                resp.setPaid(response.getIsPaid());
                return baseResponse.succeed(resp);
            }
            return baseResponse.failed(BaseResponse.APP_ERROR, response.getMsg());
        } catch (Exception e) {
            logger.error("DHInspectionController#createCloudFilmOrder(): {}", e.getMessage(), e);
            return baseResponse.error(e.getMessage());
        }
    }

    /**
     * 获取云胶片配置，如订单价格，预计出结果时间等
     *
     * @param reqData
     * @return
     */
    @RequestMapping(value = {"/cloudFilm/config"}, method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse2<GetCloudFilmConfigResp> cloudFilmConfig(@RequestBody Void reqData) {
        BaseResponse2<GetCloudFilmConfigResp> baseResponse = new BaseResponse2<>();
        try {
            int hospitalId = BizUtil.getHospitalIdByTerminalId(BizUtil.getCurrentTerminalWrapped());
            GetConfigResponse response = cloudfilmServiceBlockingStub.getConfig(GetConfigRequest.newBuilder().setHospitalId(hospitalId).build());
            if (response.getCode() == BaseResponse.SUCCEED) {
                GetCloudFilmConfigResp resp = new GetCloudFilmConfigResp();
                resp.setCheckResultFee(response.getCheckResultFee());
                resp.setEstWaitTime(response.getEstWaitTime());
                return baseResponse.succeed(resp);
            }
            return baseResponse.failed(BaseResponse.APP_ERROR, response.getInfo());
        } catch (Exception e) {
            logger.error("DHInspectionController#cloudFilm/config(): {}", e.getMessage(), e);
            return baseResponse.error(e.getMessage());
        }
    }

    /**
     * 获取报告相关云胶片信息
     *
     * @param reqData
     * @return
     */
    @RequestMapping(value = {"/cloudFilm/reportInfo"}, method = RequestMethod.POST)
    public @ResponseBody
    BaseResponse2<GetCloudFilmReportInfoResp> reportInfo(@RequestBody GetCloudFilmReportInfoReq reqData) {
        BaseResponse2<GetCloudFilmReportInfoResp> baseResponse = new BaseResponse2<>();
        try {
            GetReportInfoRequest request = GetReportInfoRequest.newBuilder()
                    .setMedicalCardId(Checker.getIntegerValue(reqData.getMedicalCardId()))
                    .setReportDate(Checker.getStringValue(reqData.getReportDate()))
                    .setReportId(Checker.getStringValue(reqData.getReportId()))
                    .setReportNum(Checker.getStringValue(reqData.getReportNum()))
                    .setReportType(Checker.getStringValue(reqData.getReportType()))
                    .build();
            GetReportInfoResponse response = cloudfilmServiceBlockingStub.getReportInfo(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                GetCloudFilmReportInfoResp resp = new GetCloudFilmReportInfoResp();
                resp.setOrderId(response.getOrderId());
                resp.setUrl2D(response.getUrl2D());
                resp.setUrl3D(response.getUrl3D());
                resp.setVisible2D(response.getVisible2D());
                resp.setVisible3D(response.getVisible3D());
                return baseResponse.succeed(resp);
            }
            return baseResponse.failed(BaseResponse.APP_ERROR, response.getInfo());
        } catch (Exception e) {
            logger.error("DHInspectionController#reportInfo(): {}", e.getMessage(), e);
            return baseResponse.error(e.getMessage());
        }
    }
}
