package digital.laboratory.platform.entrustment.listener;

import digital.laboratory.platform.entrustment.config.GlobalThreadPool;
import digital.laboratory.platform.entrustment.event.PushDataToLabsCareEvent;
import digital.laboratory.platform.entrustment.service.EntrustmentService;
import digital.laboratory.platform.entrustment.service.PushDataToLabsCareService;
import digital.laboratory.platform.entrustment.vo.EntrustmentVO;
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 EntrustmentService entrustmentService;

    @Resource
    private PushDataToLabsCareService pushDataToLabsCareService;

    /**
     * 处理委托数据推送事件
     *
     * @param event 委托数据推送事件对象
     */
    @Override
    public void onApplicationEvent(PushDataToLabsCareEvent event) {
        CompletableFuture.supplyAsync(() -> {
            // 获取委托信息
            EntrustmentVO entrustVO = entrustmentService.getEntrustmentVOById(event.getEntrustId());
            if (entrustVO == null) {
                log.warn("未找到委托信息, entrustId={}", event.getEntrustId());
                return null;
            }
            return entrustVO;
        }, GlobalThreadPool.getInstance()).thenAcceptAsync(entrustVO -> {
            if (entrustVO == null) return; // 提前返回，避免后续报错

            // 处理不同的推送类型
            switch (event.getPushType()) {
                case 1: // 推送委托书数据
                    try {
                        pushDataToLabsCareService.pushEntrustLetterData(entrustVO);
                    } catch (Exception e) {
                        log.error("委托编号 {} 的鉴定委托书数据推送失败！", entrustVO.getEntrustmentNo(), e);
                    }
                    break;
                case 2: // 推送鉴定事项确认书数据
                    try {
                        pushDataToLabsCareService.pushItemConfirmLetterData(entrustVO);
                    } catch (Exception e) {
                        log.error("受理编号 {} 的鉴定事项确认书数据推送失败！", entrustVO.getAcceptNo(), e);
                    }
                    break;
                default:
                    log.warn("未知的推送类型: {}", event.getPushType());
                    break;
            }
        }, GlobalThreadPool.getInstance()).exceptionally(e -> {
            log.error("推送数据到 LabsCare 失败", e);
            return null;
        });
    }

}
