package com.docus.server.archive.job;

import com.docus.core.util.Func;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.archive.rpc.DownPlatformService;
import com.docus.server.archive.rpc.TaskDistributeService;
import com.docus.server.archive.rpc.dto.ReportDownDto;
import com.docus.server.archive.rpc.dto.ReportDownTwoDto;
import com.docus.server.archive.rpc.dto.ReportHospitalTwoDto;
import com.docus.server.archive.rpc.dto.ReportPatientTwoDto;
import com.docus.server.fsy.api.LisReportService;
import com.docus.server.fsy.api.dto.LisPatientGroupReportRequest;
import com.docus.server.fsy.api.dto.LisPatientGroupReportResponse;
import com.docus.server.fsy.api.dto.LisPatientListRequest;
import com.docus.server.fsy.api.dto.LisPatientListResponse;
import com.docus.server.fsy.api.dto.LisPatientReportRequest;
import com.docus.server.fsy.api.dto.LisPatientReportResponse;
import com.docus.server.fsy.converter.LisReportConverter;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author YongBin Wen
 * @date 2024/3/27 16:23
 */
@Component
@Slf4j
public class LisPatientReportCollectJob {
    @Value("${fsy.lis.assortid}")
    private String lisAssortId;
    @Value("${fsy.lis.sysflag}")
    private String lisCollectorId;

    @Resource
    private LisReportService lisReportService;
    @Resource
    private DownPlatformService downPlatformService;
    @Resource
    private TaskDistributeService taskDistributeService;
    @Resource
    private TBasicMapper tBasicMapper;


    /**
     * 佛山三院Lis检验报告采集job
     *
     * @date 2024/3/27 16:27
     * @author YongBin Wen
     */
    @XxlJob("FoShanSyLisPatientReportCollectJob")
    public void foShanSyLisPatientReportCollectJob() {
        log.info("====================> 佛山三院Lis检验报告采集任务开始 ===================");
        try {
            while (true) {
                CommonResult<ReportDownTwoDto> taskResult = taskDistributeService.getNoViewTaskByCollectorId(lisCollectorId);
                if (Objects.isNull(taskResult) || taskResult.getCode().equals(ResultCode.FAILED.getCode())) {
                    break;
                }
                // 获取采集任务
                ReportDownTwoDto reportDownTwoDto = taskResult.getData();
                Long taskId = reportDownTwoDto.getTasks().get(0).getTaskId();
                log.info("佛山三院Lis检验报告采集任务,成功获取采集任务,任务id：{}", taskId);
                ReportPatientTwoDto patientTwoDto = reportDownTwoDto.getPatient();
                ReportHospitalTwoDto hospitalTwoDto = reportDownTwoDto.getHospitals().get(0);
                String admissDate = hospitalTwoDto.getAdmissDate();
                String disDate = hospitalTwoDto.getDisDate();
                if (Func.isBlank(admissDate) || Func.isBlank(disDate)) {
                    log.info("佛山三院Lis检验报告采集任务,采集任务id：{} 入院时间或者出院时间为空，不进行采集！", taskId);
                    continue;
                }
                // 获取患者的lis检验报告列表
                LisPatientListRequest lisPatientListRequest = new LisPatientListRequest();
                lisPatientListRequest.setPidInNo(patientTwoDto.getInpatientNo());
                lisPatientListRequest.setPidAddmissTimes(hospitalTwoDto.getAdmissTimes());
                lisPatientListRequest.setStartDate(admissDate);
                lisPatientListRequest.setEndDate(disDate);
                LisPatientListResponse patientListResponse = lisReportService.getPatientList(lisPatientListRequest);
                List<LisPatientListResponse.Patient> patientList = patientListResponse.getPatientList();
                if (Func.isEmpty(patientList)) {
                    log.info("佛山三院Lis检验报告采集任务,采集任务id：{} 未查询到Lis患者文件数据", taskId);
                    continue;
                }
                // 报告类型gen需要合并
                List<LisPatientListResponse.Patient> genPatientList = new ArrayList<>();
                List<LisPatientListResponse.Patient> otherPatientList= new ArrayList<>();
                for (LisPatientListResponse.Patient p : patientList) {
                    if ("gen".equalsIgnoreCase(p.getRepReportType())) {
                        genPatientList.add(p);
                        continue;
                    }
                    otherPatientList.add(p);
                }

                tBasicMapper.cancelFileBySource(lisCollectorId, reportDownTwoDto.getPatientId());
                if (Func.isNotEmpty(genPatientList)) {
                    // 合并获取接口
                    String repIds = genPatientList.stream().map(LisPatientListResponse.Patient::getRepId).collect(Collectors.joining(","));
                    LisPatientGroupReportRequest request = new LisPatientGroupReportRequest();
                    request.setReportCode("GroupPrint");
                    request.setRepIds(repIds);
                    LisPatientGroupReportResponse groupReport = lisReportService.getPatientGroupReport(request);
                    ReportDownDto reportDownDto = LisReportConverter.convertDownloadPlatform(reportDownTwoDto, groupReport);
                    reportDownDto.setCollectorid(lisCollectorId);
                    reportDownDto.setAssortid(lisAssortId);
                    downPlatformService.report(reportDownDto);

                }
                if (Func.isNotEmpty(otherPatientList)) {
                    //  文件列表查询每个文件，进行上报下载服务
                    for (LisPatientListResponse.Patient patient : otherPatientList) {
                        LisPatientReportRequest lisPatientReportRequest = new LisPatientReportRequest();
                        lisPatientReportRequest.setRepId(patient.getRepId());
                        lisPatientReportRequest.setCustomReportSuffix("");
                        LisPatientReportResponse lisReportServicePatientReport = lisReportService.getPatientReport(lisPatientReportRequest);
                        ReportDownDto reportDownDto = LisReportConverter.convertDownloadPlatform(reportDownTwoDto, patient, lisReportServicePatientReport);
                        reportDownDto.setCollectorid(lisCollectorId);
                        reportDownDto.setAssortid(lisAssortId);
                        downPlatformService.report(reportDownDto);
                    }
                }
            }
        } catch (Exception ex) {
            log.error("====================> 佛山三院Lis检验报告采集任务出现异常_" + ex.getMessage(), ex);
        }
        log.info("====================> 佛山三院Lis检验报告采集任务结束 ===================");
    }


}
