import pygame
import sys

# 初始化
pygame.init()

# 颜色
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
BLUE = (0, 120, 215)
LIGHT_BLUE = (220, 240, 255)
GRAY = (245, 245, 245)
BORDER = (200, 200, 200)

# 屏幕
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("数学公式查询器 (支持鼠标点击)")

# 字体处理
def get_font(size, bold=False):
    # 优先尝试黑体，否则用系统默认
    names = ["simhei", "microsoftyahei", "arialunicode", "stheitismart"]
    for name in names:
        try:
            return pygame.font.SysFont(name, size, bold=bold)
        except:
            continue
    return pygame.font.SysFont("arial", size)

font_text = get_font(22)
font_title = get_font(32, True)
font_formula = pygame.font.SysFont("cambria", 40, italic=True)
font_small = get_font(16)

# 数据库 (增加拼音标签方便搜索)
formula_db = [
    {"name": "勾股定理", "pinyin": "gougu", "formula": "a² + b² = c²", "desc": "直角三角形两直角边平方和等于斜边平方"},
    {"name": "圆面积", "pinyin": "yuan", "formula": "S = πr²", "desc": "圆的半径为 r 时的面积计算公式"},
    {"name": "求根公式", "pinyin": "qiugen", "formula": "x = [-b ± √(Δ)] / 2a", "desc": "一元二次方程 ax² + bx + c = 0 的解"},
    {"name": "完全平方", "pinyin": "wanquan", "formula": "(a+b)² = a²+2ab+b²", "desc": "基础代数展开式"},
    {"name": "正弦定理", "pinyin": "zhengxian", "formula": "a/sinA = b/sinB = 2R", "desc": "三角形边角关系"},
    {"name": "欧拉公式", "pinyin": "oula", "formula": "V - E + F = 2", "desc": "多面体顶点、棱、面数关系"}
]

# 状态
search_text = ""
selected_index = 0
filtered_db = formula_db
list_rects = [] # 存储左侧每个选项的矩形区域，用于点击检测

def update_search():
    global filtered_db, selected_index
    # 同时匹配中文名和拼音
    filtered_db = [f for f in formula_db if search_text.lower() in f['name'] or search_text.lower() in f['pinyin']]
    selected_index = 0

def draw():
    global list_rects
    screen.fill(WHITE)
    list_rects = [] # 清空点击区域

    # --- 左侧列表 (300宽) ---
    pygame.draw.rect(screen, GRAY, (0, 0, 300, HEIGHT))
    
    # 搜索框
    s_box = pygame.Rect(15, 20, 270, 40)
    pygame.draw.rect(screen, WHITE, s_box, border_radius=5)
    pygame.draw.rect(screen, BLUE if search_text else BORDER, s_box, 2, border_radius=5)
    
    search_hint = "输入拼音或名称搜索..." if not search_text else search_text
    search_color = (150, 150, 150) if not search_text else BLACK
    screen.blit(font_small.render(search_hint, True, search_color), (25, 32))

    # 列表项
    for i, item in enumerate(filtered_db):
        item_rect = pygame.Rect(10, 80 + i * 55, 280, 50)
        list_rects.append(item_rect) # 记录位置
        
        if i == selected_index:
            pygame.draw.rect(screen, LIGHT_BLUE, item_rect, border_radius=8)
            pygame.draw.rect(screen, BLUE, item_rect, 2, border_radius=8)
        
        txt = font_text.render(item['name'], True, BLACK)
        screen.blit(txt, (25, 92 + i * 55))

    # --- 右侧详情 ---
    if filtered_db:
        curr = filtered_db[selected_index]
        # 标题
        screen.blit(font_title.render(curr['name'], True, BLUE), (340, 40))
        
        # 公式背景板
        f_box = pygame.Rect(340, 120, 520, 180)
        pygame.draw.rect(screen, GRAY, f_box, border_radius=15)
        
        # 渲染公式 (居中)
        f_surf = font_formula.render(curr['formula'], True, BLACK)
        f_rect = f_surf.get_rect(center=f_box.center)
        screen.blit(f_surf, f_rect)
        
        # 说明
        screen.blit(font_text.render("公式说明：", True, BLACK), (340, 330))
        desc_surf = font_small.render(curr['desc'], True, (80, 80, 80))
        screen.blit(desc_surf, (340, 370))
    else:
        screen.blit(font_text.render("未找到相关公式", True, (150, 150, 150)), (450, 250))

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        # 鼠标点击处理
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos
            for i, rect in enumerate(list_rects):
                if rect.collidepoint(mouse_pos):
                    selected_index = i
        
        # 键盘输入处理
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                search_text = search_text[:-1]
                update_search()
            elif event.key == pygame.K_DOWN:
                selected_index = (selected_index + 1) % len(filtered_db) if filtered_db else 0
            elif event.key == pygame.K_UP:
                selected_index = (selected_index - 1) % len(filtered_db) if filtered_db else 0
            else:
                # 仅接收普通字符输入（英文/数字）
                if event.unicode.isprintable():
                    search_text += event.unicode
                    update_search()

    draw()
    pygame.display.flip()