package com.ruoyi.cai.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.constant.RedisConstant;
import com.ruoyi.cai.domain.Black;
import com.ruoyi.cai.mapper.BlackMapper;
import com.ruoyi.cai.service.BlackService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 黑名单Service业务层处理
 *
 * @author 77
 * @date 2024-01-04
 */
@Service
public class BlackServiceImpl extends ServiceImpl<BlackMapper,Black> implements BlackService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String getKey(Integer type){
        return String.format(RedisConstant.BLACK_REDIS,type);
    }

    @Override
    public boolean addBlack(Black black){
        black.setCreateById(LoginHelper.getUserId());
        black.setCreateByName(LoginHelper.getUsername());
        this.save(black);
        redisTemplate.opsForSet().add(getKey(black.getType()),black.getIpAddress());
        return true;
    }

    @Override
    public boolean updateBlackStatus(Long id,Integer enableStatus){
        Black black = this.getById(id);
        if(black == null){
            throw new ServiceException("数据不存在");
        }
        this.update(Wrappers.lambdaUpdate(Black.class).set(Black::getEnableStatus,enableStatus).eq(Black::getId,id));
        if(enableStatus == 1){
            redisTemplate.opsForSet().add(getKey(black.getType()),black.getIpAddress());
        }else {
            redisTemplate.opsForSet().remove(getKey(black.getType()),black.getIpAddress());
        }
        return true;
    }

    @Override
    public boolean deleteBlack(Long id){
        Black black = this.getById(id);
        if(black == null){
            throw new ServiceException("数据不存在");
        }
        this.removeById(id);
        redisTemplate.opsForSet().remove(getKey(black.getType()),black.getIpAddress());
        return true;
    }

    @Override
    public boolean checkBlackIp(String ip){
        Boolean member = redisTemplate.opsForSet().isMember(getKey(1), ip);
        return BooleanUtils.isTrue(member);
    }

    @Override
    public boolean checkBlackMic(String ip){
        Boolean member = redisTemplate.opsForSet().isMember(getKey(2), ip);
        return BooleanUtils.isTrue(member);
    }


}
