package com.docus.server.gdszyzh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.Func;
import com.docus.server.archive.entity.AfCollectPatientLog;
import com.docus.server.archive.entity.TBasic;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.gdszyzh.entity.GdSzyZhReportDataView;
import com.docus.server.gdszyzh.mapper.GdSzyZhEcgReportDataViewMapper;
import com.docus.server.gdszyzh.mapper.GdSzyZhIcuReportDataViewMapper;
import com.docus.server.gdszyzh.mapper.GdSzyZhShouMaReportDataViewMapper;
import com.docus.server.gdszyzh.service.ReportCollectService;
import com.docus.server.rpc.DownPlatformService;
import com.docus.server.rpc.GdSzyZhReportService;
import com.docus.server.rpc.dto.GdSzyZhReportDetailDto;
import com.docus.server.rpc.dto.GdSzyZhReportListDto;
import com.docus.server.rpc.dto.ReportDownDto;
import com.docus.server.rpc.dto.ReportDownPatientDto;
import com.docus.server.rpc.dto.ReportDownScanFileDto;
import com.docus.server.util.TableJsonRead;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author YongBin Wen
 * @date 2026/4/7 16:28
 */
@Slf4j
@Service
public class ReportCollectServiceImpl implements ReportCollectService {
    @Autowired
    private GdSzyZhReportService gdSzyZhReportService;
    @Autowired
    private TBasicMapper tBasicMapper;
    @Autowired
    private DownPlatformService downPlatformService;
    @Autowired
    private GdSzyZhEcgReportDataViewMapper ecgReportDataViewMapper;
    @Autowired
    private GdSzyZhIcuReportDataViewMapper icuReportDataViewMapper;
    @Autowired
    private GdSzyZhShouMaReportDataViewMapper shouMaReportDataViewMapper;

    @Override
    public void collectPacs(List<String> patientIds) {
        List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(patientIds);
        for (TBasic basic : basicList) {
            collectPacs(basic);
        }
    }

    @Override
    public void collectLis(List<String> patientIds) {
        List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(patientIds);
        for (TBasic basic : basicList) {
            collectLis(basic);
        }
    }

    @Override
    public void collectEcg(List<String> patientIds) {
        List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(patientIds);
        for (TBasic basic : basicList) {
            collectEcg(basic);
        }
    }

    @Override
    public void collectShouMa(List<String> patientIds) {
        List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(patientIds);
        for (TBasic basic : basicList) {
            collectShouMa(basic);
        }
    }

    @Override
    public void collectIcu(List<String> patientIds) {
        List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(patientIds);
        for (TBasic basic : basicList) {
            collectIcu(basic);
        }
    }


    private void collectPacs(TBasic basic) {
        Date admissDate = basic.getAdmissDate();
        Date disDate = basic.getDisDate();
        String jzh = basic.getJzh();
        String empId = basic.getEmpId();
        String patientId = basic.getPatientId();
        if (Func.isBlank(empId) || Func.isEmpty(admissDate) || Func.isEmpty(disDate)) {
            log.error("采集Pacs报告，患者：{},住院流水号：{},入院、出院时间，empId有空数据，无法采集！", basic.getInpatientNo(), jzh);
            return;
        }
        String beginDate = Func.formatDate(admissDate);
        String endDate = Func.formatDate(disDate);
        GdSzyZhReportListDto pacsList = gdSzyZhReportService.pacsList(empId, jzh, beginDate, endDate);
        List<GdSzyZhReportListDto.Report> reportList = pacsList.getReportList();
        reportList = reportList.stream()
                .sorted(Comparator.comparing(GdSzyZhReportListDto.Report::getReportClass)
                        .thenComparing(GdSzyZhReportListDto.Report::getReportTime))
                .collect(Collectors.toList());
        int sort = 0;
        List<ReportDownScanFileDto> scanFiles = new ArrayList<>();
        for (GdSzyZhReportListDto.Report report : reportList) {
            String reportNo = report.getReportNo();
            GdSzyZhReportDetailDto pacsDetail = gdSzyZhReportService.pacsDetail(reportNo);
            ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
            reportDownScanFileDto.setDownurl(pacsDetail.getReportUrl());
            reportDownScanFileDto.setFiletitle(report.getReportTitle());
            reportDownScanFileDto.setSerialnum(reportNo);
            reportDownScanFileDto.setFilesource(1);
            reportDownScanFileDto.setFiletype(1);
            reportDownScanFileDto.setFilestoragetype(1);
            reportDownScanFileDto.setTaskid(-1L);
            reportDownScanFileDto.setSort(++sort);
            scanFiles.add(reportDownScanFileDto);
        }

        final String configPath = "data-config";
        final String configName = "gdszyzh-collect-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);
        JSONObject pacsWsConfig = configOjb.getJSONObject("PACS");
        String collectorId = pacsWsConfig.getString("collectorId");
        String assortId = pacsWsConfig.getString("assortId");

        ReportDownPatientDto patient = new ReportDownPatientDto();
        patient.setPatientid(patientId);
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setCollectorid(collectorId);
        reportDownDto.setIp("");
        reportDownDto.setPatient(patient);
        reportDownDto.setAssortid(assortId);
        reportDownDto.setScanfiles(scanFiles);
        downPlatformService.report(reportDownDto);
        long count = scanFiles.stream().map(ReportDownScanFileDto::getSerialnum).distinct().count();
        saveOrUpdateCollectLog(patientId, collectorId, (int) count);
    }


    private void collectLis(TBasic basic) {
        Date admissDate = basic.getAdmissDate();
        Date disDate = basic.getDisDate();
        String jzh = basic.getJzh();
        String empId = basic.getEmpId();
        String patientId = basic.getPatientId();
        if (Func.isBlank(empId) || Func.isEmpty(admissDate) || Func.isEmpty(disDate)) {
            log.error("采集LIS报告，患者：{},住院流水号：{},入院、出院时间，empId有空数据，无法采集！", basic.getInpatientNo(), jzh);
            return;
        }
        String beginDate = Func.formatDate(admissDate);
        String endDate = Func.formatDate(disDate);
        GdSzyZhReportListDto lisList = gdSzyZhReportService.lisList(empId, jzh, beginDate, endDate);
        List<GdSzyZhReportListDto.Report> reportList = lisList.getReportList();
        reportList = reportList.stream()
                .sorted(Comparator.comparing(GdSzyZhReportListDto.Report::getReportClass)
                        .thenComparing(GdSzyZhReportListDto.Report::getReportTime))
                .collect(Collectors.toList());
        int sort = 0;
        List<ReportDownScanFileDto> scanFiles = new ArrayList<>();
        for (GdSzyZhReportListDto.Report report : reportList) {
            ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
            reportDownScanFileDto.setDownurl(report.getReporPath());
            reportDownScanFileDto.setFiletitle(report.getReportTitle());
            reportDownScanFileDto.setSerialnum(report.getReportNo());
            reportDownScanFileDto.setFilesource(1);
            reportDownScanFileDto.setFiletype(1);
            reportDownScanFileDto.setFilestoragetype(1);
            reportDownScanFileDto.setTaskid(-1L);
            reportDownScanFileDto.setSort(++sort);
            scanFiles.add(reportDownScanFileDto);
        }

        final String configPath = "data-config";
        final String configName = "gdszyzh-collect-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);
        JSONObject lisWsConfig = configOjb.getJSONObject("LIS");
        String collectorId = lisWsConfig.getString("collectorId");
        String assortId = lisWsConfig.getString("assortId");

        ReportDownPatientDto patient = new ReportDownPatientDto();
        patient.setPatientid(patientId);
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setCollectorid(collectorId);
        reportDownDto.setIp("");
        reportDownDto.setPatient(patient);
        reportDownDto.setAssortid(assortId);
        reportDownDto.setScanfiles(scanFiles);
        downPlatformService.report(reportDownDto);
        long count = scanFiles.stream().map(ReportDownScanFileDto::getSerialnum).distinct().count();
        saveOrUpdateCollectLog(patientId, collectorId, (int) count);
    }

    private void collectEcg(TBasic basic) {
        String jzh = basic.getJzh();
        String patientId = basic.getPatientId();

        List<GdSzyZhReportDataView> dataViewList = ecgReportDataViewMapper.getByJzhs(Collections.singletonList(jzh));
        dataViewList = dataViewList.stream()
                .sorted(Comparator.comparing(GdSzyZhReportDataView::getReportClass)
                        .thenComparing(GdSzyZhReportDataView::getReportTime))
                .collect(Collectors.toList());

        int sort = 0;
        List<ReportDownScanFileDto> scanFiles = new ArrayList<>();
        for (GdSzyZhReportDataView dataView : dataViewList) {
            ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
            reportDownScanFileDto.setDownurl(dataView.getReportUrl());
            reportDownScanFileDto.setFiletitle(dataView.getReportTitle());
            reportDownScanFileDto.setSerialnum(dataView.getReportNo());
            reportDownScanFileDto.setFilesource(1);
            reportDownScanFileDto.setFiletype(1);
            reportDownScanFileDto.setFilestoragetype(1);
            reportDownScanFileDto.setTaskid(-1L);
            reportDownScanFileDto.setSort(++sort);
            scanFiles.add(reportDownScanFileDto);
        }

        final String configPath = "data-config";
        final String configName = "gdszyzh-collect-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);
        JSONObject lisWsConfig = configOjb.getJSONObject("ECG");
        String collectorId = lisWsConfig.getString("collectorId");
        String assortId = lisWsConfig.getString("assortId");

        ReportDownPatientDto patient = new ReportDownPatientDto();
        patient.setPatientid(patientId);
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setCollectorid(collectorId);
        reportDownDto.setIp("");
        reportDownDto.setPatient(patient);
        reportDownDto.setAssortid(assortId);
        reportDownDto.setScanfiles(scanFiles);
        downPlatformService.report(reportDownDto);
        long count = scanFiles.stream().map(ReportDownScanFileDto::getSerialnum).distinct().count();
        saveOrUpdateCollectLog(patientId, collectorId, (int) count);
    }

    private void collectShouMa(TBasic basic) {
        String jzh = basic.getJzh();
        String patientId = basic.getPatientId();

        List<GdSzyZhReportDataView> dataViewList = shouMaReportDataViewMapper.getByJzhs(Collections.singletonList(jzh));
        dataViewList = dataViewList.stream()
                .sorted(Comparator.comparing(GdSzyZhReportDataView::getReportClass)
                        .thenComparing(GdSzyZhReportDataView::getReportTime))
                .collect(Collectors.toList());

        int sort = 0;
        List<ReportDownScanFileDto> scanFiles = new ArrayList<>();
        for (GdSzyZhReportDataView dataView : dataViewList) {
            ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
            reportDownScanFileDto.setDownurl(dataView.getReportUrl());
            reportDownScanFileDto.setFiletitle(dataView.getReportTitle());
            reportDownScanFileDto.setSerialnum(dataView.getReportNo());
            reportDownScanFileDto.setFilesource(1);
            reportDownScanFileDto.setFiletype(1);
            reportDownScanFileDto.setFilestoragetype(1);
            reportDownScanFileDto.setTaskid(-1L);
            reportDownScanFileDto.setSort(++sort);
            scanFiles.add(reportDownScanFileDto);
        }

        final String configPath = "data-config";
        final String configName = "gdszyzh-collect-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);
        JSONObject lisWsConfig = configOjb.getJSONObject("ShouMa");
        String collectorId = lisWsConfig.getString("collectorId");
        String assortId = lisWsConfig.getString("assortId");

        ReportDownPatientDto patient = new ReportDownPatientDto();
        patient.setPatientid(patientId);
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setCollectorid(collectorId);
        reportDownDto.setIp("");
        reportDownDto.setPatient(patient);
        reportDownDto.setAssortid(assortId);
        reportDownDto.setScanfiles(scanFiles);
        downPlatformService.report(reportDownDto);
        long count = scanFiles.stream().map(ReportDownScanFileDto::getSerialnum).distinct().count();
        saveOrUpdateCollectLog(patientId, collectorId, (int) count);
    }

    private void collectIcu(TBasic basic) {
        String patientId = basic.getPatientId();
        Integer admissTimes = basic.getAdmissTimes();
        List<GdSzyZhReportDataView> dataViewList = icuReportDataViewMapper.getByInpatientNo(basic.getInpatientNo());
        dataViewList = dataViewList.stream()
                .filter(d -> admissTimes.equals(d.getAdmissTimes()))
                .sorted(Comparator.comparing(GdSzyZhReportDataView::getReportClass)
                        .thenComparing(GdSzyZhReportDataView::getReportTime))
                .collect(Collectors.toList());

        int sort = 0;
        List<ReportDownScanFileDto> scanFiles = new ArrayList<>();
        for (GdSzyZhReportDataView dataView : dataViewList) {
            String reportUrl = dataView.getReportUrl();
            // 替换本地地址为ftp代理地址
            reportUrl = reportUrl.replace("\\", "/")
                    .replace("D:/DocareDocArchived", "ftp://10.0.57.90:21");
            ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
            reportDownScanFileDto.setDownurl(reportUrl);
            reportDownScanFileDto.setFiletitle(dataView.getReportTitle());
            reportDownScanFileDto.setSerialnum(dataView.getReportNo());
            reportDownScanFileDto.setFilesource(1);
            reportDownScanFileDto.setFiletype(1);
            reportDownScanFileDto.setFilestoragetype(1);
            reportDownScanFileDto.setTaskid(-1L);
            reportDownScanFileDto.setSort(++sort);
            scanFiles.add(reportDownScanFileDto);
        }

        final String configPath = "data-config";
        final String configName = "gdszyzh-collect-config";
        TableJsonRead jsonReader = new TableJsonRead();
        JSONObject configOjb = jsonReader.Read(configPath, configName, JSONObject.class);
        JSONObject lisWsConfig = configOjb.getJSONObject("ICU");
        String collectorId = lisWsConfig.getString("collectorId");
        String assortId = lisWsConfig.getString("assortId");

        ReportDownPatientDto patient = new ReportDownPatientDto();
        patient.setPatientid(patientId);
        ReportDownDto reportDownDto = new ReportDownDto();
        reportDownDto.setCollectorid(collectorId);
        reportDownDto.setIp("");
        reportDownDto.setPatient(patient);
        reportDownDto.setAssortid(assortId);
        reportDownDto.setScanfiles(scanFiles);
        downPlatformService.report(reportDownDto);
        long count = scanFiles.stream().map(ReportDownScanFileDto::getSerialnum).distinct().count();
        saveOrUpdateCollectLog(patientId, collectorId, (int) count);
    }


    private void saveOrUpdateCollectLog(String patientId, String collectorId, int fileCount) {
        AfCollectPatientLog collectPatientLog = new AfCollectPatientLog();
        collectPatientLog.setPatientId(patientId);
        collectPatientLog.setCollectId(collectorId);
        collectPatientLog.setFileCount(fileCount);
        collectPatientLog.setLastCollectTime(new Date());
        tBasicMapper.saveOrUpdateCollectLog(collectPatientLog);
    }

    public static void main(String[] args) {
        String path = "D:\\DocareDocArchived\\24315539643249459211\\CARE_DOC_GDZY_PDF\\5d7b59066b804affb61d74bfe399c6ce_24315539643249459211_1.PDF";
        path = path.replace("\\", "/")
                .replace("D:/DocareDocArchived", "ftp://10.0.57.90:21");
        System.out.println(path);
    }
}
