import pygame
import sys

# 初始化Pygame
pygame.init()

# 窗口设置
WIDTH, HEIGHT = 500, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("重量单位转换器")

# 颜色定义
WHITE = (255, 255, 255)
BLUE = (50, 150, 255)
GRAY = (200, 200, 200)
BLACK = (0, 0, 0)
RED = (255, 80, 80)

# 字体
font = pygame.font.SysFont("simhei", 24)  # 黑体
big_font = pygame.font.SysFont("simhei", 32)

# 单位列表（支持转换的重量单位）
units = ["千克(kg)", "克(g)", "斤", "磅(lb)"]

# 单位换算系数（以 千克 为基准）
unit_rates = {
    "千克(kg)": 1,
    "克(g)": 1000,
    "斤": 2,
    "磅(lb)": 2.20462
}

# 输入框、下拉菜单变量
input_text = ""
input_active = False
from_unit = 0  # 默认从千克转换
to_unit = 1    # 默认转换到克
from_open = False
to_open = False
result_text = ""

# 输入框区域
input_rect = pygame.Rect(100, 100, 300, 50)
# 两个下拉菜单区域
from_rect = pygame.Rect(100, 180, 140, 50)
to_rect = pygame.Rect(260, 180, 140, 50)

# 主循环
clock = pygame.time.Clock()
running = True

def convert_weight(value, from_u, to_u):
    """重量换算核心函数"""
    try:
        # 先转成千克，再转目标单位
        kg = value / unit_rates[units[from_u]]
        result = kg * unit_rates[units[to_u]]
        return round(result, 4)  # 保留4位小数
    except:
        return "输入错误"

while running:
    screen.fill(WHITE)
    # 绘制标题
    title = big_font.render("重量单位转换器", True, BLUE)
    screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 鼠标点击
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 输入框点击
            if input_rect.collidepoint(event.pos):
                input_active = True
            else:
                input_active = False

            # 来源单位下拉框
            if from_rect.collidepoint(event.pos):
                from_open = not from_open
                to_open = False
            else:
                # 点击选项
                if from_open:
                    for i in range(len(units)):
                        opt_rect = pygame.Rect(from_rect.x, from_rect.y + 50*(i+1), 140, 40)
                        if opt_rect.collidepoint(event.pos):
                            from_unit = i
                            from_open = False

            # 目标单位下拉框
            if to_rect.collidepoint(event.pos):
                to_open = not to_open
                from_open = False
            else:
                if to_open:
                    for i in range(len(units)):
                        opt_rect = pygame.Rect(to_rect.x, to_rect.y + 50*(i+1), 140, 40)
                        if opt_rect.collidepoint(event.pos):
                            to_unit = i
                            to_open = False

        # 键盘输入
        if event.type == pygame.KEYDOWN and input_active:
            if event.key == pygame.K_RETURN:
                # 按下回车开始转换
                try:
                    val = float(input_text)
                    res = convert_weight(val, from_unit, to_unit)
                    result_text = f"{val} {units[from_unit]} = {res} {units[to_unit]}"
                except:
                    result_text = "请输入有效数字"
            elif event.key == pygame.K_BACKSPACE:
                input_text = input_text[:-1]
            else:
                # 只允许数字和小数点
                if event.unicode in "0123456789.":
                    input_text += event.unicode

    # —————— 绘制输入框 ——————
    pygame.draw.rect(screen, BLUE if input_active else GRAY, input_rect, 2, border_radius=8)
    input_surf = font.render(input_text if input_text else "请输入数值", True, BLACK)
    screen.blit(input_surf, (input_rect.x + 10, input_rect.y + 12))

    # —————— 绘制来源单位下拉框 ——————
    pygame.draw.rect(screen, BLUE, from_rect, 2, border_radius=8)
    from_surf = font.render(units[from_unit], True, BLACK)
    screen.blit(from_surf, (from_rect.x + 10, from_rect.y + 12))
    # 展开选项
    if from_open:
        for i in range(len(units)):
            opt_rect = pygame.Rect(from_rect.x, from_rect.y + 50*(i+1), 140, 40)
            pygame.draw.rect(screen, GRAY, opt_rect)
            pygame.draw.rect(screen, BLUE, opt_rect, 1)
            opt_surf = font.render(units[i], True, BLACK)
            screen.blit(opt_surf, (opt_rect.x + 10, opt_rect.y + 8))

    # —————— 绘制目标单位下拉框 ——————
    pygame.draw.rect(screen, BLUE, to_rect, 2, border_radius=8)
    to_surf = font.render(units[to_unit], True, BLACK)
    screen.blit(to_surf, (to_rect.x + 10, to_rect.y + 12))
    if to_open:
        for i in range(len(units)):
            opt_rect = pygame.Rect(to_rect.x, to_rect.y + 50*(i+1), 140, 40)
            pygame.draw.rect(screen, GRAY, opt_rect)
            pygame.draw.rect(screen, BLUE, opt_rect, 1)
            opt_surf = font.render(units[i], True, BLACK)
            screen.blit(opt_surf, (opt_rect.x + 10, opt_rect.y + 8))

    # —————— 绘制结果 ——————
    result_surf = font.render(result_text, True, RED if "错误" in result_text else BLUE)
    screen.blit(result_surf, (50, 280))

    # 提示文字
    tip = font.render("按【回车】开始转换", True, GRAY)
    screen.blit(tip, (WIDTH//2 - tip.get_width()//2, 340))

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

pygame.quit()
sys.exit()