package com.zanxiang.game.module.sdk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.base.pojo.enums.HttpStatusEnum;
import com.zanxiang.game.module.mybatis.entity.UserBan;
import com.zanxiang.game.module.mybatis.mapper.UserBanMapper;
import com.zanxiang.game.module.sdk.pojo.param.UserData;
import com.zanxiang.game.module.sdk.service.IUserBanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

/**
 * @author : lingfeng
 * @time : 2022-06-28
 * @description : 玩家封禁管理
 */
@Slf4j
@Service
public class UserBanServiceImpl extends ServiceImpl<UserBanMapper, UserBan> implements IUserBanService {

    @Override
    public Tuple2<Boolean, HttpStatusEnum> banCheckByDevice(UserData userData) {
        //设备参数不存在, 无法检测
        if (StringUtils.isAllBlank(userData.getImei(), userData.getAndroidId(), userData.getOaid())) {
            return Tuples.of(Boolean.FALSE, HttpStatusEnum.SUCCESS);
        }
        //匹配已封禁设备标识
        LambdaQueryWrapper<UserBan> queryWrapper = new LambdaQueryWrapper<UserBan>()
                .eq(UserBan::getGameId, userData.getGameId())
                .eq(UserBan::getStatus, 1);
        queryWrapper.and(qw -> {
            boolean hasCondition = false;
            //安卓id匹配
            if (StringUtils.isNoneBlank(userData.getAndroidId())) {
                qw.or().eq(UserBan::getAndroidId, userData.getAndroidId());
                hasCondition = true;
            }
            //imei匹配
            if (StringUtils.isNoneBlank(userData.getImei())) {
                qw.or().eq(UserBan::getImei, userData.getImei());
                hasCondition = true;
            }
            //oaid匹配
            if (StringUtils.isNoneBlank(userData.getOaid())) {
                qw.or().eq(UserBan::getOaid, userData.getOaid());
                hasCondition = true;
            }
            // 避免无条件的OR查询
            if (!hasCondition) {
                qw.or().apply("1=0");
            }
        });
        //查询
        if (super.count(queryWrapper) > 0) {
            return Tuples.of(Boolean.TRUE, HttpStatusEnum.DEVICES_HALT);
        }
        return Tuples.of(Boolean.FALSE, HttpStatusEnum.SUCCESS);
    }

    @Override
    public boolean banCheckByCardId(Long gameId, String cardId) {
        //身份证号匹配
        return super.count(new LambdaQueryWrapper<UserBan>()
                .eq(UserBan::getGameId, gameId)
                .eq(UserBan::getCardId, cardId)
                .eq(UserBan::getStatus, 1)
        ) > 0;
    }
}
