package com.docus.server.gdszyzh.job;

import com.alibaba.fastjson.JSONObject;
import com.docus.server.archive.mapper.TBasicMapper;
import com.docus.server.gdszyzh.service.ReportCollectService;
import com.docus.server.util.TableJsonRead;
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.time.LocalDate;
import java.util.List;

/**
 *
 * @author YongBin Wen
 * @date 2026/4/7 16:25
 */
@Slf4j
@Component
public class GdSzyZhEcgCollectJob {
    @Autowired
    private ReportCollectService reportCollectService;
    @Autowired
    private TBasicMapper basicMapper;

    @XxlJob("GdSzyZhEcgCollectJob")
    public void gdSzyZhEcgCollectJob() {
        log.info("广东省中医珠海，动态心电血压采集任务开始！");
        LocalDate localDate = LocalDate.now();
        try {
            String jobParam = XxlJobHelper.getJobParam();
            String[] days;
            if (jobParam == null) {
                days = new String[]{"3"};
            } else {
                days = jobParam.split(",");
            }
            for (String day : days) {
                LocalDate disDateRange = localDate.plusDays(-Integer.parseInt(day));
                String disDateStart = disDateRange + " 00:00:00";
                String disDateEnd = disDateRange + " 23:59:59";
                log.info("广东省中医珠海，动态心电血压采集，患者出院时间：{} 至 {}", disDateStart, disDateEnd);
                List<String> patientIds = basicMapper.getPatientIdsByDisDate(disDateStart, disDateEnd);
                reportCollectService.collectEcg(patientIds);
            }
            log.info("广东省中医珠海，动态心电血压采集任务结束！");
        } catch (Exception e) {
            log.error("广东省中医珠海，动态心电血压采集任务出现异常！" + e.getMessage(), e);
        }
    }

    @XxlJob("GdSzyZhEcgQueryNoCollectJob")
    public void gdSzyZhEcgQueryNoCollectJob() {
        log.info("广东省中医珠海，检索动态心电血压未采集患者采集任务开始！");
        try {
            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");
            List<String> patientIds = basicMapper.getNoCollectPatientIds(collectorId);
            reportCollectService.collectEcg(patientIds);
            log.info("广东省中医珠海，检索动态心电血压未采集患者采集任务结束！");
        } catch (Exception e) {
            log.info("广东省中医珠海，检索动态心电血压未采集患者采集任务异常！" + e.getMessage(), e);
        }
    }

}
