package com.ywt.outpatient.controllers;

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.user.*;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.service.web.UserSrv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 检验检查报告
 */
@RestController
@RequestMapping({"/report"})
public class ReportController {
    private static Logger logger = LoggerFactory.getLogger(ReportController.class);

    @Autowired
    private UserSrv userSrv;

    @Autowired
    private UserService userServiceBlockingStub;

    /**
     * 获取检查结果报告列表
     *
     * @return
     */
    @RequestMapping({"/check/list"})
    public @ResponseBody
    BaseResponse getCheckReportList(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        String hisPatientId = (String) reqBody.getOrDefault("hisPatientId", "");//门诊ID
        List<Map<String, Object>> lst = new LinkedList<>();

        if (StringHelper.isNullOrWhiteSpace(hisPatientId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid hisPatientId");
        }

        try {
            GetInspectionReportListByHisPatientIdRequest req = GetInspectionReportListByHisPatientIdRequest.newBuilder()
                    .setHisPatientId(hisPatientId)
                    .build();
            GetInspectionReportListByHisPatientIdResponse res = userServiceBlockingStub.getInspectionReportListByHisPatientId(req);

            if(res.getCode() == ResultCode.SUCCEED_VALUE){
                Map<String, Object> map;
                for (InspectionReport report : res.getReportList()) {
                    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日"));
                    lst.add(map);
                }

                Map<String, Object> data = new HashMap<>();
                data.put("list", lst);
                return response.succeed(data);
            }
            return response.failed(BaseResponse.APP_ERROR, res.getMsg());
        } catch (Exception e) {
            logger.error("getCheckReportList({}): {}", hisPatientId, e.getMessage(), e);
            return response.error();
        }
    }

    /**
     * 获取检查结果报告详情
     *
     * @return
     */
    @RequestMapping({"/check/detail"})
    public @ResponseBody
    BaseResponse getInspectionReportDetail(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        String reportId = (String)reqBody.getOrDefault("reportId", "");

        if (StringHelper.isNullOrWhiteSpace(reportId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid reportId");
        }

        try {
            GetInspectionReportDetailRequest req = GetInspectionReportDetailRequest.newBuilder()
                    .setReportId(reportId)
                    .build();
            com.ywt.gapi.user.GetInspectionReportDetailResponse res = userServiceBlockingStub.getInspectionReportDetail(req);
            Result result = res.getResult();
            if (result.getCode() == ResultCode.SUCCEED) {
                com.ywt.gapi.user.InspectionReportDetail detail = res.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());
        } catch (Exception e) {
            logger.error("getInspectionReportDetail({}): {}", reportId, e.getMessage(), e);
            return response.error();
        }
    }

    /**
     * 获取化验结果报告列表
     *
     * @return
     */
    @RequestMapping({"/inspection/list"})
    public @ResponseBody
    BaseResponse getInspectionReportList(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        String hisPatientId = (String) reqBody.getOrDefault("hisPatientId", "");//门诊ID

        if (StringHelper.isNullOrWhiteSpace(hisPatientId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid hisPatientId");
        }

        try {
            List<Map<String, Object>> lst = new LinkedList<>();
            GetLaboratoryReportListByHisPatientIdRequest req = GetLaboratoryReportListByHisPatientIdRequest.newBuilder()
                    .setHisPatientId(hisPatientId)
                    .build();
            GetLaboratoryReportListByHisPatientIdResponse res = userServiceBlockingStub.getLaboratoryReportByListByHisPatientId(req);

            if (res.getCode() == ResultCode.SUCCEED_VALUE) {
                for (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日"));
                    lst.add(map);
                }
                Map<String, Object> data = new HashMap<>();
                data.put("list", lst);
                return response.succeed(data);
            }

            return response.failed(BaseResponse.APP_ERROR, res.getMsg());
        } catch (Exception e) {
            logger.error("getLaboratoryReportList({}): {}", hisPatientId, e.getMessage(), e);
            return response.error();
        }
    }

    /**
     * 获取检查结果报告详情
     *
     * @return
     */
    @RequestMapping({"/inspection/detail"})
    public @ResponseBody
    BaseResponse getLaboratoryReportDetail(@RequestBody Map<String, Object> reqBody) {
        BaseResponse response = new BaseResponse();
        String inspectionId = (String)reqBody.getOrDefault("inspectionId", "");

        if (StringHelper.isNullOrWhiteSpace(inspectionId)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "invalid inspectionId");
        }

        try {
           GetLaboratoryReportDetailRequest req = GetLaboratoryReportDetailRequest.newBuilder()
                    .setInspectionId(inspectionId)
                    .build();
            com.ywt.gapi.user.GetLaboratoryReportDetailResponse res = userServiceBlockingStub.getLaboratoryReportDetail(req);
            Result result = res.getResult();

            if (result.getCode() == ResultCode.SUCCEED) {
                List<Map<String, Object>> lst = new LinkedList<>();

                for (com.ywt.gapi.user.LaboratoryReportDetail detail : res.getDetailList()) {
                    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", res.getInspectionName());
                data.put("reportDate", DateUtil.convertTimestampToDateString(res.getInspectionDate()));
                data.put("status", res.getStatus() == 0 ? "未审核" : "已审核");
                data.put("checkDoctorName", res.getCheckDoctorName());
                data.put("specimenNo", "");
                data.put("count", lst.size());
                data.put("list", lst);
                return response.succeed(data);
            }
            return response.failed(BaseResponse.APP_ERROR, result.getInfo());
        } catch (Exception e) {
            logger.error("getInspectionReportDetail({}): {}", inspectionId, e.getMessage(), e);
            return response.error();
        }
    }
}
