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 com.docus.server.zjfsjhemr.entity.ZjFsPatIndexView;
import com.docus.server.zjfsjhemr.mapper.ZjFsPatIndexViewMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
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 ZjFsCatalogCollectTaskHelper {
    private static final Logger logger = LoggerFactory.getLogger(ZjFsCatalogCollectTaskHelper.class);
    private static final ZjFsCatalogCollectTaskHelper instance = new ZjFsCatalogCollectTaskHelper();

    public static ZjFsCatalogCollectTaskHelper getInstance() {
        return instance;
    }

    private Thread zjFsCatalogCollectTaskThread;
    private volatile boolean toStop = false;

    public void start() {
        zjFsCatalogCollectTaskThread = new Thread(() -> {
            TableJsonRead tableJsonRead = new TableJsonRead();
            ZjFsPatIndexViewMapper zjFsPatIndexViewMapper = JobAdminConfig.getJobAdminConfig().getZjFsPatIndexViewMapper();
            ArchiveMasterMapper archiveMasterMapper = JobAdminConfig.getJobAdminConfig().getArchiveMasterMapper();
            V2ViewTaskCollectService v2ViewTaskCollectService = JobAdminConfig.getJobAdminConfig().getV2ViewTaskCollectService();
            String configPath = "data-config\\jobconfig";
            String configFileName = "ZjFsCatalogCollectTask";
            while (!toStop) {
                try {
                    // 读取配置，实时观察配置文件状况
                    JSONObject jobConfig = tableJsonRead.Read(configPath, configFileName, JSONObject.class);
                    int jobIntervalSeconds = jobConfig.getIntValue("jobIntervalSeconds");
                    String lastDate = jobConfig.getString("lastDate");
                    String sysCodes = jobConfig.getString("sysCodes");
                    String where = jobConfig.getString("where");
                    if (where == null) {
                        where = "";
                    }
                    int open = jobConfig.getIntValue("open");
                    if (open == 0) {
                        TimeUnit.SECONDS.sleep(60);
                        continue;
                    }

                    Date maxCatalogDate = zjFsPatIndexViewMapper.maxCatalogDate();
                    String maxCatalogDateStr = Func.formatDateTime(maxCatalogDate);
                    // 查询视图数据，视图数据查询患者信息id，进行任务生成
                    List<ZjFsPatIndexView> zjFsPatIndexViews = zjFsPatIndexViewMapper.listByCatalogDateRange(lastDate, maxCatalogDateStr, where);
                    if (Func.isNotEmpty(zjFsPatIndexViews)) {
                        logger.info("首页编目数据查询，根据最后编目时间查询（不包含截止时间），开始时间：{}，截止时间：{},额外条件：{},视图数据：{} 条，数据为：{}", lastDate, maxCatalogDateStr, where, zjFsPatIndexViews.size(), Func.toJson(zjFsPatIndexViews));
                        for (ZjFsPatIndexView view : zjFsPatIndexViews) {
                            String inpNo = view.getInpNo();
                            Integer visitId = view.getVisitId();
                            ArchiveMaster condition = new ArchiveMaster();
                            condition.setInpNo(inpNo);
                            condition.setVisitId(visitId.toString());
                            List<ArchiveMaster> archiveMasters = archiveMasterMapper.listByCondition(condition);
                            if (Func.isEmpty(archiveMasters)) {
                                logger.warn("首页编目数据查询,住院号：{},住院次数：{} 未找到患者主表数据！", inpNo, visitId);
                                continue;
                            }
                            // 生成采集任务
                            List<String> masterIds = archiveMasters.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", maxCatalogDateStr);
                        tableJsonRead.Save(configPath, configFileName, jobConfig.toJSONString());
                    }

                    TimeUnit.SECONDS.sleep(jobIntervalSeconds);
                } catch (Exception ex) {
                    if (!toStop) {
                        logger.error(">>>>>>>>>>> zjFs Catalog CollectTask Thread error:" + ex.getMessage(), ex);
                        try {
                            TimeUnit.SECONDS.sleep(60);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            logger.info(">>>>>>>>>>>  zjFs Catalog CollectTask Thread stop");
        });
        zjFsCatalogCollectTaskThread.setDaemon(true);
        zjFsCatalogCollectTaskThread.setName("ZjFsCatalogCollectTaskHelper");
        zjFsCatalogCollectTaskThread.start();
    }

    public void toStop() {
        toStop = false;
        zjFsCatalogCollectTaskThread.interrupt();
        try {
            zjFsCatalogCollectTaskThread.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);
    }
}
