import pygame
import sys
import pyperclip
import colorsys

# 初始化Pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 700, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("颜色识别工具")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
LIGHT_GRAY = (200, 200, 200)
GRAY = (128, 128, 128)
LIGHT_BLUE = (173, 216, 230)

# 修复中文显示：使用系统中文字体
def get_chinese_font(size):
    font_names = [
        "SimHei", "Microsoft YaHei", "SimSun",
        "PingFang SC", "Heiti SC",
        "WenQuanYi Micro Hei", "Noto Sans CJK SC"
    ]
    
    for font_name in font_names:
        try:
            font = pygame.font.SysFont(font_name, size)
            test_text = font.render("测试", True, BLACK)
            if test_text.get_width() > 10:
                return font
        except:
            continue
    
    print("警告：未找到支持中文的字体，中文可能显示为方块")
    return pygame.font.Font(None, size)

# 字体设置
font_large = get_chinese_font(48)
font_medium = get_chinese_font(32)
font_small = get_chinese_font(24)

# 按钮类
class Button:
    def __init__(self, x, y, w, h, text, color=LIGHT_GRAY, hover_color=GRAY):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text
        self.color = color
        self.hover_color = hover_color
        self.is_hovered = False

    def draw(self, screen):
        current_color = self.hover_color if self.is_hovered else self.color
        pygame.draw.rect(screen, current_color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 2)
        text_surface = font_small.render(self.text, True, BLACK)
        screen.blit(text_surface, (self.rect.x + self.rect.width//2 - text_surface.get_width()//2,
                                  self.rect.y + self.rect.height//2 - text_surface.get_height()//2))

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.is_hovered = self.rect.collidepoint(event.pos)
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                return True
        return False

# 颜色块类
class ColorBlock:
    def __init__(self, x, y, size, color):
        self.rect = pygame.Rect(x, y, size, size)
        self.color = color

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 1)

    def is_clicked(self, pos):
        return self.rect.collidepoint(pos)

# 转换RGB到十六进制
def rgb_to_hex(rgb):
    return "#{:02x}{:02x}{:02x}".format(*rgb).upper()

# 转换RGB到HSV
def rgb_to_hsv(rgb):
    r, g, b = [x/255.0 for x in rgb]
    h, s, v = colorsys.rgb_to_hsv(r, g, b)
    return (int(h*360), int(s*100), int(v*100))

# 主程序
def main():
    current_color = (255, 255, 255)
    picking_color = False
    
    # 创建按钮
    pick_button = Button(50, 400, 150, 50, "屏幕取色")
    copy_rgb_button = Button(220, 400, 150, 50, "复制RGB")
    copy_hex_button = Button(390, 400, 150, 50, "复制十六进制")
    copy_hsv_button = Button(560, 400, 100, 50, "复制HSV")
    
    # 创建常用颜色调色板
    common_colors = [
        (255, 0, 0), (255, 165, 0), (255, 255, 0), (0, 255, 0),
        (0, 255, 255), (0, 0, 255), (128, 0, 128), (255, 192, 203),
        (255, 255, 255), (192, 192, 192), (128, 128, 128), (0, 0, 0)
    ]
    color_blocks = []
    for i, color in enumerate(common_colors):
        x = 50 + (i % 6) * 50
        y = 320 + (i // 6) * 50
        color_blocks.append(ColorBlock(x, y, 40, color))
    
    # 创建一个小的透明窗口用于取色
    pick_surface = pygame.Surface((1, 1))
    
    while True:
        screen.fill(WHITE)
        
        # 绘制标题
        title = font_large.render("颜色识别工具", True, BLACK)
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 20))
        
        # 绘制颜色预览区域
        pygame.draw.rect(screen, current_color, (50, 80, 600, 200))
        pygame.draw.rect(screen, BLACK, (50, 80, 600, 200), 3)
        
        # 绘制颜色信息
        rgb_text = font_medium.render(f"RGB: {current_color[0]}, {current_color[1]}, {current_color[2]}", True, BLACK)
        hex_text = font_medium.render(f"十六进制: {rgb_to_hex(current_color)}", True, BLACK)
        hsv = rgb_to_hsv(current_color)
        hsv_text = font_medium.render(f"HSV: {hsv[0]}°, {hsv[1]}%, {hsv[2]}%", True, BLACK)
        
        screen.blit(rgb_text, (50, 300))
        screen.blit(hex_text, (250, 300))
        screen.blit(hsv_text, (500, 300))
        
        # 绘制常用颜色调色板
        palette_title = font_small.render("常用颜色:", True, BLACK)
        screen.blit(palette_title, (50, 290))
        for block in color_blocks:
            block.draw(screen)
        
        # 绘制按钮
        pick_button.draw(screen)
        copy_rgb_button.draw(screen)
        copy_hex_button.draw(screen)
        copy_hsv_button.draw(screen)
        
        # 绘制操作提示
        if picking_color:
            hint = font_medium.render("点击屏幕任意位置取色，按ESC取消", True, (255, 0, 0))
            screen.blit(hint, (WIDTH//2 - hint.get_width()//2, 460))
        else:
            hint = font_small.render("点击常用颜色或使用屏幕取色功能", True, GRAY)
            screen.blit(hint, (WIDTH//2 - hint.get_width()//2, 460))
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    if picking_color:
                        picking_color = False
                        pygame.display.set_mode((WIDTH, HEIGHT))
                    else:
                        pygame.quit()
                        sys.exit()
            
            if picking_color:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    # 获取鼠标位置
                    x, y = pygame.mouse.get_pos()
                    # 获取该位置的颜色
                    pygame.display.iconify()
                    pygame.time.wait(100)
                    color = pygame.display.get_surface().get_at((x, y))
                    current_color = (color[0], color[1], color[2])
                    picking_color = False
                    pygame.display.set_mode((WIDTH, HEIGHT))
            else:
                # 处理按钮事件
                if pick_button.handle_event(event):
                    picking_color = True
                    # 创建一个全屏透明窗口用于取色
                    pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
                    screen.fill((0, 0, 0, 0))
                
                if copy_rgb_button.handle_event(event):
                    pyperclip.copy(f"{current_color[0]}, {current_color[1]}, {current_color[2]}")
                
                if copy_hex_button.handle_event(event):
                    pyperclip.copy(rgb_to_hex(current_color))
                
                if copy_hsv_button.handle_event(event):
                    hsv = rgb_to_hsv(current_color)
                    pyperclip.copy(f"{hsv[0]}, {hsv[1]}, {hsv[2]}")
                
                # 修复：先检查事件类型，再访问event.pos
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for block in color_blocks:
                        if block.is_clicked(event.pos):
                            current_color = block.color
        
        pygame.display.flip()

if __name__ == "__main__":
    main()