package com.docus.server.jobadmin.thread;

import com.alibaba.fastjson.JSONObject;
import com.docus.core.util.Func;
import com.docus.infrastructure.core.utils.TableJsonRead;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.server.archivesqlserver.entity.ArchiveMaster;
import com.docus.server.archivesqlserver.mapper.ArchiveMasterMapper;
import com.docus.server.jobadmin.config.JobAdminConfig;
import com.docus.server.rpc.V2ViewTaskCollectService;
import com.docus.server.rpc.dto.TaskMakeupDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 湛江附属医院费用清单采集任务job
 *
 * @author YongBin Wen
 * @date 2024/1/23 10:59
 */

public class ZjFsCostListCollectTaskHelper {
    private static final Logger logger = LoggerFactory.getLogger(ZjFsCostListCollectTaskHelper.class);
    private static final ZjFsCostListCollectTaskHelper instance = new ZjFsCostListCollectTaskHelper();

    public static ZjFsCostListCollectTaskHelper getInstance() {
        return instance;
    }

    private Thread zjFsCostListCollectTaskThread;
    private volatile boolean toStop = false;

    public void start() {
        zjFsCostListCollectTaskThread = new Thread(() -> {
            TableJsonRead tableJsonRead = new TableJsonRead();
            ArchiveMasterMapper archiveMasterMapper = JobAdminConfig.getJobAdminConfig().getArchiveMasterMapper();
            V2ViewTaskCollectService v2ViewTaskCollectService = JobAdminConfig.getJobAdminConfig().getV2ViewTaskCollectService();
            String configPath = "data-config\\jobconfig";
            String configFileName = "ZjFsCostListCollectTask";
            while (!toStop) {
                try {
                    LocalDateTime runTime = LocalDateTime.now();
                    // 读取配置，实时观察配置文件状况
                    JSONObject jobConfig = tableJsonRead.Read(configPath, configFileName, JSONObject.class);
                    int jobIntervalSeconds = jobConfig.getIntValue("jobIntervalSeconds");
                    String lastDate = jobConfig.getString("lastDate");
                    String sysCodes = jobConfig.getString("sysCodes");
                    int delayDays = jobConfig.getIntValue("delayDays");
                    LocalDateTime nextSelectDateTime = runTime.plusDays(-delayDays);
                    int open = jobConfig.getIntValue("open");
                    if (open == 0) {
                        TimeUnit.SECONDS.sleep(60);
                        continue;
                    }
                    // 下次执行的开始时间为现在时间减去间隔时间
                    String nextSelectDateTimeStr=Func.formatDateTime(nextSelectDateTime);
                    if(Func.isBlank(lastDate)){
                        lastDate=nextSelectDateTimeStr;
                    }

                    // 查询视图数据，视图数据查询患者信息id，进行任务生成
                    List<ArchiveMaster> archiveMasterList = archiveMasterMapper.listByNoCollectTaskAndGeDisDate(lastDate, sysCodes);
                    if (archiveMasterList == null) {
                        archiveMasterList = new ArrayList<>();
                    }
                    logger.info("查询未生成费用清单队列 {} 的患者基础数据,出院时间大于等于 {} 的数据有 {} 条，数据为：{}",sysCodes,lastDate,archiveMasterList.size(),Func.toJson(archiveMasterList));

                    if (!archiveMasterList.isEmpty()) {
                        // 生成采集任务
                        List<String> masterIds = archiveMasterList.stream().map(ArchiveMaster::getId).collect(Collectors.toList());
                        TaskMakeupDto makeupDto = new TaskMakeupDto();
                        makeupDto.setPatientIds(masterIds);
                        makeupDto.setSysCodes(sysCodes);
                        logger.info("费用清单生成队列参数：{}", Func.toJson(makeupDto));
                        CommonResult<String> result = v2ViewTaskCollectService.generateTaskByPatientIdAndSysCodes(makeupDto);
                        logger.info("费用清单生成队列返回结果：{}", Func.toJson(result));
                    }

                    // 刷新配置
                    jobConfig.put("lastDate", nextSelectDateTimeStr);
                    tableJsonRead.Save(configPath, configFileName, jobConfig.toJSONString());
                    TimeUnit.SECONDS.sleep(jobIntervalSeconds);
                } catch (Exception ex) {
                    if (!toStop) {
                        logger.error(">>>>>>>>>>> zjFs CostList CollectTask Thread error:" + ex.getMessage(), ex);
                        try {
                            TimeUnit.SECONDS.sleep(60);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            logger.info(">>>>>>>>>>>  zjFs CostList CollectTask Thread stop");
        });
        zjFsCostListCollectTaskThread.setDaemon(true);
        zjFsCostListCollectTaskThread.setName("ZjFsCostListCollectTaskHelper");
        zjFsCostListCollectTaskThread.start();
    }

    public void toStop() {
        toStop = false;
        zjFsCostListCollectTaskThread.interrupt();
        try {
            zjFsCostListCollectTaskThread.join();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    public static void main(String[] args) {
        TableJsonRead tableJsonRead = new TableJsonRead();
        JSONObject config = tableJsonRead.Read("data-config\\jobconfig", "ZjFsCatalogCollectTask", JSONObject.class);
        System.out.println(config);
    }
}
