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.archivemysql.entity.TBasic;
import com.docus.server.archivemysql.mapper.TBasicMapper;
import com.docus.server.fssyjhemr.entity.FsSyJswzhBmztEmrView;
import com.docus.server.fssyjhemr.mapper.FsSyJswzhBmztEmrViewMapper;
import com.docus.server.jobadmin.config.JobAdminConfig;
import com.docus.server.rpc.V3ViewTaskCollectService;
import com.docus.server.rpc.dto.CompensateTaskDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

    public static FsSyCatalogCollectTaskHelper getInstance() {
        return instance;
    }

    private Thread fsSyCatalogCollectTaskThread;
    private volatile boolean toStop = false;

    public void start() {
        fsSyCatalogCollectTaskThread = new Thread(() -> {
            TableJsonRead tableJsonRead = new TableJsonRead();
            FsSyJswzhBmztEmrViewMapper fsSyJswzhBmztEmrViewMapper = JobAdminConfig.getJobAdminConfig().getFsSyJswzhBmztEmrViewMapper();
            TBasicMapper tBasicMapper = JobAdminConfig.getJobAdminConfig().gettBasicMapper();
            V3ViewTaskCollectService v3ViewTaskCollectService = JobAdminConfig.getJobAdminConfig().getV3ViewTaskCollectService();
            String configPath = "data-config\\jobconfig";
            String configFileName = "FsSyCatalogCollectTask";
            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 maxBmsj = fsSyJswzhBmztEmrViewMapper.maxBmsj();
                    String maxBmsjStr = Func.formatDateTime(maxBmsj);
                    // 查询视图数据，视图数据查询患者信息id，进行任务生成
                            List<FsSyJswzhBmztEmrView> fsSyJswzhBmztEmrViews = fsSyJswzhBmztEmrViewMapper.listByBmsjRange(lastDate, maxBmsjStr, where);
                    if (Func.isNotEmpty(fsSyJswzhBmztEmrViews)) {
                        logger.info("首页编目数据查询，根据最后编目时间查询（不包含截止时间），开始时间：{}，截止时间：{},额外条件：{},视图数据：{} 条，数据为：{}", lastDate, maxBmsjStr, where, fsSyJswzhBmztEmrViews.size(), Func.toJson(fsSyJswzhBmztEmrViews));
                        for (FsSyJswzhBmztEmrView view : fsSyJswzhBmztEmrViews) {
                            String jzh = view.getJzh();
                            List<TBasic> tbasic = tBasicMapper.findTbasicByJzhs(Collections.singletonList(jzh));
                            if (Func.isEmpty(tbasic)) {
                                logger.warn("首页编目数据查询,记账号：{} 未找到患者主表数据！", jzh);
                                continue;
                            }
                            // 生成采集任务
                            List<String> patientIds = tbasic.stream().map(TBasic::getPatientId).collect(Collectors.toList());
                            CompensateTaskDTO compensateTaskDTO = new CompensateTaskDTO();
                            compensateTaskDTO.setPatientIds(patientIds);
                            compensateTaskDTO.setCollectorIds(Arrays.asList(sysCodes.split(",")));
                            compensateTaskDTO.setPriority(3);
                            logger.info("首页编目生成队列参数：{}", Func.toJson(compensateTaskDTO));
                            CommonResult<String> result = v3ViewTaskCollectService.compensateTask(compensateTaskDTO);
                            logger.info("首页编目生成队列返回结果：{}", Func.toJson(result));
                        }
                        // 刷新配置
                        jobConfig.put("lastDate", maxBmsjStr);
                        tableJsonRead.Save(configPath, configFileName, jobConfig.toJSONString());
                    }

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

            }
            logger.info(">>>>>>>>>>>  fsSy Catalog CollectTask Thread stop");
        });
        fsSyCatalogCollectTaskThread.setDaemon(true);
        fsSyCatalogCollectTaskThread.setName("fsSyCatalogCollectTaskHelper");
        fsSyCatalogCollectTaskThread.start();
    }

    public void toStop() {
        toStop = false;
        fsSyCatalogCollectTaskThread.interrupt();
        try {
            fsSyCatalogCollectTaskThread.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", "fsSyCatalogCollectTask", JSONObject.class);
        System.out.println(config);
    }
}
