package com.docus.server.mzsy.job;

import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.DateUtil;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.utils.TableJsonRead;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.archive.entity.TBasic;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.mzsy.entity.MzsyMectReportView;
import com.docus.server.mzsy.entity.MzsyReportDataView;
import com.docus.server.mzsy.entity.MzsyShoumaReportDataView;
import com.docus.server.mzsy.mapper.MzsyReportDataViewMapper;
import com.docus.server.mzsy.mapper.MzsyShoumaReportDataViewMapper;
import com.docus.server.rpc.DownPlatformService;
import com.docus.server.rpc.TaskDistributeService;
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.rpc.dto.ReportDownTwoDto;
import com.docus.server.rpc.dto.ReportHospitalTwoDto;
import com.docus.server.rpc.dto.ReportPatientTwoDto;
import com.docus.server.rpc.dto.ReportTaskTwoDto;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author YongBin Wen
 * @date 2024/8/16 14:45
 */
@Component
@Slf4j
public class MzsyReportCollectJob {

    @Autowired
    private DownPlatformService downPlatformService;
    @Autowired
    private TaskDistributeService taskDistributeService;
    @Autowired
    private MzsyReportDataViewMapper reportDataViewMapper;
    @Autowired
    private MzsyShoumaReportDataViewMapper shoumaReportDataViewMapper;
    @Autowired
    private TBasicMapper tBasicMapper;

    @XxlJob("MzsyReportCollectJob")
    public void reportCollect() {
        // 1.获取任务和患者信息 2.查询视图信息 3.上报下载
        String jobParam = XxlJobHelper.getJobParam();
        JSONObject jobParamJsonObject = JSONObject.parseObject(jobParam);
        String collectorId = jobParamJsonObject.getString("collectorId");
        String extraCondition = jobParamJsonObject.getString("extraCondition");
        if (Func.isBlank(collectorId)) {
            log.warn(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 检查、检验、心电等报告视图采集,未配置采集器获取任务信息");
            return;
        }

        CommonResult<ReportDownTwoDto> commonResult = taskDistributeService.getTaskByCollectorId(collectorId);
        if (ResultCode.SUCCESS.getCode().equals(commonResult.getCode())
                && commonResult.getData() != null) {
            ReportDownTwoDto downTwoDto = commonResult.getData();
            ReportTaskTwoDto task = downTwoDto.getTasks().get(0);
            log.info(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 检查、检验、心电等报告视图采集任务，获取了任务：{}", Func.toJson(task));

            ReportHospitalTwoDto hospitalTwoDto = downTwoDto.getHospitals().get(0);
            ReportPatientTwoDto reportPatientTwoDto = downTwoDto.getPatient();
            String jzh = downTwoDto.getJzh();
            String patientId = downTwoDto.getPatientId();
            List<TBasic> basicList = tBasicMapper.getTbasicByPatientIds(Collections.singletonList(patientId));
            TBasic tBasic = basicList.get(0);

            List<MzsyReportDataView> mzsyReportDataViewList = new ArrayList<>();
            List<MzsyReportDataView> mzsyReportDataViewListByJzh = reportDataViewMapper.findByPatJzhAndOtherCondition(jzh, extraCondition);
            List<MzsyReportDataView> mzsyReportDataViewListByInpatNoTime = reportDataViewMapper.findByPatNoTimeAndOtherCondition(tBasic.getInpatientNo(), Func.formatDateTime(tBasic.getAdmissDate()), Func.formatDateTime(tBasic.getDisDate()), extraCondition);
            Map<String, String> fileIdDistinct = new HashMap<>();

            for (MzsyReportDataView mzsyReportDataView : mzsyReportDataViewListByJzh) {
                mzsyReportDataViewList.add(mzsyReportDataView);
                fileIdDistinct.put(mzsyReportDataView.getFfileId(), "0");
            }
            for (MzsyReportDataView mzsyReportDataView : mzsyReportDataViewListByInpatNoTime) {
                if (fileIdDistinct.containsKey(mzsyReportDataView.getFfileId())) {
                    continue;
                }
                mzsyReportDataViewList.add(mzsyReportDataView);
                fileIdDistinct.put(mzsyReportDataView.getFfileId(), "0");
            }
            // Date xinLiStartDateTime = Func.parseDate("2025-04-01 00:00:00", DateUtil.PATTERN_DATETIME);
            mzsyReportDataViewList = mzsyReportDataViewList.stream()
                    // 如果是心里量表，并且报告时间小于标记时间（不为心里量表或者报告时间不小于目标时间） 则不采集，医院扫描上传
                   // .filter(view -> !"心理量表".equals(view.getFpatModule()) || !view.getFfileTime().before(xinLiStartDateTime))
                    .sorted(Comparator.comparing(MzsyReportDataView::getFpatModule)
                            .thenComparing(MzsyReportDataView::getFfileTime))
                    .collect(Collectors.toList());


            int size = mzsyReportDataViewList.size();
            log.info("住院号：{}，住院次数：{},记账号：{} 采集视图数据：{} 条！数据：{}", reportPatientTwoDto.getInpatientNo(), hospitalTwoDto.getAdmissTimes(), jzh, size, Func.toJson(mzsyReportDataViewList));
            if (size <= 0) {
                return;
            }
            // 验证心理量表签名情况
            for (MzsyReportDataView reportDataView : mzsyReportDataViewList) {
                if ("心理量表".equals(reportDataView.getFpatModule()) && Func.isBlank(reportDataView.getReportDoctor())) {
                    tBasicMapper.updateTaskRemarkById(task.getTaskId(), "心理量表存在未签名报告！");
                    log.warn("住院号：{}，住院次数：{},记账号：{} 采集视图数据,心理量表:{} 未签名！", reportPatientTwoDto.getInpatientNo(), hospitalTwoDto.getAdmissTimes(), jzh, reportDataView.getFfileName());
                    return;
                }
            }


            // 以下代表完成
            // 提示修改为空
            tBasicMapper.updateTaskRemarkById(task.getTaskId(), "");
            TableJsonRead tableJsonRead = new TableJsonRead();
            JSONObject moduleAlisConfig = tableJsonRead.Read("data-config", "mzsy-module-alis", JSONObject.class);

            ReportDownPatientDto patient = new ReportDownPatientDto();
            patient.setPatientid(patientId);

            ReportDownDto reportDownDto = new ReportDownDto();
            reportDownDto.setCollectorid(collectorId);
            reportDownDto.setIp("");
            reportDownDto.setPatient(patient);
            int sort = 0;
            tBasicMapper.invalidFileBySource(patientId, collectorId);
            for (MzsyReportDataView mzsyReportDataView : mzsyReportDataViewList) {
                ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
                reportDownScanFileDto.setDownurl(mzsyReportDataView.getFfilePath());
                reportDownScanFileDto.setFiletitle(mzsyReportDataView.getFfileName());
                reportDownScanFileDto.setSerialnum(mzsyReportDataView.getFfileId());
                reportDownScanFileDto.setFilesource(1);
                reportDownScanFileDto.setFiletype(1);
                reportDownScanFileDto.setFilestoragetype(1);
                reportDownScanFileDto.setTaskid(task.getTaskId());
                reportDownScanFileDto.setSort(++sort);
                List<ReportDownScanFileDto> scanFiles = Collections.singletonList(reportDownScanFileDto);

                String assortId;
                String fpatModule = mzsyReportDataView.getFpatModule();
                if (Func.isBlank(fpatModule)) {
                    assortId = moduleAlisConfig.getString("default");
                } else {
                    assortId = moduleAlisConfig.getString(fpatModule.toLowerCase().trim());
                    if (Func.isBlank(assortId)) {
                        assortId = moduleAlisConfig.getString("default");
                    }
                }
                reportDownDto.setAssortid(assortId);
                reportDownDto.setScanfiles(scanFiles);
                downPlatformService.report(reportDownDto);
            }
        }
    }


    @XxlJob("MzsyShouMaReportCollectJob")
    public void shouMaReportCollect() {
        // 1.获取任务和患者信息 2.查询视图信息 3.上报下载
        String jobParam = XxlJobHelper.getJobParam();
        JSONObject jobParamJsonObject = JSONObject.parseObject(jobParam);
        String collectorId = jobParamJsonObject.getString("collectorId");
        String extraCondition = jobParamJsonObject.getString("extraCondition");
        String assortId = jobParamJsonObject.getString("assortId");
        if (Func.isBlank(collectorId) || Func.isBlank(assortId)) {
            log.warn(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 手麻报告视图采集,未配置采集器获取任务信息");
            return;
        }

        CommonResult<ReportDownTwoDto> commonResult = taskDistributeService.getTaskByCollectorId(collectorId);
        if (ResultCode.SUCCESS.getCode().equals(commonResult.getCode())
                && commonResult.getData() != null) {
            ReportDownTwoDto downTwoDto = commonResult.getData();
            ReportTaskTwoDto task = downTwoDto.getTasks().get(0);
            log.info(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 手麻报告视图采集任务，获取了任务：{}", Func.toJson(task));

            ReportHospitalTwoDto hospitalTwoDto = downTwoDto.getHospitals().get(0);
            ReportPatientTwoDto reportPatientTwoDto = downTwoDto.getPatient();
            String jzh = downTwoDto.getJzh();
            String inpatientNo = reportPatientTwoDto.getInpatientNo();
            Integer admissTimes = hospitalTwoDto.getAdmissTimes();

            List<MzsyShoumaReportDataView> shoumaReportDataViewList = shoumaReportDataViewMapper.findByinpNoAndTimesAndOtherCondition(inpatientNo, String.valueOf(admissTimes), extraCondition);
            int size = shoumaReportDataViewList.size();
            log.info("住院号：{}，住院次数：{},记账号：{} 采集视图数据：{} 条！数据：{}", inpatientNo, admissTimes, jzh, size, Func.toJson(shoumaReportDataViewList));
            if (size <= 0) {
                return;
            }

            ReportDownPatientDto patient = new ReportDownPatientDto();
            patient.setPatientid(downTwoDto.getPatientId());

            ReportDownDto reportDownDto = new ReportDownDto();
            reportDownDto.setCollectorid(collectorId);
            reportDownDto.setIp("");
            reportDownDto.setPatient(patient);
            int sort = 0;
            tBasicMapper.invalidFileBySource(downTwoDto.getPatientId(), collectorId);
            for (MzsyShoumaReportDataView mzsyShouMaReportDataView : shoumaReportDataViewList) {
                ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
                reportDownScanFileDto.setDownurl(mzsyShouMaReportDataView.getFilePath());
                reportDownScanFileDto.setFiletitle(mzsyShouMaReportDataView.getFileTitle());
                reportDownScanFileDto.setSerialnum(mzsyShouMaReportDataView.getFilePath());
                reportDownScanFileDto.setFilesource(1);
                reportDownScanFileDto.setFiletype(1);
                reportDownScanFileDto.setFilestoragetype(1);
                reportDownScanFileDto.setTaskid(task.getTaskId());
                reportDownScanFileDto.setSort(++sort);
                List<ReportDownScanFileDto> scanFiles = Collections.singletonList(reportDownScanFileDto);

                reportDownDto.setAssortid(assortId);
                reportDownDto.setScanfiles(scanFiles);
                downPlatformService.report(reportDownDto);
            }
        }
    }


    @XxlJob("MzsyMectReportCollectJob")
    public void mectReportCollect() {
        try {
            // 1.获取任务和患者信息 2.查询视图信息 3.上报下载
            String jobParam = XxlJobHelper.getJobParam();
            JSONObject jobParamJsonObject = JSONObject.parseObject(jobParam);
            String collectorId = jobParamJsonObject.getString("collectorId");
            String extraCondition = jobParamJsonObject.getString("extraCondition");
            String assortId = jobParamJsonObject.getString("assortId");
            if (Func.isBlank(collectorId) || Func.isBlank(assortId)) {
                log.warn(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 MECT 报告视图采集,未配置采集器获取任务信息");
                return;
            }

            CommonResult<ReportDownTwoDto> commonResult = taskDistributeService.getTaskByCollectorId(collectorId);
            if (ResultCode.SUCCESS.getCode().equals(commonResult.getCode())
                    && commonResult.getData() != null) {
                ReportDownTwoDto downTwoDto = commonResult.getData();
                ReportTaskTwoDto task = downTwoDto.getTasks().get(0);
                log.info(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 MECT 报告视图采集任务，获取了任务：{}", Func.toJson(task));

                ReportHospitalTwoDto hospitalTwoDto = downTwoDto.getHospitals().get(0);
                ReportPatientTwoDto reportPatientTwoDto = downTwoDto.getPatient();
                String jzh = downTwoDto.getJzh();
                String inpatientNo = reportPatientTwoDto.getInpatientNo();
                Integer admissTimes = hospitalTwoDto.getAdmissTimes();

                List<MzsyMectReportView> mzsyMectReportViews = reportDataViewMapper.findByPatIdAndOtherCondition(jzh, extraCondition);
                int size = mzsyMectReportViews.size();
                log.info("MECT 住院号：{}，住院次数：{},记账号：{} 采集视图数据：{} 条！数据：{}", inpatientNo, admissTimes, jzh, size, Func.toJson(mzsyMectReportViews));
                if (size <= 0) {
                    return;
                }

                ReportDownPatientDto patient = new ReportDownPatientDto();
                patient.setPatientid(downTwoDto.getPatientId());

                ReportDownDto reportDownDto = new ReportDownDto();
                reportDownDto.setCollectorid(collectorId);
                reportDownDto.setIp("");
                reportDownDto.setPatient(patient);
                int sort = 0;
                tBasicMapper.invalidFileBySource(downTwoDto.getPatientId(), collectorId);
                for (MzsyMectReportView mzsyMectReportView : mzsyMectReportViews) {
                    ReportDownScanFileDto reportDownScanFileDto = new ReportDownScanFileDto();
                    reportDownScanFileDto.setDownurl(mzsyMectReportView.getPdfReportPath());
                    reportDownScanFileDto.setFiletitle(mzsyMectReportView.getModuleName());
                    reportDownScanFileDto.setSerialnum(mzsyMectReportView.getApplyId());
                    reportDownScanFileDto.setFilesource(1);
                    reportDownScanFileDto.setFiletype(1);
                    reportDownScanFileDto.setFilestoragetype(1);
                    reportDownScanFileDto.setTaskid(task.getTaskId());
//                reportDownScanFileDto.setSort(++sort);
                    reportDownScanFileDto.setSort(sort);
                    List<ReportDownScanFileDto> scanFiles = Collections.singletonList(reportDownScanFileDto);

                    reportDownDto.setAssortid(assortId);
                    reportDownDto.setScanfiles(scanFiles);
                    downPlatformService.report(reportDownDto);
                }
            }
        } catch (Exception ex) {
            log.error(">>>>>>>>>>>>>>>>>>>>>> 梅州三院 MECT 报告视图采集 错误，" + ex.getMessage(), ex);
        }
    }


    public static void main(String[] args) {
        Date xinLiStartDateTime = Func.parseDate("2025-04-01 00:00:00", DateUtil.PATTERN_DATETIME);
        Date fileTime = Func.parseDate("2025-04-01 00:00:00", DateUtil.PATTERN_DATETIME);
        Date fileTime2 = Func.parseDate("2025-04-02 00:00:00", DateUtil.PATTERN_DATETIME);
        Date fileTime3 = Func.parseDate("2025-03-01 00:00:00", DateUtil.PATTERN_DATETIME);
        System.out.println(fileTime.before(xinLiStartDateTime));
        System.out.println(fileTime2.before(xinLiStartDateTime));
        System.out.println(fileTime3.before(xinLiStartDateTime));
    }
}
