package digital.laboratory.platform.inspection.listener;


import digital.laboratory.platform.inspection.event.PushDataToLabsCareEvent;
import digital.laboratory.platform.inspection.service.PushDataToLabsCareService;
import digital.laboratory.platform.inspection.threadpool.GlobalThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * 监听有关推送数据到LabsCare 平台的事件， 采用异步
 */
@Slf4j
//@Component
public class PushDataToLabsCareEventListener implements ApplicationListener<PushDataToLabsCareEvent> {

    @Resource
    private PushDataToLabsCareService pushDataToLabsCareService;

    /**
     * 处理委托数据推送事件
     *
     * @param event 委托数据推送事件对象
     */
    @Override
    public void onApplicationEvent(PushDataToLabsCareEvent event) {
        CompletableFuture.runAsync(() -> {
            // 处理不同的推送类型
            switch (event.getPushType()) {
                case 3: // 推送委托书数据
                    try {
                        pushDataToLabsCareService.pushBiologyQualitativeRecordData(event.getTestId());
                    } catch (Exception e) {
                        log.error("实验id为 {} 的生物定性检验记录数据推送失败！", event.getTestId(), e);
                    }
                    break;
                case 4: // 推送委托书数据
                    try {
                        pushDataToLabsCareService.pushNonInfraredGeneralQualitativeRecordData(event.getTestId());
                    } catch (Exception e) {
                        log.error("实验id为 {} 的普通检材定性记录非红外报告数据推送失败！", event.getTestId(), e);
                    }
                    break;
                default:
                    log.warn("未知的推送类型: {}", event.getPushType());
                    break;
            }
        }, GlobalThreadPool.getInstance()).exceptionally(e -> {
            log.error("推送数据到 LabsCare 失败", e);
            return null;
        });
    }

}
