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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.base.pojo.enums.ShellControlEnum;
import com.zanxiang.game.module.mybatis.entity.GameAppletShell;
import com.zanxiang.game.module.mybatis.entity.GameExt;
import com.zanxiang.game.module.mybatis.entity.GameUserRole;
import com.zanxiang.game.module.mybatis.entity.User;
import com.zanxiang.game.module.mybatis.mapper.GameAppletShellMapper;
import com.zanxiang.game.module.sdk.enums.ShellSwitchEnum;
import com.zanxiang.game.module.sdk.pojo.result.IpCheckResult;
import com.zanxiang.game.module.sdk.service.IAliApiService;
import com.zanxiang.game.module.sdk.service.IGameAppletShellService;
import com.zanxiang.game.module.sdk.service.IGameExtService;
import com.zanxiang.game.module.sdk.service.IGameUserRoleService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.exception.BaseException;
import com.zanxiang.module.web.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author : lingfeng
 * @time : 2023-07-06
 * @description : 壳包控制
 */
@Slf4j
@Service
public class GameAppletShellServiceImpl extends ServiceImpl<GameAppletShellMapper, GameAppletShell> implements IGameAppletShellService {

    @Autowired
    private IGameExtService gameExtService;

    @Autowired
    private IGameUserRoleService gameUserRoleService;

    @Autowired
    private IAliApiService aliApiService;

    @Override
    public Integer getShellSwitch(String appId, String version) {
        log.error("壳包接口收到请求, appId : {}, version : {}", appId, version);
        GameExt gameExt = gameExtService.getByGameAppId(appId);
        if (gameExt == null) {
            throw new BaseException("游戏参数设置错误, 游戏信息不存在");
        }
        GameAppletShell gameAppletShell = super.getOne(new LambdaQueryWrapper<GameAppletShell>()
                .eq(GameAppletShell::getGameId, gameExt.getGameId()));
        if (gameAppletShell == null) {
            throw new BaseException("游戏参数设置错误, 游戏设置信息不存在");
        }
        //版本为提审版本
        if (Objects.equals(gameAppletShell.getArraignVersion(), version)) {
            return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
        }
        //线上版本
        if (Objects.equals(gameAppletShell.getProVersion(), version)) {
            //申诉中, 返回申诉状态
            if (Objects.equals(gameAppletShell.getIsAppeal(), Boolean.TRUE)) {
                return ShellSwitchEnum.SHELL_SWITCH_APPEAL.getShellSwitch();
            }
            //开启
            if (Objects.equals(gameAppletShell.getProControlType(), ShellControlEnum.SHELL_CONTROL_OPEN.getShellControl())) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            //返回关闭
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }
        //测试版本, 关闭壳包, 提审前版本测试
        if (Objects.equals(gameAppletShell.getTestVersion(), version)) {
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }
        //测试版本, 关闭壳包, 兼容需要多个版本的情况
        if (Strings.isNotBlank(gameAppletShell.getTestVersion()) && gameAppletShell.getTestVersion().contains(version)) {
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }
        //兜底逻辑,  找不到版本号直接返回进入壳包
        log.error("版本信息不存在, 默认进壳包, appId : {}, version : {}", appId, version);
        return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
    }

    @Override
    public Integer getUserShellSwitch(User user, boolean register, HttpServletRequest request) {
        GameAppletShell gameAppletShell = super.getOne(new LambdaQueryWrapper<GameAppletShell>()
                .eq(GameAppletShell::getGameId, user.getGameId()));
        //未设置, 统一返回关闭
        if (gameAppletShell == null) {
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }
        //控制类型
        Integer proControlType = gameAppletShell.getProControlType();
        //关闭
        if (Objects.equals(proControlType, ShellControlEnum.SHELL_CONTROL_CLOSE.getShellControl())) {
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }
        //开启
        if (Objects.equals(proControlType, ShellControlEnum.SHELL_CONTROL_OPEN.getShellControl())) {
            return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
        }
        //新用户开启
        if (Objects.equals(proControlType, ShellControlEnum.SHELL_CONTROL_NEW_USER_OPEN.getShellControl())) {
            return register ? ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch() : ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }

        //查询用户角色列表
        List<GameUserRole> gameUserRoleList = gameUserRoleService.list(new LambdaQueryWrapper<GameUserRole>()
                .eq(GameUserRole::getUserId, user.getId())
                .eq(GameUserRole::getGameId, user.getGameId()));

        //等级控制开启
        if (Objects.equals(proControlType, ShellControlEnum.SHELL_CONTROL_LOW_LEVEL_OPEN.getShellControl())) {
            //不存在角色的新用户, 开启
            if (CollectionUtils.isEmpty(gameUserRoleList)) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            //获取用户等级最好的角色
            GameUserRole gameUserRole = gameUserRoleList.stream().max(Comparator.comparing(GameUserRole::getRoleLevel)).orElse(null);
            //角色不存在, 或者等级小于等于控制等级
            if (gameUserRole == null || gameUserRole.getRoleLevel() <= gameAppletShell.getProControlLevel()) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }

        //省份屏蔽
        if (Objects.equals(proControlType, ShellControlEnum.SHELL_CONTROL_PROV_OPEN.getShellControl())) {
            if (Strings.isBlank(gameAppletShell.getProvShield())) {
                return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
            }
            String prov = null;
            try {
                IpCheckResult result = aliApiService.userIpCheck(IpUtil.getRealIp(request));
                prov = result.getData().getResult().getProv();
            } catch (Exception ignored) {
            }
            //未查询到归属地, 或者不包含屏蔽省份, 关闭壳包
            if (prov == null || !prov.contains(gameAppletShell.getProvShield())) {
                return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
            }
            //未设置更多的等级限制, 直接进壳
            if (gameAppletShell.getProControlLevel() == null) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            //不存在角色的新用户, 开启
            if (CollectionUtils.isEmpty(gameUserRoleList)) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            //获取用户等级最高的角色
            GameUserRole gameUserRole = gameUserRoleList.stream().max(Comparator.comparing(GameUserRole::getRoleLevel)).orElse(null);
            //角色不存在, 或者等级小于等于控制等级
            if (gameUserRole == null || gameUserRole.getRoleLevel() <= gameAppletShell.getProControlLevel()) {
                return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
            }
            return ShellSwitchEnum.SHELL_SWITCH_CLOSE.getShellSwitch();
        }

        log.error("壳包控制配置不存在, 默认进壳包, userId : {}, gameAppletShell : {}", user.getId(), JsonUtil.toString(gameAppletShell));
        return ShellSwitchEnum.SHELL_SWITCH_OPEN.getShellSwitch();
    }
}
