import pygame
import sys
import os
from datetime import datetime

# 初始化pygame
pygame.init()

# 设置窗口大小
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("学生证件生成器")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (30, 60, 150)
LIGHT_BLUE = (200, 220, 255)
GRAY = (240, 240, 240)
RED = (220, 20, 60)

# 字体
try:
    title_font = pygame.font.SysFont('microsoftyahei', 36, bold=True)
    header_font = pygame.font.SysFont('microsoftyahei', 28, bold=True)
    text_font = pygame.font.SysFont('microsoftyahei', 24)
    small_font = pygame.font.SysFont('microsoftyahei', 20)
except:
    # 如果找不到中文字体，使用默认字体
    title_font = pygame.font.Font(None, 36)
    header_font = pygame.font.Font(None, 28)
    text_font = pygame.font.Font(None, 24)
    small_font = pygame.font.Font(None, 20)

class StudentCard:
    def __init__(self):
        self.name = "张三"
        self.student_id = "20230001"
        self.college = "计算机科学与技术学院"
        self.major = "软件工程"
        self.grade = "2023级"
        self.valid_date = "2023.09 - 2027.06"
        self.photo_path = None
        
    def set_info(self, name, student_id, college, major, grade, valid_date):
        self.name = name
        self.student_id = student_id
        self.college = college
        self.major = major
        self.grade = grade
        self.valid_date = valid_date
    
    def set_photo(self, path):
        self.photo_path = path
    
    def draw(self, surface, x, y, width, height):
        # 绘制证件背景
        pygame.draw.rect(surface, WHITE, (x, y, width, height))
        pygame.draw.rect(surface, BLUE, (x, y, width, height), 4)
        
        # 绘制顶部标题栏
        title_rect = pygame.Rect(x, y, width, 60)
        pygame.draw.rect(surface, BLUE, title_rect)
        
        title_text = title_font.render("学 生 证", True, WHITE)
        title_pos = title_text.get_rect(center=title_rect.center)
        surface.blit(title_text, title_pos)
        
        # 绘制学校名称
        school_text = header_font.render("XX大学", True, BLUE)
        school_rect = school_text.get_rect(center=(x + width//2, y + 100))
        surface.blit(school_text, school_rect)
        
        # 绘制照片区域
        photo_rect = pygame.Rect(x + 50, y + 150, 150, 200)
        pygame.draw.rect(surface, LIGHT_BLUE, photo_rect)
        pygame.draw.rect(surface, BLACK, photo_rect, 2)
        
        # 如果有照片，加载并显示
        if self.photo_path and os.path.exists(self.photo_path):
            try:
                photo = pygame.image.load(self.photo_path)
                photo = pygame.transform.scale(photo, (146, 196))
                surface.blit(photo, (x + 52, y + 152))
            except:
                # 如果加载失败，显示"照片"文字
                no_photo = text_font.render("照 片", True, BLUE)
                no_photo_rect = no_photo.get_rect(center=photo_rect.center)
                surface.blit(no_photo, no_photo_rect)
        else:
            no_photo = text_font.render("照 片", True, BLUE)
            no_photo_rect = no_photo.get_rect(center=photo_rect.center)
            surface.blit(no_photo, no_photo_rect)
        
        # 绘制学生信息
        info_start_y = y + 150
        info_start_x = x + 230
        
        # 姓名
        name_label = text_font.render("姓 名：", True, BLACK)
        surface.blit(name_label, (info_start_x, info_start_y))
        name_value = text_font.render(self.name, True, BLACK)
        surface.blit(name_value, (info_start_x + 100, info_start_y))
        
        # 学号
        id_label = text_font.render("学 号：", True, BLACK)
        surface.blit(id_label, (info_start_x, info_start_y + 50))
        id_value = text_font.render(self.student_id, True, BLACK)
        surface.blit(id_value, (info_start_x + 100, info_start_y + 50))
        
        # 学院
        college_label = text_font.render("学 院：", True, BLACK)
        surface.blit(college_label, (info_start_x, info_start_y + 100))
        college_value = text_font.render(self.college, True, BLACK)
        surface.blit(college_value, (info_start_x + 100, info_start_y + 100))
        
        # 专业
        major_label = text_font.render("专 业：", True, BLACK)
        surface.blit(major_label, (info_start_x, info_start_y + 150))
        major_value = text_font.render(self.major, True, BLACK)
        surface.blit(major_value, (info_start_x + 100, info_start_y + 150))
        
        # 年级
        grade_label = text_font.render("年 级：", True, BLACK)
        surface.blit(grade_label, (info_start_x, info_start_y + 200))
        grade_value = text_font.render(self.grade, True, BLACK)
        surface.blit(grade_value, (info_start_x + 100, info_start_y + 200))
        
        # 有效期
        valid_label = small_font.render("有效期：", True, RED)
        surface.blit(valid_label, (x + 50, y + height - 50))
        valid_value = small_font.render(self.valid_date, True, RED)
        surface.blit(valid_value, (x + 130, y + height - 50))
        
        # 底部印章
        stamp_text = small_font.render("XX大学教务处", True, RED)
        stamp_rect = stamp_text.get_rect(bottomright=(x + width - 20, y + height - 20))
        surface.blit(stamp_text, stamp_rect)
        
        # 当前时间戳
        timestamp = small_font.render(f"生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", True, GRAY)
        timestamp_rect = timestamp.get_rect(bottomleft=(x + 10, y + height - 5))
        surface.blit(timestamp, timestamp_rect)

def save_card_as_image(card, filename="student_card.png"):
    """将证件保存为图片"""
    save_surface = pygame.Surface((600, 400))
    save_surface.fill(WHITE)
    card.draw(save_surface, 0, 0, 600, 400)
    pygame.image.save(save_surface, filename)
    print(f"证件已保存为 {filename}")

def main():
    # 创建学生证件实例
    student_card = StudentCard()
    
    # 设置示例信息
    student_card.set_info(
        name="李小明",
        student_id="2023123456",
        college="信息科学与工程学院",
        major="人工智能",
        grade="2023级",
        valid_date="2023.09 - 2027.06"
    )
    
    # 尝试加载示例照片（如果有的话）
    # student_card.set_photo("student_photo.jpg")
    
    clock = pygame.time.Clock()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_s:
                    # 按S键保存证件
                    save_card_as_image(student_card)
                elif event.key == pygame.K_ESCAPE:
                    running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 这里可以添加点击交互功能
                pass
        
        # 清屏
        screen.fill(GRAY)
        
        # 绘制背景网格
        for i in range(0, WIDTH, 20):
            pygame.draw.line(screen, (220, 220, 220), (i, 0), (i, HEIGHT))
        for i in range(0, HEIGHT, 20):
            pygame.draw.line(screen, (220, 220, 220), (0, i), (WIDTH, i))
        
        # 绘制学生证件
        student_card.draw(screen, 100, 50, 600, 400)
        
        # 绘制操作提示
        tips = [
            "学生证件生成器",
            "按 S 键：保存为图片",
            "按 ESC 键：退出程序"
        ]
        
        for i, tip in enumerate(tips):
            tip_text = small_font.render(tip, True, BLUE)
            screen.blit(tip_text, (WIDTH - 250, 20 + i * 30))
        
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()