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

import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Service;

import com.ruoyi.bst.app.domain.AppVO;
import com.ruoyi.bst.channel.domain.ChannelVO;
import com.ruoyi.bst.channel.domain.enums.ChannelApiType;
import com.ruoyi.bst.channel.domain.vo.ChannelPaySubVO;
import com.ruoyi.bst.channel.domain.vo.ChannelPayVO;
import com.ruoyi.bst.creditUser.domain.CreditUserVO;
import com.ruoyi.bst.pay.service.PayValidator;
import com.ruoyi.bst.userApp.domain.UserAppVO;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

@Service
public class PayValidatorImpl implements PayValidator {


    @Override
    public void checkPay(AppVO app, ChannelVO channel, UserAppVO userApp, List<ChannelPayVO> channelPayList, CreditUserVO creditUser) {
        // 应用
        ServiceUtil.assertion(app == null || app.getId() == null, "应用不存在");

        // 渠道
        ServiceUtil.assertion(channel == null || channel.getChannelId() == null, "渠道不存在");
        ServiceUtil.assertion(channel.getEnabled() == null || !channel.getEnabled(), "当前渠道暂不可用");
        ServiceUtil.assertion(channel.getAppIds() == null || !channel.getAppIds().contains(app.getId()), "ID为%s的渠道不支持ID为%s的应用", channel.getChannelId(), app.getId());

        // 用户应用
        ServiceUtil.assertion(userApp == null, "用户在%s应用中未绑定账号", app.getName());

        // 可用渠道校验
        ServiceUtil.assertion(CollectionUtils.isEmptyElement(channelPayList), "当前订单无可用的支付渠道");
        ChannelPayVO channelPay = channelPayList.stream()
            .filter(item -> Objects.equals(item.getId(), channel.getChannelId()))
            .findFirst().orElse(null);
        ServiceUtil.assertion(channelPay == null, "当前不允许使用ID为%s的支付渠道", channel.getChannelId());

        // 挂账校验
        if (ChannelApiType.CREDIT.getType().equals(channel.getApiType())) {
            ServiceUtil.assertion(creditUser == null, "挂账用户不存在");
            ServiceUtil.assertion(!Objects.equals(creditUser.getUserId(), userApp.getUserId()), "挂账用户与当前用户不匹配");

            List<ChannelPaySubVO> subList = channelPay.getSubList();
            ServiceUtil.assertion(CollectionUtils.isEmptyElement(subList), "暂无可用挂账用户");
            ChannelPaySubVO sub = subList.stream()
                .filter(item -> Objects.equals(item.getId(), creditUser.getId()))
                .findFirst().orElse(null);
            ServiceUtil.assertion(sub == null, "当前支付不支持使用ID为%s的挂账用户", creditUser.getId());
        }
    }
}
