from PIL import Image, ImageDraw, ImageFont
import math
import os
from io import BytesIO
import io
import textwrap
import cv2
import time
import datetime
import numpy as np
from .img_utils import *
from .data_utils import *
from .param import *

filepath = os.path.dirname(__file__).replace("\\", "/")

# 字体
font_XXL = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 72)
font_XL = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 64)
font_L = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 48)
font_M = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 36)
font_MS = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 32)
font_S = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 28)
font_XS = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 24)
font_XXS = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 18)
font_XXXS = ImageFont.truetype(f"{filepath}/font/演示创黑FLY.ttf", 16)


async def build_stats_card(game="bfv", player="Player001", pid=1145141919, kd=1.25, kpm=2.3, spm=500, acc=25.6,
                           head_shots=10, rank=100, time_play=100, kills=100, kill_assists=150, revives=114, wins=10,
                           loses=10, destroyed=514, best_weapon="M1907 SF", best_vehicle="坦克", best_class="Support",
                           longest_head_shot=1200, highest_ill_streak=100, stat_data=None, level_designation=None):
    if stat_data is None:
        stat_data = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

    # 获取当前事件并且格式化
    now = datetime.datetime.now()
    formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")

    # ---------------- OpenCV 部分 ----------------
    # 载入模板
    img = cv2.imread(f"{filepath}/template/{game}.png", cv2.IMREAD_COLOR)

    # 载入头像并缩放
    avatar = cv2.imread(f"{filepath}/avatar_cache/0.png", cv2.IMREAD_UNCHANGED)
    avatar = cv2.resize(avatar, (200, 200), interpolation=cv2.INTER_AREA)

    # 创建圆形蒙版
    mask = np.zeros((200, 200), dtype=np.uint8)
    cv2.circle(mask, (100, 100), 100, 255, -1)  # 绘制半径100的实心圆

    # 处理透明通道
    if avatar.shape[2] == 4:
        # 合并圆形蒙版与原有alpha通道
        alpha = cv2.bitwise_and(avatar[:, :, 3], mask)
        avatar[:, :, 3] = alpha
    else:
        # 无透明通道时创建BGRA图像
        avatar = cv2.cvtColor(avatar, cv2.COLOR_BGR2BGRA)
        avatar[:, :, 3] = mask

    # 粘贴头像（保持原有坐标）
    y, x = 55, 426
    h, w = avatar.shape[:2]
    alpha = avatar[:, :, 3] / 255.0
    for c in range(3):
        img[y:y + h, x:x + w, c] = (alpha * avatar[:, :, c] +
                                    (1 - alpha) * img[y:y + h, x:x + w, c])

    # 公告栏
    img = notice_paste(img)

    # ---------------- PIL 部分 ----------------
    pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(pil_img)

    # 玩家信息
    draw.text((665, 65), f"{player}", fill="white", font=font_L)
    draw.text((745, 133), f"{pid}", fill="white", font=font_M)

    # 等级游玩时长
    draw.text((740, 212), f"{rank}", fill="white", font=font_M)
    draw.text((985, 212), f"{time_play}H", fill="white", font=font_M)
    # draw_centered_text(draw=draw, text=rank, x_left=730, x_right=905, y=210, font=font_M, fill="white", )
    # draw_centered_text(draw=draw, text=f"{time_play}H", x_left=965, x_right=1120, y=210, font=font_M, fill="white", )
    # draw.text((730, 195), f"{rank}", fill="white", font=font_M)
    # draw.text((1000, 195), f"{time_play}", fill="white", font=font_M)

    # 生涯总览

    # 场次
    draw_centered_text(draw=draw, text=(wins + loses), x_left=45, x_right=265, y=350,
                       font=font_L,
                       fill="white")

    # 命中率
    draw_centered_text(draw=draw, text=round(float(acc.replace("%", "")), 1), x_left=415, x_right=495, y=343,
                       font=font_M,
                       fill="white")
    # 爆头率
    if head_shots:
        head_shots = head_shots.replace("%", "")
    else:
        head_shots = 0
    draw_centered_text(draw=draw, text=round(float(head_shots), 1), x_left=395, x_right=470, y=420, font=font_M,
                       fill="white")
    # kd
    draw_centered_text(draw=draw, text=kd, x_left=585, x_right=785, y=340, font=font_XL, fill="white")
    # kpm
    draw_centered_text(draw=draw, text=round(kpm, 1), x_left=825, x_right=1025, y=340, font=font_XL, fill="white")
    # spm
    draw_centered_text(draw=draw, text=round(spm, 1), x_left=1065, x_right=1265, y=340, font=font_XL, fill="white")

    # 击杀
    draw_centered_text(draw=draw, text=kills, x_left=870, x_right=1190, y=595, font=font_L, fill="white")

    # 助攻
    draw_centered_text(draw=draw, text=kill_assists, x_left=820, x_right=1145, y=770, font=font_L, fill="white")

    # 急救
    draw_centered_text(draw=draw, text=revives, x_left=770, x_right=1090, y=960, font=font_L, fill="white")

    # 摧毁
    draw_centered_text(draw=draw, text=destroyed, x_left=720, x_right=1040, y=1140, font=font_L, fill="white")

    # 底部栏

    # 评级
    level = level_designation['level']
    des = level_designation['designation']
    color = level_designation['color']
    draw_centered_text(draw=draw, text=level, x_left=70, x_right=200, y=1120, font=font_XL, fill=color)
    draw_centered_text(draw=draw, text=des, x_left=200, x_right=550, y=1120, font=font_XL, fill="white")

    # 最佳兵种

    draw_centered_text(draw=draw, text=classes[best_class], x_left=140, x_right=310, y=1290, font=font_L, fill="white")

    # 最远击杀
    draw_centered_text(draw=draw, text=f"{longest_head_shot}m", x_left=455, x_right=625, y=1290, font=font_L,
                       fill="white")

    # 最高连杀
    draw_centered_text(draw=draw, text=highest_ill_streak, x_left=765, x_right=935, y=1290, font=font_L, fill="white")

    # 最佳⭐
    pil_img = build_best(draw, pil_img, best_weapon, best_vehicle, game)

    # 生成时间
    draw.text((1870, 1420), f"{formatted_time}", fill=(154, 132, 149), font=font_XXXS)

    # ---------------- 转回 OpenCV ----------------
    img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)

    # ---------------- 雷达图 ----------------
    center = (311, 796)
    r = 185
    scale_min = 0.25 if min(stat_data) < 0.25 else min(stat_data)
    img = draw_radar(img, stat_data, center=center, r=r,
                     buffer=0.1, scale_min=scale_min, scale_max=1.10)
    # 保存
    success, buffer = cv2.imencode(".png", img)
    if success:
        b_io = io.BytesIO(buffer)
        return b_io  # 就可以直接 return 二进制流
    else:
        return None


def build_best(draw: ImageDraw, img: Image, weapons, vehicle, game: str):
    # 最佳武器
    weapon_name = weapons["weaponName"]
    w_kills = weapons["kills"]
    w_kpm = weapons["killsPerMinute"]
    acc = weapons["accuracy"].replace("%", "")
    headshots = weapons["headshots"].replace("%", "")

    # 最佳载具
    vehicle_name = vehicle["vehicleName"]
    v_kills = vehicle["kills"]
    v_kpm = vehicle["killsPerMinute"]
    destroyed = vehicle["destroyed"]

    # 绘制最佳⭐
    # 武器
    draw_centered_text(draw=draw, text=bf_item[game][weapon_name].upper(), x_left=1240, x_right=1750, y=1355,
                       font=font_MS, fill="white")
    draw_centered_text(draw=draw, text=w_kills, x_left=1190, x_right=1390, y=1260, font=font_L, fill="white")
    draw_centered_text(draw=draw, text=w_kpm, x_left=1510, x_right=1635, y=1260, font=font_L, fill="white")
    draw_centered_text(draw=draw, text=acc, x_left=1735, x_right=1803, y=1030, font=font_M, fill="white")
    draw_centered_text(draw=draw, text=headshots, x_left=1695, x_right=1760, y=1200, font=font_M, fill="white")

    # 载具
    draw_centered_text(draw=draw, text=bf_item[game][vehicle_name].upper(), x_left=1990, x_right=2440, y=1355,
                       font=font_MS, fill="white")
    draw_centered_text(draw=draw, text=v_kills, x_left=1940, x_right=2150, y=1260, font=font_L, fill="white")
    draw_centered_text(draw=draw, text=v_kpm, x_left=2295, x_right=2465, y=1055, font=font_XL, fill="white")
    draw_centered_text(draw=draw, text=destroyed, x_left=2265, x_right=2440, y=1260, font=font_L, fill="white")

    # 图片
    weapon_url = weapons["image"]
    vehicle_url = vehicle["image"]
    wp_icon = get_save_icon(game, weapon_name, "weapon", weapon_url)
    vc_icon = get_save_icon(game, vehicle_name, "vehicles", vehicle_url)

    img = image_paste_center(wp_icon, img, (1165, 1110))
    img = image_paste_center(vc_icon, img, (1920, 1110))
    return img


def normalize_for_radar(data, buffer=0.1, scale_min=0.0, scale_max=1.0):
    """
    将数据动态归一化到指定区间 [scale_min, scale_max]，
    并给最大值预留 buffer，让图形更饱满。

    Args:
        data (list/ndarray): 原始数据
        buffer (float): 缓冲比例，例如 0.1 表示最大值按 1.1 倍处理
        scale_min (float): 映射区间下限
        scale_max (float): 映射区间上限

    Returns:
        list: 归一化后的数据
    """
    data = np.array(data, dtype=float)
    d_min, d_max = data.min(), data.max()

    # 给最大值留 buffer
    d_max = d_max * (1 + buffer)

    if d_max == d_min:  # 避免除零
        norm = np.ones_like(data) * (scale_min + scale_max) / 2
    else:
        norm = (data - d_min) / (d_max - d_min)
        norm = scale_min + norm * (scale_max - scale_min)

    return norm.tolist()


# ---------------- 雷达图示例 ----------------
def draw_radar(img, stat_data, center=(311, 796), r=185,
               buffer=0.1, scale_min=0.1, scale_max=1.05):
    # 动态归一化
    scaled_data = normalize_for_radar(stat_data, buffer, scale_min, scale_max)

    points = []
    for i, v in enumerate(scaled_data):
        angle = 2 * np.pi / len(scaled_data) * i - np.pi / 2
        px = int(center[0] + r * v * np.cos(angle))
        py = int(center[1] + r * v * np.sin(angle))
        points.append([px, py])
    points = np.array(points, np.int32)

    # 绘制填充
    overlay = img.copy()
    cv2.fillPoly(overlay, [points], color=(255, 255, 255, 76))
    img = cv2.addWeighted(overlay, 0.3, img, 0.7, 0)
    # 绘制边框
    cv2.polylines(img, [points], isClosed=True, color=(255, 255, 255), thickness=2)
    return img


def build_bf6_simple_card(player_info):
    # 1.创建黑色板块 1920*1080
    new_img = Image.new('RGBA', (1080, 1920), (255, 255, 255, 1000))

    draw = ImageDraw.Draw(new_img)

    draw.text((50, 60), f"玩家名称：{player_info['玩家名称']}", fill='black', font=font_M)
    draw.text((550, 60), f"游玩平台：{player_info['游玩平台']}", fill='black', font=font_M)

    draw.text((50, 160), f"游戏等级：{player_info['游戏等级']}", fill='black', font=font_M)
    draw.text((550, 160), f"游玩时长：{player_info['游玩时长']}", fill='black', font=font_M)

    draw.text((50, 260), f"游玩场次：{player_info['游玩场次']}", fill='black', font=font_M)
    draw.text((550, 260), f"对局胜率：{player_info['对局胜率']}", fill='black', font=font_M)

    draw.text((50, 360), f"对局得分：{player_info['对局得分']}", fill='black', font=font_M)
    draw.text((550, 360), f"玩家SPM：{player_info['玩家SPM']}", fill='black', font=font_M)

    draw.text((50, 460), f"玩家K/D：{player_info['玩家K/D']}", fill='black', font=font_M)
    draw.text((550, 460), f"玩家KPM：{player_info['玩家KPM']}", fill='black', font=font_M)

    draw.text((50, 560), f"击杀总计：{player_info['击杀总计']}", fill='black', font=font_M)
    draw.text((550, 560), f"真人击杀：{player_info['真人击杀']}", fill='black', font=font_M)

    draw.text((50,660), f"游戏助攻：{player_info['游戏助攻']}", fill='black', font=font_M)
    draw.text((550, 660), f"目标占领：{player_info['目标占领']}", fill='black', font=font_M)

    draw.text((50, 760), f"救援数量：{player_info['救援数量']}", fill='black', font=font_M)
    draw.text((550, 760), f"最高连杀：{player_info['最高连杀']}", fill='black', font=font_M)

    draw.text((50, 860), f"命中率：{player_info['命中率']}", fill='black', font=font_M)
    draw.text((550, 860), f"爆头率：{player_info['爆头率']}", fill='black', font=font_M)

    draw.text((150, 1060), f"最佳武器", fill='black', font=font_M)
    draw.text((650, 1060), f"最佳载具", fill='black', font=font_M)

    draw.text((50, 1160), f"名称：{player_info['最佳武器']['名称']}", fill='black', font=font_M)
    draw.text((50, 1260), f"击杀：{player_info['最佳武器']['击杀']}", fill='black', font=font_M)
    draw.text((50, 1360), f"KPM：{player_info['最佳武器']['KPM']}", fill='black', font=font_M)
    draw.text((50, 1460), f"时长：{player_info['最佳武器']['时长']}", fill='black', font=font_M)
    draw.text((50, 1560), f"命中率：{player_info['最佳武器']['命中率']}", fill='black', font=font_M)
    draw.text((50, 1660), f"爆头率：{player_info['最佳武器']['爆头率']}", fill='black', font=font_M)

    draw.text((550, 1160), f"名称：{player_info['最佳载具']['名称']}", fill='black', font=font_M)
    draw.text((550, 1260), f"击杀：{player_info['最佳载具']['击杀']}", fill='black', font=font_M)
    draw.text((550, 1360), f"KPM：{player_info['最佳载具']['KPM']}", fill='black', font=font_M)
    draw.text((550, 1460), f"时长：{player_info['最佳载具']['时长']}", fill='black', font=font_M)
    draw.text((550, 1560), f"碾压：{player_info['最佳载具']['碾压']}", fill='black', font=font_M)
    draw.text((550, 1660), f"摧毁：{player_info['最佳载具']['摧毁']}", fill='black', font=font_M)

    b_io = BytesIO()
    new_img.save(b_io, format="PNG")
    return b_io  # 就可以直接 return 二进制流


def build_bf6_weapon_card(weapon_info):
    # 1.创建黑色板块 1920*1080
    new_img = Image.new('RGBA', (1080, 1920), (255, 255, 255, 1000))
