package com.ruoyi.web.work.hl7.hl7service;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.app.HL7Service;
import ca.uhn.hl7v2.llp.MinLowerLayerProtocol;
import ca.uhn.hl7v2.parser.ParserConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 使用HL7监听器，监控目标端口收到的协议
 */
@Component
@Slf4j(topic = "hl7message")
public class HL7Monitor {

    @Autowired
    private HL7Properties mHL7Properties;
    @Autowired
    private HL7Business mHL7Business;
    private static HapiContext context = new DefaultHapiContext();

    @PostConstruct
    public void startWatchHL7(){
        if (!"1".equals(mHL7Properties.getFlag())) {
            return;
        }
        try {
            ThreadPoolExecutor executor = new ThreadPoolExecutor(
                    mHL7Properties.getCorePoolSize(), mHL7Properties.getMaximumPoolSize(),
                    mHL7Properties.getKeepAliveTime(), TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(mHL7Properties.getQueueCapacity()));
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            MinLowerLayerProtocol mllp = new MinLowerLayerProtocol();
            mllp.setCharset("UTF-8");
            context.setLowerLayerProtocol(mllp);
            context.setExecutorService(executor);
            //设置hl7不校验字段值
            ParserConfiguration tParserConfiguration = new ParserConfiguration();
            tParserConfiguration.setValidating(false);
            context.setParserConfiguration(tParserConfiguration);
            //创建监听服务
            boolean useSecureConnection = false;
            HL7Service ourHl7Server = context.newServer(mHL7Properties.getPort(), useSecureConnection);

            ourHl7Server.registerApplication(mHL7Business);
            ourHl7Server.startAndWait();
        } catch (Exception e) {
            log.error("hl7协议监听失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}