package com.micer.easyball.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.micer.easyball.mapper.ClubMapper;
import com.micer.easyball.mapper.ClubPlayerMapper;
import com.micer.easyball.mapper.PlayerLastClubMapper;
import com.micer.easyball.mapper.UserMapper;
import com.micer.easyball.pojo.*;
import com.micer.easyball.pojo.Dto.ClubPlayerDto;
import com.micer.easyball.service.ClubService;
import com.micer.easyball.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.net.InetAddress;
import java.net.URI;

@Service
public class ClubServiceImpl implements ClubService {
    @Autowired
    ClubMapper clubMapper;

    @Autowired
    PlayerLastClubMapper playerLastClubMapper;

    @Autowired
    ClubPlayerMapper clubPlayerMapper;

    @Autowired
    UserMapper userMapper;

    // 在类头部注入 RestTemplate
    @Autowired
    private RestTemplate restTemplate;

    @Override
    @Transactional
    public ResponseResult addClub(Club club) {
        club.setCreateAt(new Date(System.currentTimeMillis()));
        if (clubMapper.exists(new QueryWrapper<Club>().eq("name", club.getName()).eq("city", club.getCity())))
        {
            return new ResponseResult(430, "俱乐部已存在");
        }

        club.setId(JwtUtil.getUUID());

        clubMapper.insert(club);
        return new ResponseResult(200, "成功添加俱乐部");
    }

    @Override
    public ResponseResult getPlayers() {
        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId();
        List<String> permissions = loginUser.getPermisssions();

        // 获取当前俱乐部ID
        PlayerLastClub playerLastClub = playerLastClubMapper.selectOne(new QueryWrapper<PlayerLastClub>().eq("player_id", userId));
        String clubId = playerLastClub.getLastClubId();

        // 获取俱乐部中所有球员
        List<ClubPlayer> clubPlayerList = clubPlayerMapper.selectList(new QueryWrapper<ClubPlayer>().eq("club_id", clubId));
        // 判断当前用户是否有权查看手机号
        ClubPlayer currentClubPlayer = clubPlayerMapper.selectOne(new QueryWrapper<ClubPlayer>().eq("club_id", clubId).eq("player_id", userId));
        boolean canViewTelephone = (permissions != null && permissions.contains("ROLE_ADMIN"))
                || (currentClubPlayer != null && "ROLE_CLUB_ADMIN".equals(currentClubPlayer.getRole()));

        List<ClubPlayerDto> clubPlayerDtoList = new ArrayList<>();
        for (ClubPlayer clubPlayer: clubPlayerList)
        {
            ClubPlayerDto clubPlayerDto = new ClubPlayerDto(clubPlayer);
            User player = userMapper.selectById(clubPlayer.getPlayerId());
            clubPlayerDto.setPlayerName(player.getUsername());
            // 仅管理员或俱乐部管理员可见手机号，其他用户置空或脱敏
            if (canViewTelephone) {
                clubPlayerDto.setTelephone(player.getTelephone());
            } else {
                clubPlayerDto.setTelephone(null);
            }
            clubPlayerDtoList.add(clubPlayerDto);
        }

        return new ResponseResult(200, "成功", clubPlayerDtoList);
    }

    // 添加测试 Webhook 的方法
    @Override
    public ResponseResult testWebhook(String webhookUrl) {
        try {
            URI uri = new URI(webhookUrl);

            // 1. 协议白名单校验：仅允许 http/https
            String scheme = uri.getScheme();
            if (scheme == null || (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme))) {
                return new ResponseResult(403, "Webhook 配置失败：仅支持 HTTP/HTTPS 协议");
            }

            // 2. DNS 解析并进行内网/环回地址阻断（检查所有解析到的地址）
            String host = uri.getHost();
            if (host == null || host.isEmpty()) {
                return new ResponseResult(403, "Webhook 配置失败：URL 主机为空");
            }

            InetAddress[] inetAddresses = InetAddress.getAllByName(host);
            for (InetAddress inetAddress : inetAddresses) {
                if (inetAddress.isLoopbackAddress()
                        || inetAddress.isSiteLocalAddress()
                        || inetAddress.isAnyLocalAddress()
                        || inetAddress.isLinkLocalAddress()
                        || inetAddress.isMulticastAddress()) {
                    return new ResponseResult(403, "Webhook 配置失败：禁止访问内网或本地保留地址！");
                }
            }

            // 3. 校验通过，发起请求（RestTemplate 全局拦截器将再次校验）
            String response = restTemplate.getForObject(uri, String.class);
            return new ResponseResult(200, "Webhook 测试连通性成功，响应内容：", response);
        } catch (Exception e) {
            return new ResponseResult(500, "Webhook 测试失败或 URL 格式非法：" + e.getMessage());
        }
    }
}
