package com.micer.easyball.expression;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.micer.easyball.mapper.ClubPlayerMapper;
import com.micer.easyball.mapper.PlayerLastClubMapper;
import com.micer.easyball.pojo.ClubPlayer;
import com.micer.easyball.pojo.LoginUser;
import com.micer.easyball.pojo.User;
import com.alibaba.fastjson.JSON;
import com.micer.easyball.pojo.PlayerLastClub;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

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

/**
 * 自定义权限
 */
@Component("ex")
public class MyExpressionRoot {

    @Autowired
    private ClubPlayerMapper clubPlayerMapper;

    @Autowired
    private PlayerLastClubMapper playerLastClubMapper;

    public boolean hasRole(String role) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermisssions();
        String userId = loginUser.getUser().getId();

        // 用户有最高权限
        if (permissions.contains("ROLE_ADMIN"))
        {
            return true;
        }

        // 需要最高权限
        if (role.equals("ROLE_ADMIN"))
        {
            return permissions.contains(role);
        }

        // 获取用户在球队中的权限
        PlayerLastClub playerLastClub = playerLastClubMapper.selectOne(new QueryWrapper<PlayerLastClub>().eq("player_id", userId));
        ClubPlayer clubPlayer = clubPlayerMapper.selectOne(new QueryWrapper<ClubPlayer>().eq("club_id", playerLastClub.getLastClubId()).eq("player_id", userId));

        // 用户可能已经不属于该俱乐部
        if (Objects.isNull(clubPlayer))
        {
            return false;
        }

        // 需要球队管理员权限
        if (role.equals("ROLE_CLUB_ADMIN"))
        {
            return (clubPlayer.getRole().equals("ROLE_CLUB_ADMIN"));
        }

        // 需要球队球员权限
        if (role.equals("ROLE_CLUB_PLAYER"))
        {
            return (clubPlayer.getRole().equals("ROLE_CLUB_ADMIN") || clubPlayer.getRole().equals("ROLE_CLUB_PLAYER"));
        }

        // 其他情况默认拒绝，避免意外放行
        return false;
    }

    /**
     * 检查是否允许切换到目标角色
     */
    public boolean canSwitchToRole(String targetRole) {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();

        // 目标角色必须在用户 role_list 中
        List<String> roleList = JSON.parseArray(user.getRoleList(), String.class);
        if (roleList == null || !roleList.contains(targetRole)) {
            return false;
        }

        // 禁止从非管理员角色直接切换为管理员角色
        String currentRole = user.getCurrentRole();
        if (!"ROLE_ADMIN".equals(currentRole) && "ROLE_ADMIN".equals(targetRole)) {
            return false;
        }

        return true;
    }
}
