package com.sckw.payment.service;

import com.sckw.core.exception.BusinessException;
import com.sckw.core.utils.StringUtils;
import com.sckw.payment.api.model.constant.ChannelEnum;
import com.sckw.payment.api.model.dto.common.R;
import com.sckw.payment.model.dto.common.BusinessNo;
import com.sckw.payment.model.dto.wallet.PatchPay;
import com.sckw.payment.model.dto.wallet.WalletInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author xucaiqin
 * @date 2023-09-20 15:04:06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WalletBusinessService {
    private final PayCenterService payCenterService;

    /**
     * 校验付款金额是否超过钱包可用余额
     *
     * @param uid         支付方
     * @param filter      收款方
     * @param channelEnum 渠道
     * @param price       支付金额 元
     */
    public void checkMoney(String uid, String filter, ChannelEnum channelEnum, BigDecimal price) {
        R<WalletInfo> walletInfoR = payCenterService.totalInfo(uid, channelEnum, filter);
        if (!walletInfoR.getStatus()) {
            throw new BusinessException(StringUtils.isNotBlank(walletInfoR.getMsg()) ? walletInfoR.getMsg() : "双方企业暂未开通电子钱包");
        }
        //钱包余额校验
        WalletInfo data = Objects.isNull(walletInfoR.getData()) ? new WalletInfo() : walletInfoR.getData();
        //可用余额 分
        BigDecimal money = data.getMoney();
        //付款金额大于钱包可用余额
        if (price.compareTo(money.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP)) > 0) {
            log.error("付款金额：{} 钱包可用余额：{}", price, money);
            throw new BusinessException("钱包可用余额不足");
        }
    }

    /**
     * 清分金额
     *
     * @param businessNo  流水号
     * @param uid
     * @param filter
     * @param channelEnum
     * @param price       清分金额
     * @param payType     支付方式 支付类型0-默认1-仅预付支付2-仅余额支付
     */
    public void splitMoney(String businessNo, String uid, String filter, ChannelEnum channelEnum, BigDecimal price, String payType) {
        long value = price.multiply(new BigDecimal("100")).longValueExact();
        List<PatchPay> split = new ArrayList<>() {{
            add(new PatchPay(filter, value, uid + "清分" + value + "至" + filter));
        }};
        R<BusinessNo> businessNoR = payCenterService.payAgentPayV2(uid, filter, channelEnum, value, split, businessNo, payType);
        if (!businessNoR.getStatus()) {
            log.error("流水号：{} uid:{} filter:{} channel:{} price:{} payType:{}", businessNoR, uid, filter, channelEnum, price, payType);
            throw new BusinessException(businessNoR.getMsg());
        }
    }
}
