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

import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.ss.store.service.StoreValidator;
import com.ruoyi.ss.user.service.UserValidator;
import com.ruoyi.ss.vip.domain.Vip;
import com.ruoyi.ss.vip.domain.VipQuery;
import com.ruoyi.ss.vip.domain.VipVO;
import com.ruoyi.ss.vip.service.VipService;
import com.ruoyi.ss.vip.service.VipValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author wjh
 * 2024/12/9
 */
@Service
public class VipValidatorImpl implements VipValidator {

    @Autowired
    private VipService vipService;

    @Autowired
    private UserValidator userValidator;

    @Autowired
    private StoreValidator storeValidator;

    /**
     * 新增、更新前校验
     *
     * @param data
     */
    @Override
    public void beforeCheck(Vip data) {
        ServiceUtil.assertion(data == null, "参数错误");

        this.checkRepeatUserStore(data.getId(), data.getUserId(), data.getStoreId());
    }


    @Override
    public void afterCheck(VipVO vo) {
        if (vo == null) {
            return;
        }
        this.checkRepeatUserStore(vo.getId(), vo.getUserId(), vo.getStoreId());

        this.checkMch(vo.getStoreMchId(), vo.getVipMchId());
    }

    @Override
    public boolean canView(VipVO vo, Long userId) {
        return vo != null && userId != null && Objects.equals(vo.getStoreMchId(), userId);
    }

    private void checkMch(Long storeMchId, Long vipMchId) {
        ServiceUtil.assertion(!Objects.equals(storeMchId, vipMchId), "当前选择的VIP等级与店铺商户不一致");
    }

    /**
     * 校验用户是否重复成为店铺会员
     * @param id 会员ID
     * @param userId 用户ID
     * @param storeId 店铺ID
     */
    private void checkRepeatUserStore(Long id, Long userId, Long storeId) {
        if (userId == null || storeId == null) {
            return;
        }
        VipQuery query = new VipQuery();
        query.setUserId(userId);
        query.setStoreId(storeId);
        query.setExcludeId(id);
        ServiceUtil.assertion(vipService.selectCount(query) > 0, "当前用户已经是店铺VIP，无法重复绑定");;
    }
}
