
package com.tmerclub.cloud.auth.listener;

import com.tmerclub.cloud.api.auth.bo.UserRegisterNotifyBO;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.dto.AuthAccountDTO;
import com.tmerclub.cloud.auth.model.AuthAccount;
import com.tmerclub.cloud.auth.service.AuthAccountService;
import com.tmerclub.cloud.common.util.Json;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户注册监听
 *
 * @author tmerclub
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "userNotifyRegisterTemplate", maximumPoolSize = 20)
public class BatchUserRegisterTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private AuthAccountService authAccountService;

    @SuppressWarnings("unchecked")
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object authAccounts) {
        int row = authAccountService.batchSaveAccounts((List<AuthAccount>) authAccounts);
        if (row == 0) {
            checkLocalTransaction(msg);
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        UserRegisterNotifyBO userRegisterNotifyBO = Json.parseObject((byte[]) msg.getPayload(), UserRegisterNotifyBO.class);
        List<Long> userIds = userRegisterNotifyBO.getAccountDTOList().stream().map(AuthAccountDTO::getUserId).collect(Collectors.toList());
        // 如果插入的数据为0，这个时候我们是不需要插入数据的，则不用提交了
        int row = authAccountService.countByUserIds(userIds, SysTypeEnum.ORDINARY.value());
        if (row == 0) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
