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.redis.service.IdService;
import com.docus.infrastructure.web.api.CommonResult;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.archivemysql.entity.TBasic;
import com.docus.server.archivemysql.entity.TaskMakeupOnView;
import com.docus.server.archivemysql.mapper.TBasicMapper;
import com.docus.server.jobadmin.config.JobAdminConfig;
import com.docus.server.rpc.V3ViewTaskCollectService;
import com.docus.server.rpc.dto.CompensateTaskDTO;
import com.docus.server.zqdyrmyy.entity.ZqDyRmYyOutpatientLisReportView;
import com.docus.server.zqdyrmyy.mapper.ZqDyRmYyOutpatientLisReportViewMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 佛山三院医院编目采集任务job
 *
 * @author YongBin Wen
 * @date 2024/1/23 10:59
 */

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

    public static ZqDyRmYyLabPacsCollectTaskHelper getInstance() {
        return instance;
    }

    private Thread zqDyRmYyLabPacsCollectTaskThread;
    private volatile boolean toStop = false;

    public void start() {
        zqDyRmYyLabPacsCollectTaskThread = new Thread(() -> {
            TableJsonRead tableJsonRead = new TableJsonRead();
            ZqDyRmYyOutpatientLisReportViewMapper zqDyRmYyOutpatientLisReportViewMapper = JobAdminConfig.getJobAdminConfig().getZqDyRmYyOutpatientLisReportViewMapper();
            TBasicMapper tBasicMapper = JobAdminConfig.getJobAdminConfig().gettBasicMapper();
            IdService idService = JobAdminConfig.getJobAdminConfig().getIdService();
            V3ViewTaskCollectService v3ViewTaskCollectService = JobAdminConfig.getJobAdminConfig().getV3ViewTaskCollectService();
            String configPath = "data-config\\jobconfig";
            String configFileName = "ZqDyRmYyLabPacsCollectTask";
            while (!toStop) {
                try {
                    // 读取配置，实时观察配置文件状况
                    JSONObject jobConfig = tableJsonRead.Read(configPath, configFileName, JSONObject.class);
                    int jobIntervalSeconds = jobConfig.getIntValue("jobIntervalSeconds");
                    int delayDays = jobConfig.getIntValue("delayDays");
                    String labSysCode = jobConfig.getString("lab");
                    String pacsSysCode = jobConfig.getString("pacs");
                    int open = jobConfig.getIntValue("open");
                    if (open == 0) {
                        TimeUnit.SECONDS.sleep(60);
                        continue;
                    }
                    LocalDate startDate = LocalDate.now().plusDays(-delayDays);
                    String startDateTime = startDate + " 00:00:00";

                    List<ZqDyRmYyOutpatientLisReportView> lisReportViews = zqDyRmYyOutpatientLisReportViewMapper.findOutpatientLisReportByReportDate(startDateTime);

                    if (Func.isNotEmpty(lisReportViews)) {
                        Map<String, List<ZqDyRmYyOutpatientLisReportView>> groupPatientReport = new HashMap<>();
                        for (ZqDyRmYyOutpatientLisReportView lisReportView : lisReportViews) {
                            String key = lisReportView.getInpatientNo() + "_" + lisReportView.getAdmissTimes() + "_" + lisReportView.getType();
                            groupPatientReport.computeIfAbsent(key, k -> new ArrayList<>()).add(lisReportView);
                        }

                        Set<Map.Entry<String, List<ZqDyRmYyOutpatientLisReportView>>> entries = groupPatientReport.entrySet();
                        for (Map.Entry<String, List<ZqDyRmYyOutpatientLisReportView>> entry : entries) {
                            List<ZqDyRmYyOutpatientLisReportView> views = entry.getValue();
                            ZqDyRmYyOutpatientLisReportView maxReportDateView = views.stream()
                                    .max(Comparator.comparing(ZqDyRmYyOutpatientLisReportView::getReportDate))
                                    .orElse(null);
                            if (maxReportDateView == null) {
                                continue;
                            }
                            List<TBasic> tBasicList = tBasicMapper.findTbasicByInpatientNo(maxReportDateView.getInpatientNo());
                            if (Func.isEmpty(tBasicList)) {
                                continue;
                            }
                            TBasic basic = tBasicList.stream()
                                    .filter(tBasic -> maxReportDateView.getInpatientNo().equalsIgnoreCase(tBasic.getInpatientNo())
                                            && maxReportDateView.getAdmissTimes().equals(tBasic.getAdmissTimes()))
                                    .findFirst().orElse(null);
                            if (basic == null) {
                                continue;
                            }
                            String patientId = basic.getPatientId();
                            String collectSys = "检验".equals(maxReportDateView.getType()) ? labSysCode : pacsSysCode;

                            TaskMakeupOnView taskMakeup = tBasicMapper.findTaskMakeup(maxReportDateView.getInpatientNo(), maxReportDateView.getAdmissTimes(), collectSys);
                            boolean isUpdate = taskMakeup != null;
                            if (isUpdate) {
                                if (!maxReportDateView.getReportDate().after(taskMakeup.getReportLastModify())) {
                                    continue;
                                }
                            } else {
                                taskMakeup = new TaskMakeupOnView();
                                taskMakeup.setId(idService.getDateSeq());
                                taskMakeup.setInpatientNo(maxReportDateView.getInpatientNo());
                                taskMakeup.setAdmissTimes(maxReportDateView.getAdmissTimes());
                                taskMakeup.setName(maxReportDateView.getName());
                                taskMakeup.setCollectSysType(collectSys);

                            }
                            taskMakeup.setPatientId(patientId);
                            taskMakeup.setReportLastModify(maxReportDateView.getReportDate());

                            List<String> patientIds = Collections.singletonList(patientId);
                            CompensateTaskDTO compensateTaskDTO = new CompensateTaskDTO();
                            compensateTaskDTO.setPatientIds(patientIds);
                            compensateTaskDTO.setCollectorIds(Collections.singletonList(collectSys));
                            compensateTaskDTO.setPriority(3);
                            logger.info("肇庆检查、检验补偿生成队列参数：{}", Func.toJson(compensateTaskDTO));
                            CommonResult<String> result = v3ViewTaskCollectService.compensateTask(compensateTaskDTO);
                            logger.info("肇庆检查、检验补偿生成队列返回结果：{}", Func.toJson(result));
                            if (result != null && result.getCode().equals(ResultCode.SUCCESS.getCode())) {
                                if (isUpdate) {
                                    tBasicMapper.update(taskMakeup);
                                } else {
                                    tBasicMapper.insert(taskMakeup);
                                }
                            }
                        }
                    }
                    TimeUnit.SECONDS.sleep(jobIntervalSeconds);
                } catch (Exception ex) {
                    if (!toStop) {
                        logger.error(">>>>>>>>>>> zqDyRmYy LabPacs CollectTask Thread error:" + ex.getMessage(), ex);
                        try {
                            TimeUnit.SECONDS.sleep(60);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            logger.info(">>>>>>>>>>>  zqDyRmYy LabPacs CollectTask Thread stop");
        });
        zqDyRmYyLabPacsCollectTaskThread.setDaemon(true);
        zqDyRmYyLabPacsCollectTaskThread.setName("zqDyRmYyLabPacsCollectTaskHelper");
        zqDyRmYyLabPacsCollectTaskThread.start();
    }

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