import pygame
import requests
import hashlib
import random
import pyperclip

# ============ 百度翻译配置（请替换成自己的）============
APP_ID = "你的APPID"
APP_KEY = "你的密钥"
# ======================================================

# 语言配置 名称：百度翻译代码
LANG_MAP = {
    "中文": "zh",
    "英语": "en",
    "日语": "jp",
    "韩语": "kor",
    "法语": "fra",
    "德语": "de",
    "西班牙语": "spa"
}
LANG_LIST = list(LANG_MAP.keys())

# 百度翻译接口
def baidu_translate(query, from_lang, to_lang):
    if not query.strip():
        return "请输入待翻译文本"
    url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
    salt = str(random.randint(32768, 65536))
    sign_raw = APP_ID + query + salt + APP_KEY
    sign = hashlib.md5(sign_raw.encode()).hexdigest()
    params = {
        "q": query,
        "from": from_lang,
        "to": to_lang,
        "appid": APP_ID,
        "salt": salt,
        "sign": sign
    }
    try:
        res = requests.get(url, params=params, timeout=8)
        data = res.json()
        if "trans_result" in data:
            return data["trans_result"][0]["dst"]
        else:
            return f"错误：{data.get('error_msg', '翻译失败')}"
    except Exception as e:
        return f"网络异常：{str(e)}"


# pygame初始化
pygame.init()
WIDTH, HEIGHT = 720, 520
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame多语言翻译器")
clock = pygame.time.Clock()

# 字体
font_normal = pygame.font.SysFont("simhei", 22)
font_button = pygame.font.SysFont("simhei", 20)
font_title = pygame.font.SysFont("simhei", 24)

# 颜色
BG_COLOR = (248, 248, 250)
BOX_COLOR = (255, 255, 255)
TEXT_BLACK = (20, 20, 20)
TEXT_BLUE = (15, 70, 180)
BORDER_COLOR = (80, 80, 80)
BTN_NORMAL = (70, 130, 220)
BTN_HOVER = (40, 100, 190)
BTN_TEXT = (255, 255, 255)

# 程序变量
input_text = ""
result_text = "翻译结果显示在此处"
source_idx = 0    # 默认源语言：中文
target_idx = 1    # 默认目标语言：英语

# 矩形区域定义
input_rect = pygame.Rect(20, 80, 680, 90)
output_rect = pygame.Rect(20, 220, 680, 90)
btn_clear = pygame.Rect(20, 340, 130, 45)
btn_copy = pygame.Rect(170, 340, 130, 45)
btn_trans = pygame.Rect(320, 340, 130, 45)

# 语言下拉框简易位置
source_box = pygame.Rect(20, 20, 160, 36)
target_box = pygame.Rect(200, 20, 160, 36)
dropdown_open = None  # "source" / "target" / None

running = True
while running:
    mouse_pos = pygame.mouse.get_pos()
    screen.fill(BG_COLOR)

    # 绘制语言选择框
    pygame.draw.rect(screen, BOX_COLOR, source_box)
    pygame.draw.rect(screen, BORDER_COLOR, source_box, 2)
    src_txt = font_normal.render(f"源语言：{LANG_LIST[source_idx]}", True, TEXT_BLACK)
    screen.blit(src_txt, (source_box.x + 6, source_box.y + 4))

    pygame.draw.rect(screen, BOX_COLOR, target_box)
    pygame.draw.rect(screen, BORDER_COLOR, target_box, 2)
    tar_txt = font_normal.render(f"目标语言：{LANG_LIST[target_idx]}", True, TEXT_BLACK)
    screen.blit(tar_txt, (target_box.x + 6, target_box.y + 4))

    # 输入框
    pygame.draw.rect(screen, BOX_COLOR, input_rect)
    pygame.draw.rect(screen, BORDER_COLOR, input_rect, 2)
    input_render = font_normal.render(input_text, True, TEXT_BLACK)
    screen.blit(input_render, (input_rect.x + 8, input_rect.y + 8))

    # 输出框
    pygame.draw.rect(screen, BOX_COLOR, output_rect)
    pygame.draw.rect(screen, BORDER_COLOR, output_rect, 2)
    output_render = font_normal.render(result_text, True, TEXT_BLUE)
    screen.blit(output_render, (output_rect.x + 8, output_rect.y + 8))

    # 按钮绘制（悬浮变色）
    # 清空按钮
    btn_color = BTN_HOVER if btn_clear.collidepoint(mouse_pos) else BTN_NORMAL
    pygame.draw.rect(screen, btn_color, btn_clear, border_radius=6)
    clear_txt = font_button.render("清空内容", True, BTN_TEXT)
    screen.blit(clear_txt, (btn_clear.x + 30, btn_clear.y + 10))

    # 复制译文按钮
    btn_color = BTN_HOVER if btn_copy.collidepoint(mouse_pos) else BTN_NORMAL
    pygame.draw.rect(screen, btn_color, btn_copy, border_radius=6)
    copy_txt = font_button.render("复制译文", True, BTN_TEXT)
    screen.blit(copy_txt, (btn_copy.x + 30, btn_copy.y + 10))

    # 翻译按钮
    btn_color = BTN_HOVER if btn_trans.collidepoint(mouse_pos) else BTN_NORMAL
    pygame.draw.rect(screen, btn_color, btn_trans, border_radius=6)
    trans_txt = font_button.render("开始翻译", True, BTN_TEXT)
    screen.blit(trans_txt, (btn_trans.x + 30, btn_trans.y + 10))


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

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # 点击【清空】
            if btn_clear.collidepoint(mouse_pos):
                input_text = ""
                result_text = "翻译结果显示在此处"
            # 点击【复制译文】
            elif btn_copy.collidepoint(mouse_pos):
                if result_text and result_text != "翻译结果显示在此处":
                    pyperclip.copy(result_text)
                    result_text = "✅复制成功！"
            # 点击【翻译】
            elif btn_trans.collidepoint(mouse_pos):
                src_code = LANG_MAP[LANG_LIST[source_idx]]
                tar_code = LANG_MAP[LANG_LIST[target_idx]]
                result_text = baidu_translate(input_text, src_code, tar_code)
            # 点击语言选择框
            elif source_box.collidepoint(mouse_pos):
                dropdown_open = "source"
            elif target_box.collidepoint(mouse_pos):
                dropdown_open = "target"
            else:
                dropdown_open = None

        # 键盘输入
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_BACKSPACE:
                input_text = input_text[:-1]
            elif event.key == pygame.K_RETURN:
                # 回车直接翻译
                src_code = LANG_MAP[LANG_LIST[source_idx]]
                tar_code = LANG_MAP[LANG_LIST[target_idx]]
                result_text = baidu_translate(input_text, src_code, tar_code)
            else:
                if len(input_text) < 300:
                    input_text += event.unicode

    # 简易下拉菜单（弹出语言选择列表）
    if dropdown_open is not None:
        menu_y = source_box.bottom
        for i, lang_name in enumerate(LANG_LIST):
            item_rect = pygame.Rect(source_box.x if dropdown_open=="source" else target_box.x,
                                    menu_y + i*30, 160, 30)
            pygame.draw.rect(screen, BOX_COLOR, item_rect)
            pygame.draw.rect(screen, BORDER_COLOR, item_rect, 1)
            lang_render = font_normal.render(lang_name, True, TEXT_BLACK)
            screen.blit(lang_render, (item_rect.x + 5, item_rect.y + 2))

            # 点击选中语言
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and item_rect.collidepoint(mouse_pos):
                if dropdown_open == "source":
                    source_idx = i
                else:
                    target_idx = i
                dropdown_open = None

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

pygame.quit()