package cn.axzo.workflow.core.common.event;

import cn.axzo.workflow.core.conf.SupportRefreshProperties;
import cn.axzo.workflow.core.repository.entity.ExtAxMqLog;
import cn.axzo.workflow.core.service.ExtAxMqLogService;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Api Log 记录表操作监听
 *
 * @author wangli
 * @since 2024/4/3 10:37
 */
@Component
@Slf4j
public class MqLogListener implements ApplicationListener<MqLogEvent> {

    @Resource
    private SupportRefreshProperties refreshProperties;
    @Resource
    private ExtAxMqLogService mqLogService;


    @SneakyThrows
    @Override
    public void onApplicationEvent(MqLogEvent event) {
        log.info("receive mq log event");
        if (!refreshProperties.getMqLogEnable()) {
            return;
        }
        switch (event.getEventType()) {
            case INSERT:
                insert(buildMqLogEntity(event));
                break;
            case UPDATE:
                update(buildMqLogEntity(event));
                break;
            case DELETE:
                delete(buildMqLogEntity(event));
                break;
            default:
                break;
        }
    }

    private ExtAxMqLog buildMqLogEntity(MqLogEvent event) {
        ExtAxMqLog entity = new ExtAxMqLog();
        entity.setUniqueId(event.getUniqueId());
        entity.setMessageId(event.getMessageId());
        entity.setMqTag(event.getMqTag());
        entity.setMqKey(event.getMqKey());
        entity.setMessageBody(event.getMessageBody());
        entity.setTraceId(event.getTraceId());
        return entity;
    }

    private void delete(ExtAxMqLog event) {
        log.info("delete mq log, event: {}", JSONUtil.toJsonStr(event));
        event.setDeleteThreadName(Thread.currentThread().getName());
        mqLogService.delete(event);
    }

    private void update(ExtAxMqLog event) {
        log.info("update mq log, event: {}", JSONUtil.toJsonStr(event));
        event.setUpdateThreadName(Thread.currentThread().getName());
        mqLogService.update(event);
    }

    private void insert(ExtAxMqLog event) {
        log.info("insert mq log, event: {}", JSONUtil.toJsonStr(event));
        event.setInsertThreadName(Thread.currentThread().getName());
        mqLogService.insert(event);
    }

}
