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.UserBalanceInsufficientCheckoutPayload;
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 UserBalanceInsufficientCheckoutHandler 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) {
        UserBalanceInsufficientCheckoutPayload payload = event.normalizedData(UserBalanceInsufficientCheckoutPayload.class);
        log.info("UserBalanceInsufficientCheckoutHandler payload:{}", payload);
        if (payload.getUserId() == null) {
            return;
        }
        //加锁，防止并发统计出问题
        String userBalanceInsufficientCheckoutLockKey = redisKeyUtils.userBalanceInsufficientCheckoutLockKey(payload.getUserId());
        RedisLock redisLock = new RedisLock(userBalanceInsufficientCheckoutLockKey, redisWrapper);
        redisLock.tryAcquireRun(() -> {
            userDeductionStatService.userDeductionCheckout(payload.getUserId());
            return true;
        });
    }

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