package com.ruoyi.bst.withdraw.service.impl;

import com.ruoyi.bst.withdraw.domain.enums.WithdrawServiceType;
import com.ruoyi.bst.withdraw.domain.vo.WithdrawAmountVO;
import com.ruoyi.bst.withdraw.service.WithdrawConverter;
import com.ruoyi.common.constants.ConfigKeys;
import com.ruoyi.common.core.domain.vo.UserVO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.system.config.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author wjh
 * 2025/4/7
 */
@Service
public class WithdrawConverterImpl implements WithdrawConverter {

    @Autowired
    private ConfigService configService;

    /**
     * 查询提现服务费
     */
    @Override
    public WithdrawAmountVO calcAmount(UserVO user, BigDecimal amount) {
        if (user == null || amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }

        String type = user.getWithdrawServiceType();
        BigDecimal value = user.getWithdrawServiceValue();
        ServiceUtil.assertion(StringUtils.isBlank(type), "提现服务费方式为空");
        ServiceUtil.assertion(value == null, "提现服务费为空");

        BigDecimal minAmount = configService.getDecimal(ConfigKeys.WITHDRAW_MIN_AMOUNT);
        BigDecimal maxAmount = configService.getDecimal(ConfigKeys.WITHDRAW_MAX_AMOUNT);

        WithdrawAmountVO vo = new WithdrawAmountVO();
        vo.setType(type);
        vo.setMinAmount(minAmount);
        vo.setMaxAmount(maxAmount);

        if (WithdrawServiceType.POINT.getCode().equals(type)) {
            vo.setPoint(value);
            BigDecimal serviceChange = value.multiply(amount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            vo.setServiceCharge(serviceChange);
        } else if(WithdrawServiceType.FIXED.getCode().equals(type)) {
            vo.setServiceCharge(value);
        } else {
            throw new ServiceException("暂不支持类型为" + type + "的提现服务费方式");
        }

        vo.setAmount(MathUtils.subtractDecimal(amount, vo.getServiceCharge()));

        return vo;
    }
}
