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

import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.vip.domain.VipQuery;
import com.ruoyi.ss.vip.service.VipService;
import com.ruoyi.ss.vipLevel.domain.VipLevelVO;
import com.ruoyi.ss.vipLevel.service.VipLevelService;
import com.ruoyi.ss.vipLevel.service.VipLevelValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author wjh
 * 2024/12/9
 */
@Service
public class VipLevelValidatorImpl implements VipLevelValidator {

    @Autowired
    private VipLevelService vipLevelService;

    @Autowired
    private VipService vipService;

    /**
     * 用户是否可见
     *
     * @param vo
     * @param userId
     */
    @Override
    public boolean canView(VipLevelVO vo, Long userId) {
        return vo != null && userId != null && Objects.equals(vo.getMchId(), userId);
    }

    @Override
    public boolean canOpera(Long id, Long userId) {
        if (userId == null || id == null) {
            return false;
        }
        VipLevelVO vo = vipLevelService.selectVipLevelById(id);
        return canOpera(vo, userId);
    }

    @Override
    public boolean canOperaAll(List<Long> ids, Long userId) {
        if (CollectionUtils.isEmptyElement(ids) || userId == null) {
            return false;
        }
        List<VipLevelVO> list = vipLevelService.selectByIds(ids);
        for (VipLevelVO vo : list) {
            if (!this.canOpera(vo, userId)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean canOpera(VipLevelVO vo, Long userId) {
        return vo != null && userId != null && Objects.equals(vo.getMchId(), userId);
    }

    @Override
    public void beforeDel(List<Long> ids) {
        ServiceUtil.assertion(CollectionUtils.isEmptyElement(ids), "参数错误");

        // 判断当前等级下还有没有VIP
        ServiceUtil.assertion(this.hasVip(ids), "待删除的等级中还有用户正在使用中，请先删除对应VIP后重试");;
    }

    private boolean hasVip(List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return false;
        }
        VipQuery query = new VipQuery();
        query.setVipLevelIds(ids);
        return vipService.selectCount(query) > 0;
    }
}
