import pygame
import sys
from PIL import Image
import os

pygame.init()
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("学生证件生成器")

# 颜色
WHITE = (255, 255, 255)
BLUE = (20, 60, 160)
LIGHT_BLUE = (220, 235, 255)
BLACK = (0, 0, 0)
GRAY = (150, 150, 150)
RED = (180, 30, 30)

# ========== 核心：解决中文方块乱码 ==========
def get_cn_font(size):
    # Windows系统自带宋体路径，百分百存在
    font_path = r"C:\Windows\Fonts\simsun.ttc"
    try:
        return pygame.font.Font(font_path, size)
    except:
        # 备用微软雅黑
        try:
            return pygame.font.Font(r"C:\Windows\Fonts\msyh.ttc", size)
        except:
            # 兜底系统字体
            for name in ["msyh", "simhei", "simsun"]:
                try:
                    return pygame.font.SysFont(name, size)
                except:
                    continue
            # 最后兜底无中文字体
            return pygame.font.Font(None, size)

font_big = get_cn_font(32)
font_mid = get_cn_font(24)
font_small = get_cn_font(18)
# ==========================================

# 输入框
input_texts = ["", "", "", ""]
input_labels = ["姓名：", "班级：", "学号：", "性别："]
active_box = 0
box_rects = [pygame.Rect(180, 120 + i*45, 220, 32) for i in range(4)]

# 按钮
generate_btn = pygame.Rect(200, 320, 180, 45)
save_btn = pygame.Rect(400, 320, 150, 45)
card_surface = None

def draw_student_card(name, cls, sid, gender):
    card_w, card_h = 480, 300
    card = pygame.Surface((card_w, card_h))
    card.fill(LIGHT_BLUE)
    pygame.draw.rect(card, BLUE, (0,0,card_w,card_h), 4)

    title = font_big.render("学生证件", True, BLUE)
    card.blit(title, (card_w//2 - title.get_width()//2, 20))

    # 照片框
    photo_rect = pygame.Rect(30, 70, 110, 140)
    pygame.draw.rect(card, BLACK, photo_rect, 2)
    tip = font_small.render("一寸照片", True, GRAY)
    card.blit(tip, (photo_rect.centerx - tip.get_width()//2, photo_rect.centery))

    # 信息
    info_y = 75
    line_gap = 38
    info_list = [
        f"姓  名：{name}",
        f"班  级：{cls}",
        f"学  号：{sid}",
        f"性  别：{gender}"
    ]
    for text in info_list:
        txt = font_mid.render(text, True, BLACK)
        card.blit(txt, (170, info_y))
        info_y += line_gap

    school_txt = font_small.render("XX市实验中学", True, RED)
    card.blit(school_txt, (card_w//2 - school_txt.get_width()//2, 235))
    valid_txt = font_small.render("有效期：在校期间", True, GRAY)
    card.blit(valid_txt, (card_w//2 - valid_txt.get_width()//2, 260))
    return card

def save_card(image_surface):
    buf = pygame.image.tostring(image_surface, "RGB")
    img = Image.frombytes("RGB", image_surface.get_size(), buf)
    save_path = "学生证件.png"
    img.save(save_path)
    print(f"证件已保存至：{os.path.abspath(save_path)}")

clock = pygame.time.Clock()
running = True

while running:
    screen.fill(WHITE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            # 切换输入框
            for i, rect in enumerate(box_rects):
                if rect.collidepoint(event.pos):
                    active_box = i
                    break
            # 生成证件
            if generate_btn.collidepoint(event.pos):
                if all(t.strip() != "" for t in input_texts):
                    card_surface = draw_student_card(*input_texts)
            # 保存图片
            if save_btn.collidepoint(event.pos) and card_surface is not None:
                save_card(card_surface)

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                input_texts[active_box] = input_texts[active_box][:-1]
            elif event.key == pygame.K_RETURN:
                active_box = (active_box + 1) % 4
            else:
                if len(input_texts[active_box]) < 16:
                    input_texts[active_box] += event.unicode

    # 绘制输入区域
    for i in range(4):
        label = font_mid.render(input_labels[i], True, BLACK)
        screen.blit(label, (80, 122 + i*45))

        box_color = (240,248,255) if i == active_box else WHITE
        pygame.draw.rect(screen, box_color, box_rects[i])
        pygame.draw.rect(screen, BLACK, box_rects[i], 2)

        text_surf = font_mid.render(input_texts[i], True, BLACK)
        screen.blit(text_surf, (box_rects[i].x + 8, box_rects[i].y + 4))

    # 生成按钮
    pygame.draw.rect(screen, BLUE, generate_btn)
    gen_txt = font_mid.render("生成证件", True, WHITE)
    screen.blit(gen_txt, (generate_btn.centerx - gen_txt.get_width()//2, generate_btn.y + 8))

    # 保存按钮
    pygame.draw.rect(screen, RED, save_btn)
    save_txt = font_mid.render("保存图片", True, WHITE)
    screen.blit(save_txt, (save_btn.centerx - save_txt.get_width()//2, save_btn.y + 8))

    # 证件预览
    if card_surface is not None:
        preview = pygame.transform.scale(card_surface, (360, 225))
        screen.blit(preview, (10, 10))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()