package com.sonic.frog.event.inner.handler;

import com.sonic.common.event.Event;
import com.sonic.common.event.EventConsumer;
import com.sonic.common.event.EventHandler;
import com.sonic.common.utils.RedisLock;
import com.sonic.frog.event.inner.EventType;
import com.sonic.frog.event.inner.payload.CalcHeartbeatLevelPayload;
import com.sonic.frog.service.AiUserHeartbeatRelationService;
import com.sonic.frog.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author code
 */
@Slf4j
@Component
public class CalcHeartbeatLevelHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private AiUserHeartbeatRelationService aiUserHeartbeatRelationService;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @Override
    public void onEvent(Event event) {
        CalcHeartbeatLevelPayload payload = event.normalizedData(CalcHeartbeatLevelPayload.class);
        log.info("CalcHeartbeatLevelHandler payload:{}", payload);
        //redis键
        String calcHeartbeatLevelLockKey = redisKeyUtils.calcHeartbeatLevelLockKey(payload.getUserId(), payload.getAiId());
        //加锁处理
        RedisLock redisLock = new RedisLock(calcHeartbeatLevelLockKey, redisWrapper);
        redisLock.tryAcquireRun(() -> {
            aiUserHeartbeatRelationService.calcAiUserHeartbeatLevel(payload);
            return true;
        });
    }

    @Override
    public void afterPropertiesSet() {
        eventConsumer.registerHandler(EventType.CALC_HEARTBEAT_LEVEL.getEventCode(), this);
    }
}
