package thyyxxk.webserver.service.examinations;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.envionment.ApiUrl;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.examinations.InspectionsDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.examinations.inspections.consts.PatientNumType;
import thyyxxk.webserver.entity.examinations.inspections.request.ReportDetailInquiry;
import thyyxxk.webserver.entity.examinations.inspections.request.ReportIndexInquiry;
import thyyxxk.webserver.entity.examinations.inspections.response.*;
import thyyxxk.webserver.utils.*;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * @author dj
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InspectionsService {
    private final InspectionsDao dao;
    private final RestTemplate template;
    private final ApiUrl apiUrl;


    public List<JyIndexResponse> queryJyIndex(ReportIndexInquiry inquiry) {
        String url = apiUrl.getThirdpartApi() + "/inspection/queryJyIndex";

        if (StrUtil.isBlank(inquiry.getPatNo())) {
            inquiry.setPatNo(inquiry.getContent());
        }

        ResultVo<List<JyIndexResponse>> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(inquiry),
                new ParameterizedTypeReference<ResultVo<List<JyIndexResponse>>>() {
                }
        ).getBody();

        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR, response.getMessage());
        }
        return response.getData();
    }

    public JyDetailResponse queryJyDetail(String reportId) {
        ReportDetailInquiry inquiry = new ReportDetailInquiry();
        inquiry.setReportId(reportId);
        String url = apiUrl.getThirdpartApi() + "/inspection/queryJyDetail";

        ResultVo<JyDetailResponse> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(inquiry),
                new ParameterizedTypeReference<ResultVo<JyDetailResponse>>() {
                }
        ).getBody();

        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR, response.getMessage());
        }
        return response.getData();
    }

    public List<TestReport> checkTestIndex(ReportIndexInquiry inquiry) {
        String url = apiUrl.getThirdpartApi() + "/inspection/queryJcIndex";
        ResultVo<List<TestReport>> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(inquiry),
                new ParameterizedTypeReference<ResultVo<List<TestReport>>>() {
                }
        ).getBody();
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR);
        }
        return response.getData();
    }

    public TestReport checkTestDetail(ReportDetailInquiry request) {
        if (StringUtil.isBlank(request.getReportId())) {
            throw new BizException(ExceptionEnum.NULL_POINTER, "报告ID不能为空！");
        }
        String url = apiUrl.getThirdpartApi() + "/inspection/queryJcDetail";
        ResultVo<TestReport> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(request),
                new ParameterizedTypeReference<ResultVo<TestReport>>() {
                }
        ).getBody();
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR);
        }
        return response.getData();
    }

    public List<PathologyIndex> checkPathologyIndex(ReportIndexInquiry request) {
        String url = apiUrl.getThirdpartApi() + "/inspection/queryBlIndex";
        request.setSocialNo(getPatSocialNo(request.getPatType(), request.getPatNo()));
        ResultVo<List<PathologyIndex>> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(request),
                new ParameterizedTypeReference<ResultVo<List<PathologyIndex>>>() {
                }
        ).getBody();
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR);
        }
        List<PathologyIndex> list = response.getData();
        list.sort(Comparator.comparing(PathologyIndex::getApplyDate).reversed());
        return list;
    }

    public List<ElectroIndex> checkElectroIndex(ReportIndexInquiry request) {
        String url = apiUrl.getThirdpartApi() + "/inspection/queryXdIndex";
        request.setSocialNo(getPatSocialNo(request.getPatType(), request.getPatNo()));
        ResultVo<List<ElectroIndex>> response = template.exchange(
                url, HttpMethod.POST, new HttpEntity<>(request),
                new ParameterizedTypeReference<ResultVo<List<ElectroIndex>>>() {
                }
        ).getBody();
        if (null == response) {
            throw new BizException(ExceptionEnum.NETWORK_ERROR);
        }
        if (!Objects.equals(response.getCode(), ExceptionEnum.SUCCESS.getCode())) {
            throw new BizException(ExceptionEnum.API_FUNC_ERROR);
        }
        List<ElectroIndex> list = response.getData();
        list.forEach(item -> item.setApplyDate(formatNumericDate(item.getApplyDate())));
        list.sort(Comparator.comparing(ElectroIndex::getApplyDate).reversed());
        return list;
    }

    private String getPatSocialNo(PatientNumType patType, String patNo) {
        if (patType == PatientNumType.InPatient) {
            return dao.selectInpatientSocialNo(patNo);
        }
        return dao.selectOutpatientSocialNo(patNo);
    }

    private String formatNumericDate(String date) {
        return date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6);
    }
}
