
package com.tmerclub.cloud.user.controller.app;

import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.user.bo.mongo.MongoUserBalanceLogBO;
import com.tmerclub.cloud.user.model.UserExtension;
import com.tmerclub.cloud.user.service.UserBalanceLogService;
import com.tmerclub.cloud.user.service.UserExtensionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author tmerclub
 * @date 2021/5/11
 */
@RestController
@RequestMapping("/userBalance")
@Tag(name = "app-余额支付")
public class UserBalancePayController {

    @Autowired
    private UserExtensionService userExtensionService;

    @Autowired
    private RocketMQTemplate balancePayTemplate;

    @Autowired
    private UserBalanceLogService userBalanceLogService;

    @PostMapping("/balancePay")
    @Operation(summary = "支付", description = "余额支付")
    public ServerResponseEntity<Void> pay(@RequestBody Long payId) {
        Long userId = AuthUserContext.get().getUserId();

        UserExtension userExtension = userExtensionService.getByUserId(userId);

        // 获取用户可用余额
        Long balance = userExtension.getActualBalance();

        // 需要支付的金额
        MongoUserBalanceLogBO userBalanceLog = userBalanceLogService.getByPayId(payId);
        if (userBalanceLog.getChangeBalance() > balance) {
            return ServerResponseEntity.showFailMsg("余额不足");
        }

        TransactionSendResult transactionSendResult = balancePayTemplate.sendMessageInTransaction(RocketMqConstant.BALANCE_PAY_TOPIC, new GenericMessage<>(payId), userBalanceLog);


        if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        return ServerResponseEntity.success();
    }

}
