import pygame
import sys

# 初始化窗口
pygame.init()
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("长度单位转换器")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (180, 180, 180)
DARK_GRAY = (100, 100, 100)
BLUE = (30, 130, 220)
GREEN = (20, 170, 70)
RED = (210, 40, 40)
BG_COLOR = (240, 245, 250)

# 字体
font_title = pygame.font.SysFont("simhei", 34)
font_text = pygame.font.SysFont("simhei", 22)
font_btn = pygame.font.SysFont("simhei", 20)

# 长度单位与基准换算（统一转米作为中间值）
unit_info = [
    ("mm 毫米", 0.001),
    ("cm 厘米", 0.01),
    ("m 米", 1.0),
    ("km 千米", 1000.0),
    ("inch 英寸", 0.0254),
    ("ft 英尺", 0.3048),
    ("mi 英里", 1609.344)
]
unit_names = [item[0] for item in unit_info]

# 下拉选择数据
source_idx = 2
target_idx = 0
drop_open = False
drop_type = None  # source / target

# 输入框
input_rect = pygame.Rect(160, 80, 280, 42)
input_text = ""
input_active = False

# 功能按钮
btn_convert = pygame.Rect(150, 240, 130, 46)
btn_clear = pygame.Rect(320, 240, 130, 46)

# 转换结果文本
result_text = "转换结果："

# 绘制文字工具
def draw_text(surface, text, x, y, color=BLACK, font=font_text):
    text_surf = font.render(text, True, color)
    surface.blit(text_surf, (x, y))

# 长度换算核心函数
def convert_length():
    global result_text
    if not input_text:
        result_text = "转换结果：请输入长度数值！"
        return
    try:
        val = float(input_text)
        src_name, src_to_m = unit_info[source_idx]
        dst_name, dst_to_m = unit_info[target_idx]
        # 转为米
        meter = val * src_to_m
        # 转为目标单位
        output = meter / dst_to_m
        short_src = src_name.split(" ")[0]
        short_dst = dst_name.split(" ")[0]
        result_text = f"转换结果：{val:.4f} {short_src} = {output:.4f} {short_dst}"
    except ValueError:
        result_text = "转换结果：输入无效，仅支持数字！"

def main():
    global input_text, input_active, source_idx, target_idx, drop_open, drop_type, result_text
    running = True
    while running:
        screen.fill(BG_COLOR)
        mouse_pos = pygame.mouse.get_pos()

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

            # 鼠标点击
            if event.type == pygame.MOUSEBUTTONDOWN:
                input_active = input_rect.collidepoint(mouse_pos)
                source_box = pygame.Rect(160, 140, 180, 36)
                target_box = pygame.Rect(160, 185, 180, 36)

                # 下拉框展开/关闭
                if source_box.collidepoint(mouse_pos):
                    drop_open = not drop_open
                    drop_type = "source"
                elif target_box.collidepoint(mouse_pos):
                    drop_open = not drop_open
                    drop_type = "target"
                # 选择下拉选项
                elif drop_open:
                    for i in range(len(unit_names)):
                        item_rect = pygame.Rect(160, 140 + (i+1)*36, 180, 36)
                        if item_rect.collidepoint(mouse_pos):
                            if drop_type == "source":
                                source_idx = i
                            else:
                                target_idx = i
                            drop_open = False
                            break
                # 转换按钮
                if btn_convert.collidepoint(mouse_pos):
                    convert_length()
                # 清空按钮
                if btn_clear.collidepoint(mouse_pos):
                    input_text = ""
                    result_text = "转换结果："
                # 空白区域关闭下拉
                if not source_box.collidepoint(mouse_pos) and not target_box.collidepoint(mouse_pos):
                    drop_open = False

            # 键盘输入
            if event.type == pygame.KEYDOWN and input_active:
                if event.key == pygame.K_BACKSPACE:
                    input_text = input_text[:-1]
                elif event.key == pygame.K_RETURN:
                    convert_length()
                else:
                    char = event.unicode
                    # 只允许数字、小数点、负号
                    if char in "0123456789.-":
                        if char == "-" and len(input_text) > 0:
                            continue
                        if char == "." and "." in input_text:
                            continue
                        input_text += char

        # 标题
        draw_text(screen, "长度单位转换器", WIDTH//2 - 150, 15, BLUE, font_title)

        # 输入框绘制
        draw_text(screen, "数值：", 80, 86)
        pygame.draw.rect(screen, WHITE, input_rect)
        pygame.draw.rect(screen, BLUE if input_active else DARK_GRAY, input_rect, 2)
        draw_text(screen, input_text, input_rect.x + 10, input_rect.y + 6)

        # 原单位选择框
        draw_text(screen, "原单位：", 80, 146)
        source_box = pygame.Rect(160, 140, 180, 36)
        pygame.draw.rect(screen, WHITE, source_box)
        pygame.draw.rect(screen, DARK_GRAY, source_box, 2)
        draw_text(screen, unit_names[source_idx], source_box.x + 10, source_box.y + 5)

        # 目标单位选择框
        draw_text(screen, "目标单位：", 80, 191)
        target_box = pygame.Rect(160, 185, 180, 36)
        pygame.draw.rect(screen, WHITE, target_box)
        pygame.draw.rect(screen, DARK_GRAY, target_box, 2)
        draw_text(screen, unit_names[target_idx], target_box.x + 10, target_box.y + 5)

        # 绘制下拉菜单
        if drop_open:
            for i in range(len(unit_names)):
                item_r = pygame.Rect(160, 140 + (i+1)*36, 180, 36)
                pygame.draw.rect(screen, WHITE, item_r)
                pygame.draw.rect(screen, GRAY, item_r, 1)
                draw_text(screen, unit_names[i], item_r.x + 10, item_r.y + 5)

        # 功能按钮
        pygame.draw.rect(screen, BLUE, btn_convert, border_radius=6)
        draw_text(screen, "开始转换", btn_convert.x + 22, btn_convert.y + 8, WHITE, font_btn)

        pygame.draw.rect(screen, RED, btn_clear, border_radius=6)
        draw_text(screen, "清空", btn_clear.x + 48, btn_clear.y + 8, WHITE, font_btn)

        # 结果面板
        res_rect = pygame.Rect(70, 300, 470, 60)
        pygame.draw.rect(screen, WHITE, res_rect)
        pygame.draw.rect(screen, GREEN, res_rect, 2)
        draw_text(screen, result_text, res_rect.x + 12, res_rect.y + 16)

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()