package com.tmerclub.cloud.user.feign;

import com.tmerclub.cloud.api.user.feign.UserWithdrawCashFeignClient;
import com.tmerclub.cloud.common.constant.AllinpayPayStatus;
import com.tmerclub.cloud.common.constant.AllinpayWithdrawCashStatusType;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.user.constant.RechargeTypeEnum;
import com.tmerclub.cloud.user.model.UserWithdrawCash;
import com.tmerclub.cloud.user.service.UserExtensionService;
import com.tmerclub.cloud.user.service.UserWithdrawCashService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author gaozijie
 * @date 2023-04-24
 */
@DubboService
public class UserWithdrawCashFeignController implements UserWithdrawCashFeignClient {

    @Autowired
    private UserExtensionService userExtensionService;
    @Autowired
    private UserWithdrawCashService userWithdrawCashService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponseEntity<Void> withdrawBack(String bizOrderNo,
                                                   String payStatus,
                                                   String payFailMessage) {
        // 查询提现记录
        UserWithdrawCash withdrawCash = userWithdrawCashService.getByBizOrderNo(bizOrderNo);
        if (withdrawCash == null) {
            throw new LuckException("提现记录不存在");
        }
        // 更新提现记录
        boolean isOk = Objects.equals(payStatus, AllinpayPayStatus.OK.value());
        if (isOk) {
            withdrawCash.setStatus(AllinpayWithdrawCashStatusType.CASH_SUCCESS.value());
            userWithdrawCashService.update(withdrawCash);
        } else {
            withdrawCash.setStatus(AllinpayWithdrawCashStatusType.CASH_FAIL.value());
            withdrawCash.setPayFailMessage(payFailMessage);
            userWithdrawCashService.update(withdrawCash);
            // 提现失败，不做余额变动
            return ServerResponseEntity.success();
        }
        // 余额变动，新增余额日志
        userExtensionService.changeAllinpayBalance(
                withdrawCash.getUserId(), -withdrawCash.getAmount(), RechargeTypeEnum.WITHDRAW.value()
        );
        return ServerResponseEntity.success();
    }
}
