package com.ruoyi.ss.vipOrder.service.impl;

import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.ss.bonus.domain.BonusVO;
import com.ruoyi.ss.bonus.domain.enums.BonusArrivalType;
import com.ruoyi.ss.bonus.domain.enums.BonusBstType;
import com.ruoyi.ss.bonus.service.BonusService;
import com.ruoyi.ss.channel.domain.ChannelVO;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.vip.domain.VipVO;
import com.ruoyi.ss.vip.service.VipService;
import com.ruoyi.ss.vipLevel.domain.VipLevelVO;
import com.ruoyi.ss.vipLevel.domain.enums.VipLevelStatus;
import com.ruoyi.ss.vipOrder.domain.VipOrderVO;
import com.ruoyi.ss.vipOrder.domain.bo.AddPayVipOrderBO;
import com.ruoyi.ss.vipOrder.domain.dto.AddPayVipOrderDTO;
import com.ruoyi.ss.vipOrder.service.VipOrderValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author wjh
 * 2025/1/17
 */
@Service
public class VipOrderValidatorImpl implements VipOrderValidator {

    @Autowired
    private VipService vipService;

    @Autowired
    private BonusService bonusService;

    @Override
    public void preAddAndPay(AddPayVipOrderBO bo) {
        ServiceUtil.assertion(bo == null, "参数错误");

        AddPayVipOrderDTO dto = bo.getDto();
        VipLevelVO level = bo.getLevel();
        SmUserVO mch = bo.getMch();
        ChannelVO channel = bo.getChannel();
        SmUserVO user = bo.getUser();

        // 校验用户前端查看到的数据和后台数据是否一致
        ServiceUtil.assertion(level == null, "ID为%sVIP不存在", dto.getLevelId());
        ServiceUtil.assertion(!VipLevelStatus.ON_SALE.getStatus().equals(level.getStatus()), "ID为%s会员目前不可购买", level.getId());
        ServiceUtil.assertion(!Objects.equals(dto.getLevelLimitType(), level.getLimitType()), "当前使用限制已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelLimitType(), level.getLimitType());
        ServiceUtil.assertion(!Objects.equals(dto.getLevelLimitCount(), level.getLimitCount()), "当前限制次数已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelLimitCount(), level.getLimitCount());
        ServiceUtil.assertion(!Objects.equals(dto.getLevelLimitTotal(), level.getLimitTotal()), "当前总限制次数已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelLimitTotal(), level.getLimitTotal());
        ServiceUtil.assertion(level.getPrice() == null, "价格不允许为空，请重新下单");
        ServiceUtil.assertion(!MathUtils.equals(dto.getLevelPrice(), level.getPrice()), "当前价格已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelPrice(), level.getPrice());
        ServiceUtil.assertion(!Objects.equals(dto.getLevelTime(), level.getTime()), "当前可购买的时长已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelTime(), level.getTime());
        ServiceUtil.assertion(!MathUtils.equals(dto.getLevelDiscount(), level.getDiscount()), "当前折扣已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelDiscount(), level.getDiscount());
        ServiceUtil.assertion(!Objects.equals(dto.getLevelStoreId(), level.getStoreId()), "当前可用店铺已发生变化，请重新下单。当前值:%s，最新值:%s", dto.getLevelStoreId(), level.getStoreId());

        // 商户是否存在
        ServiceUtil.assertion(mch == null, "ID为%s的商户不存在", level.getMchId());
        // 用户是否存在
        ServiceUtil.assertion(user == null, "当前下单用户不存在");

        // 校验渠道是否可用
        ServiceUtil.assertion(channel == null, "ID为%s的支付渠道不存在", dto.getChannelId());
        ServiceUtil.assertion(channel.getEnabled() == null || !channel.getEnabled(), "ID为%s的支付渠道已禁用", channel.getChannelId());

        // 校验用户VIP兼容性，若不兼容，则校验是否有选择方案
//        if (this.isCompatibility(level, user)) {
//            ServiceUtil.assertion(StringUtils.isBlank(dto.getSolution()), "当前拥有的VIP与下单的VIP不兼容，请选择解决方案");
//        }
    }

    /**
     * 判断用户目前拥有的VIP与当前购买SKU是否兼容
     * @param level level
     * @param user 用户
     */
    private boolean isCompatibility(VipLevelVO level, SmUserVO user) {
        if (level == null  || user == null) {
            return false;
        }

        // 查询用户所拥有的当前VIP
        VipVO vip = vipService.selectUserSameVip(
                user.getUserId(),
                level.getId(),
                level.getDiscount(),
                level.getStoreId(),
                level.getLimitType(),
                level.getLimitCount()
        );

        return vip != null;
    }

    @Override
    public boolean canView(VipOrderVO order, Long userId) {
        if (order == null || userId == null) {
            return false;
        }
        return isBonus(order, userId) || isUser(order, userId);
    }

    /**
     * 判断用户是否是订单的分成方
     */
    private boolean isBonus(VipOrderVO order, Long userId) {
        if (order == null || userId == null) {
            return false;
        }

        // 查询订单的分成方
        List<BonusVO> bonusList = bonusService.selectBonusByBstId(BonusBstType.VIP, order.getId());

        // 判断用户是否分成方
        return bonusList.stream()
            .anyMatch(bonus ->
                BonusArrivalType.userList().contains(bonus.getArrivalType())
                && Objects.equals(bonus.getArrivalId(), userId)
            );
    }

    /**
     * 判断用户是否是订单的创建者
     */
    private boolean isUser(VipOrderVO order, Long userId) {
        return userId != null && order != null && Objects.equals(order.getUserId(), userId);
    }
}
