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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.manage.pojo.params.UserRechargeWhiteAddParam;
import com.zanxiang.game.module.manage.pojo.params.UserRechargeWhiteListParam;
import com.zanxiang.game.module.manage.pojo.vo.UserRechargeWhiteVO;
import com.zanxiang.game.module.manage.service.IGameUserRoleService;
import com.zanxiang.game.module.manage.service.IUserRechargeWhiteService;
import com.zanxiang.game.module.manage.service.IUserService;
import com.zanxiang.game.module.mybatis.entity.GameUserRole;
import com.zanxiang.game.module.mybatis.entity.User;
import com.zanxiang.game.module.mybatis.entity.UserRechargeWhite;
import com.zanxiang.game.module.mybatis.mapper.UserRechargeWhiteMapper;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : lingfeng
 * @time : 2025-05-13
 * @description : 玩家充值白名单
 */
@Slf4j
@Service
public class UserRechargeWhiteServiceImpl extends ServiceImpl<UserRechargeWhiteMapper, UserRechargeWhite> implements IUserRechargeWhiteService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGameUserRoleService gameUserRoleService;

    @Override
    public Map<Long, String> rechargeWhiteGameMap() {
        return Collections.singletonMap(36L, "仙剑Android通");
    }

    @Override
    public boolean addRechargeWhite(UserRechargeWhiteAddParam param) {
        //查询玩家
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getGameId, param.getGameId())
                .and(qw -> qw.eq(User::getMobile, param.getAccount())
                        .or().eq(User::getUsername, param.getAccount())
                        .or().eq(User::getId, param.getAccount()))
                .orderByDesc(User::getUpdateTime)
                .last("limit 1"));
        if (user == null) {
            throw new BaseException("添加玩家充值白名单失败, 玩家不存在");
        }
        //查询玩家是否已经添加
        if (super.count(new LambdaQueryWrapper<UserRechargeWhite>()
                .eq(UserRechargeWhite::getGameId, user.getGameId())
                .eq(UserRechargeWhite::getUserId, user.getId())
        ) > 0) {
            throw new BaseException("玩家已在白名单中, 禁止重复添加");
        }
        //新建保存
        return super.save(UserRechargeWhite.builder()
                .userId(user.getId())
                .gameId(user.getGameId())
                .createTime(LocalDateTime.now())
                .build());
    }

    @Override
    public IPage<UserRechargeWhiteVO> listOfPage(UserRechargeWhiteListParam param) {
        //玩家id列表
        List<Long> userIdList = null;
        //是否存在条件筛选
        boolean hasCondition = false;
        //账号条件
        if (Strings.isNotBlank(param.getAccount())) {
            userIdList = userService.list(new LambdaQueryWrapper<User>()
                    .eq(User::getGameId, param.getGameId())
                    .and(qw -> qw.eq(User::getMobile, param.getAccount())
                            .or().eq(User::getUsername, param.getAccount())
                            .or().eq(User::getId, param.getAccount()))
            ).stream().map(User::getId).collect(Collectors.toList());
            hasCondition = true;
        }
        //角色条件
        if (Strings.isNotBlank(param.getRoleId()) || Strings.isNotBlank(param.getRoleName())) {
            userIdList = gameUserRoleService.list(new LambdaQueryWrapper<GameUserRole>()
                    .eq(GameUserRole::getGameId, param.getGameId())
                    .in(CollectionUtils.isNotEmpty(userIdList), GameUserRole::getUserId, userIdList)
                    .eq(Strings.isNotBlank(param.getRoleId()), GameUserRole::getRoleId, param.getRoleId())
                    .like(Strings.isNotBlank(param.getRoleName()), GameUserRole::getRoleName, param.getRoleName())
            ).stream().map(GameUserRole::getUserId).distinct().collect(Collectors.toList());
            hasCondition = true;
        }
        //有条件, 但是未筛选出玩家id, 不返回数据
        if (hasCondition && CollectionUtils.isEmpty(userIdList)) {
            Page<UserRechargeWhiteVO> userRechargeWhiteVOPage = new Page<>(param.getPageNum(),
                    param.getPageSize(), 0L);
            userRechargeWhiteVOPage.setRecords(Collections.emptyList());
            return userRechargeWhiteVOPage;
        }
        //分页查询
        IPage<UserRechargeWhite> rechargeWhitePage = super.page(param.toPage(), new LambdaQueryWrapper<UserRechargeWhite>()
                .eq(UserRechargeWhite::getGameId, param.getGameId())
                .in(CollectionUtils.isNotEmpty(userIdList), UserRechargeWhite::getUserId, userIdList)
        );
        //对象转换
        Page<UserRechargeWhiteVO> userRechargeWhiteVOPage = new Page<>(rechargeWhitePage.getCurrent(),
                rechargeWhitePage.getSize(), rechargeWhitePage.getTotal());
        userRechargeWhiteVOPage.setRecords(this.toBatchVO(rechargeWhitePage.getRecords()));
        return userRechargeWhiteVOPage;
    }

    private List<UserRechargeWhiteVO> toBatchVO(List<UserRechargeWhite> userRechargeWhiteList) {
        if (CollectionUtils.isEmpty(userRechargeWhiteList)) {
            return Collections.emptyList();
        }
        //游戏列表
        Map<Long, String> gameMap = this.rechargeWhiteGameMap();
        //玩家列表
        List<Long> userIdList = userRechargeWhiteList.stream().map(UserRechargeWhite::getUserId)
                .distinct().collect(Collectors.toList());
        Map<Long, User> userMap = userService.listByIds(userIdList).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        return userRechargeWhiteList.stream().map(userRechargeWhite -> {
            UserRechargeWhiteVO userRechargeWhiteVO = BeanUtil.copy(userRechargeWhite, UserRechargeWhiteVO.class);
            User user = userMap.get(userRechargeWhiteVO.getUserId());
            userRechargeWhiteVO.setUsername(user.getUsername());
            userRechargeWhiteVO.setMobile(user.getShowPhoneNum());
            userRechargeWhiteVO.setGameName(gameMap.get(userRechargeWhiteVO.getGameId()));
            return userRechargeWhiteVO;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean delRechargeWhite(Long id) {
        return super.removeById(id);
    }
}
