package com.sonic.frog.event.outer.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.outer.EventType;
import com.sonic.frog.event.outer.payload.UserCratedPayload;
import com.sonic.frog.event.outer.payload.UserDeductionStatPayload;
import com.sonic.frog.service.UserDeductionStatService;
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 UserDeductionStatHandler implements EventHandler, InitializingBean {

    @Autowired
    private EventConsumer eventConsumer;
    @Autowired
    private UserDeductionStatService userDeductionStatService;
    @Autowired
    private RedisKeyUtils redisKeyUtils;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;

    @Override
    public void onEvent(Event event) {
        UserDeductionStatPayload payload = event.normalizedData(UserDeductionStatPayload.class);
        log.info("UserDeductionStatHandler payload:{}", payload);
        if (payload.getUserId() == null || payload.getAiId() == null || payload.getDeductionType() == null) {
            return;
        }
        //加锁，防止并发统计出问题
        String userDeductionsStatLockKey = redisKeyUtils.userDeductionsStatLockKey(payload.getUserId(), payload.getAiId(), payload.getDeductionType());
        RedisLock redisLock = new RedisLock(userDeductionsStatLockKey, redisWrapper);
        redisLock.tryAcquireRun(() -> {
            userDeductionStatService.userDeductionStat(payload.getUserId(), payload.getAiId(), payload.getDeductionType(), payload.getExtra());
            return true;
        });
    }

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