import tkinter as tk
from tkinter import ttk, messagebox
import math

class WeightConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("重量单位转换器")
        self.root.geometry("750x700")
        self.root.configure(bg='#f5f7fa')
        self.root.resizable(True, True)
        
        # 设置颜色主题
        self.colors = {
            'primary': '#8B4513',  # 棕色主题，适合重量
            'secondary': '#A0522D',
            'accent': '#D2691E',
            'bg': '#f5f7fa',
            'card_bg': '#ffffff',
            'text': '#2c3e50',
            'light_text': '#7f8c8d',
            'border': '#d5d5d5',
            'success': '#27ae60',
            'info': '#3498db'
        }
        
        # 重量单位定义（以千克为基准）
        self.weight_units = {
            't': {'name': '吨', 'full_name': '吨 (t)', 'to_kg': 1000, 'precision': 4},
            'kg': {'name': '千克', 'full_name': '千克 (kg)', 'to_kg': 1, 'precision': 3},
            'hg': {'name': '百克', 'full_name': '百克 (hg)', 'to_kg': 0.1, 'precision': 2},
            'dag': {'name': '十克', 'full_name': '十克 (dag)', 'to_kg': 0.01, 'precision': 2},
            'g': {'name': '克', 'full_name': '克 (g)', 'to_kg': 0.001, 'precision': 1},
            'dg': {'name': '分克', 'full_name': '分克 (dg)', 'to_kg': 0.0001, 'precision': 1},
            'cg': {'name': '厘克', 'full_name': '厘克 (cg)', 'to_kg': 0.00001, 'precision': 0},
            'mg': {'name': '毫克', 'full_name': '毫克 (mg)', 'to_kg': 0.000001, 'precision': 0},
            'μg': {'name': '微克', 'full_name': '微克 (μg)', 'to_kg': 1e-9, 'precision': 0},
            'ng': {'name': '纳克', 'full_name': '纳克 (ng)', 'to_kg': 1e-12, 'precision': 0},
            'lb': {'name': '磅', 'full_name': '磅 (lb)', 'to_kg': 0.45359237, 'precision': 3},
            'oz': {'name': '盎司', 'full_name': '盎司 (oz)', 'to_kg': 0.0283495, 'precision': 3},
            'stone': {'name': '英石', 'full_name': '英石 (st)', 'to_kg': 6.35029, 'precision': 3},
            'catty': {'name': '斤', 'full_name': '斤 (斤)', 'to_kg': 0.5, 'precision': 3},
            'tael': {'name': '两', 'full_name': '两 (两)', 'to_kg': 0.0375, 'precision': 3},
            'carat': {'name': '克拉', 'full_name': '克拉 (ct)', 'to_kg': 0.0002, 'precision': 2},
            'jin': {'name': '市斤', 'full_name': '市斤 (市斤)', 'to_kg': 0.5, 'precision': 3}
        }
        
        # 单位分类
        self.unit_categories = {
            '公制大单位': ['t', 'kg'],
            '公制小单位': ['hg', 'dag', 'g', 'dg', 'cg', 'mg', 'μg', 'ng'],
            '英制': ['lb', 'oz', 'stone'],
            '中国传统': ['catty', 'tael', 'jin'],
            '特殊': ['carat']
        }
        
        # 常用转换预设
        self.presets = [
            ("成年人平均体重", "70", "kg", ["lb", "stone", "catty"]),
            ("苹果重量", "0.2", "kg", ["g", "oz", "catty"]),
            ("汽车重量", "1500", "kg", ["t", "lb"]),
            ("大象体重", "5000", "kg", ["t", "lb"]),
            ("手机重量", "0.2", "kg", ["g", "oz"]),
            ("笔记本电脑", "1.5", "kg", ["lb", "g"]),
            ("一袋米", "5", "kg", ["catty", "lb"]),
            ("钻石(1克拉)", "1", "carat", ["g", "mg", "oz"]),
            ("金条(1公斤)", "1", "kg", ["g", "oz", "tael"]),
            ("瓶装水", "0.5", "kg", ["g", "lb", "catty"])
        ]
        
        # 常见物品重量参照
        self.comparisons = [
            ("蚂蚁", "0.000005", "kg", "🐜"),
            ("回形针", "0.001", "kg", "📎"),
            ("硬币(1元)", "0.006", "kg", "💰"),
            ("鸡蛋", "0.05", "kg", "🥚"),
            ("苹果", "0.2", "kg", "🍎"),
            ("笔记本电脑", "1.5", "kg", "💻"),
            ("猫", "4", "kg", "🐱"),
            ("微波炉", "15", "kg", "🍲"),
            ("成年人", "70", "kg", "👤"),
            ("摩托车", "150", "kg", "🏍️"),
            ("汽车", "1500", "kg", "🚗"),
            ("大象", "5000", "kg", "🐘"),
            ("蓝鲸", "150000", "kg", "🐋")
        ]
        
        # 创建界面
        self.setup_ui()
        
        # 初始转换
        self.convert_weight()
    
    def setup_ui(self):
        """设置用户界面"""
        # 主容器
        main_container = tk.Frame(self.root, bg=self.colors['bg'])
        main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 标题区域
        title_frame = tk.Frame(main_container, bg=self.colors['primary'], height=100)
        title_frame.pack(fill=tk.X, pady=(0, 20))
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(
            title_frame,
            text="⚖️ 重量单位转换器",
            font=('Microsoft YaHei', 24, 'bold'),
            fg='white',
            bg=self.colors['primary']
        )
        title_label.pack(expand=True, pady=10)
        
        subtitle_label = tk.Label(
            title_frame,
            text="支持公制、英制、中国传统、珠宝等多种重量单位转换",
            font=('Microsoft YaHei', 10),
            fg='#f0f0f0',
            bg=self.colors['primary']
        )
        subtitle_label.pack(pady=(0, 10))
        
        # 输入区域卡片
        input_card = self.create_card(main_container, "重量输入")
        input_card.pack(fill=tk.X, pady=(0, 15))
        
        # 输入框和单位选择
        input_frame = tk.Frame(input_card, bg=self.colors['card_bg'])
        input_frame.pack(fill=tk.X, padx=20, pady=20)
        
        # 输入框
        self.weight_var = tk.StringVar(value="1")
        tk.Label(
            input_frame,
            text="重量值:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        ).pack(side=tk.LEFT, padx=(0, 10))
        
        self.weight_entry = tk.Entry(
            input_frame,
            textvariable=self.weight_var,
            font=('Microsoft YaHei', 16),
            width=18,
            justify='center',
            bd=2,
            relief=tk.SOLID,
            bg='#f9f9f9'
        )
        self.weight_entry.pack(side=tk.LEFT, padx=(0, 20))
        self.weight_entry.bind('<KeyRelease>', lambda e: self.convert_weight())
        self.weight_entry.select_range(0, tk.END)
        self.weight_entry.focus_set()
        
        # 从单位选择
        tk.Label(
            input_frame,
            text="从:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        ).pack(side=tk.LEFT, padx=(0, 10))
        
        self.from_unit = ttk.Combobox(
            input_frame,
            values=[self.weight_units[u]['full_name'] for u in self.weight_units],
            state='readonly',
            width=20,
            font=('Microsoft YaHei', 12)
        )
        self.from_unit.set(self.weight_units['kg']['full_name'])
        self.from_unit.pack(side=tk.LEFT)
        self.from_unit.bind('<<ComboboxSelected>>', lambda e: self.convert_weight())
        
        # 控制按钮区域
        btn_frame = tk.Frame(input_card, bg=self.colors['card_bg'])
        btn_frame.pack(fill=tk.X, padx=20, pady=(0, 20))
        
        # 主要功能按钮
        buttons = [
            ("🔄 立即转换", self.convert_weight, self.colors['accent']),
            ("⇄ 交换单位", self.swap_units, self.colors['secondary']),
            ("📊 比较重量", self.show_comparison_dialog, self.colors['info']),
            ("🗑️ 重置", self.clear_all, '#e74c3c')
        ]
        
        for text, command, color in buttons:
            btn = tk.Button(
                btn_frame,
                text=text,
                command=command,
                font=('Microsoft YaHei', 10, 'bold'),
                bg=color,
                fg='white',
                activebackground=color,
                activeforeground='white',
                bd=0,
                padx=15,
                pady=8,
                cursor='hand2',
                relief=tk.RAISED
            )
            btn.pack(side=tk.LEFT, padx=5)
        
        # 单位类别选择
        self.setup_unit_categories(main_container)
        
        # 主内容区域
        content_frame = tk.Frame(main_container, bg=self.colors['bg'])
        content_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        # 左侧：转换结果表格
        result_card = self.create_card(content_frame, "转换结果")
        result_card.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
        
        self.setup_results_table(result_card)
        
        # 右侧：预设和参照
        right_frame = tk.Frame(content_frame, bg=self.colors['bg'], width=350)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=False)
        right_frame.pack_propagate(False)
        
        # 预设面板
        preset_card = self.create_card(right_frame, "📋 快速预设")
        preset_card.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        self.setup_presets(preset_card)
        
        # 参照面板
        reference_card = self.create_card(right_frame, "📊 重量参照")
        reference_card.pack(fill=tk.BOTH, expand=True)
        
        self.setup_references(reference_card)
        
        # 状态栏
        self.setup_status_bar(main_container)
    
    def create_card(self, parent, title):
        """创建卡片式容器"""
        card = tk.Frame(parent, bg=self.colors['card_bg'], relief=tk.RAISED, bd=2)
        
        # 标题
        title_label = tk.Label(
            card,
            text=title,
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['primary'],
            bg=self.colors['card_bg'],
            anchor='w'
        )
        title_label.pack(fill=tk.X, padx=15, pady=10)
        
        # 分隔线
        separator = tk.Frame(card, height=1, bg=self.colors['border'])
        separator.pack(fill=tk.X, padx=10)
        
        return card
    
    def setup_unit_categories(self, parent):
        """设置单位类别选择"""
        category_card = self.create_card(parent, "🔍 单位类别筛选")
        category_card.pack(fill=tk.X, pady=(0, 15))
        
        category_frame = tk.Frame(category_card, bg=self.colors['card_bg'])
        category_frame.pack(fill=tk.X, padx=20, pady=15)
        
        self.category_vars = {}
        
        for i, (category_name, units) in enumerate(self.unit_categories.items()):
            var = tk.BooleanVar(value=True)
            self.category_vars[category_name] = var
            
            chk = tk.Checkbutton(
                category_frame,
                text=f"{category_name} ({len(units)}种)",
                variable=var,
                command=self.update_unit_list,
                font=('Microsoft YaHei', 10),
                fg=self.colors['text'],
                bg=self.colors['card_bg'],
                selectcolor=self.colors['card_bg'],
                activebackground=self.colors['card_bg'],
                cursor='hand2'
            )
            chk.grid(row=i//3, column=i%3, sticky='w', padx=10, pady=5)
    
    def setup_results_table(self, parent):
        """设置结果表格"""
        # 创建Treeview
        columns = ('unit', 'name', 'value', 'desc')
        self.results_tree = ttk.Treeview(
            parent,
            columns=columns,
            show='tree headings',
            height=15
        )
        
        # 设置列
        self.results_tree.heading('unit', text='单位', anchor='center')
        self.results_tree.heading('name', text='名称', anchor='center')
        self.results_tree.heading('value', text='数值', anchor='center')
        self.results_tree.heading('desc', text='重量级别', anchor='center')
        
        self.results_tree.column('unit', width=80, anchor='center')
        self.results_tree.column('name', width=100, anchor='center')
        self.results_tree.column('value', width=120, anchor='center')
        self.results_tree.column('desc', width=120, anchor='center')
        
        # 样式配置
        style = ttk.Style()
        style.configure("Treeview", 
                       font=('Microsoft YaHei', 9),
                       rowheight=25)
        style.configure("Treeview.Heading", 
                       font=('Microsoft YaHei', 10, 'bold'),
                       background=self.colors['primary'],
                       foreground='white')
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(parent, orient="vertical", command=self.results_tree.yview)
        self.results_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.results_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=15, pady=15)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=15)
        
        # 绑定双击事件
        self.results_tree.bind('<Double-Button-1>', self.on_result_double_click)
    
    def setup_presets(self, parent):
        """设置预设按钮"""
        preset_frame = tk.Frame(parent, bg=self.colors['card_bg'])
        preset_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
        # 使用Canvas实现滚动
        canvas = tk.Canvas(preset_frame, bg=self.colors['card_bg'], highlightthickness=0)
        scrollbar = tk.Scrollbar(preset_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas, bg=self.colors['card_bg'])
        
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        for i, (name, value, unit, target_units) in enumerate(self.presets):
            btn_frame = tk.Frame(scrollable_frame, bg=self.colors['card_bg'])
            btn_frame.pack(fill=tk.X, pady=5)
            
            # 预设按钮
            btn = tk.Button(
                btn_frame,
                text=name,
                command=lambda v=value, u=unit: self.apply_preset(v, u),
                font=('Microsoft YaHei', 9),
                bg='#f8f9fa',
                fg=self.colors['text'],
                bd=1,
                relief=tk.RAISED,
                padx=15,
                pady=8,
                cursor='hand2',
                anchor='w',
                justify='left',
                width=20
            )
            btn.pack(side=tk.LEFT, fill=tk.X, expand=True)
            
            # 目标单位
            target_text = "→" + "/".join([self.weight_units[u]['name'] for u in target_units[:2]])
            tk.Label(
                btn_frame,
                text=target_text,
                font=('Microsoft YaHei', 8),
                fg=self.colors['light_text'],
                bg=self.colors['card_bg']
            ).pack(side=tk.RIGHT, padx=(5, 0))
        
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    
    def setup_references(self, parent):
        """设置重量参照"""
        ref_frame = tk.Frame(parent, bg=self.colors['card_bg'])
        ref_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
        for name, weight, unit, emoji in self.comparisons:
            item_frame = tk.Frame(ref_frame, bg=self.colors['card_bg'])
            item_frame.pack(fill=tk.X, pady=3)
            
            # 图标
            tk.Label(
                item_frame,
                text=emoji,
                font=('Microsoft YaHei', 12),
                bg=self.colors['card_bg']
            ).pack(side=tk.LEFT, padx=(0, 5))
            
            # 物品名称
            tk.Label(
                item_frame,
                text=name,
                font=('Microsoft YaHei', 9),
                fg=self.colors['text'],
                bg=self.colors['card_bg'],
                width=10,
                anchor='w'
            ).pack(side=tk.LEFT)
            
            # 重量
            weight_text = f"{float(weight):g} {unit}"
            tk.Label(
                item_frame,
                text=weight_text,
                font=('Microsoft YaHei', 8),
                fg=self.colors['light_text'],
                bg=self.colors['card_bg']
            ).pack(side=tk.LEFT, padx=(5, 0))
            
            # 比较按钮
            compare_btn = tk.Button(
                item_frame,
                text="比一比",
                command=lambda w=weight, u=unit, n=name: self.quick_compare(w, u, n),
                font=('Microsoft YaHei', 8),
                bg='#3498db',
                fg='white',
                bd=0,
                padx=8,
                pady=2,
                cursor='hand2'
            )
            compare_btn.pack(side=tk.RIGHT)
    
    def setup_status_bar(self, parent):
        """设置状态栏"""
        status_frame = tk.Frame(parent, bg='#34495e', height=30)
        status_frame.pack(fill=tk.X, side=tk.BOTTOM)
        status_frame.pack_propagate(False)
        
        self.status_var = tk.StringVar(value="就绪 | 输入重量值并选择单位进行转换")
        status_label = tk.Label(
            status_frame,
            textvariable=self.status_var,
            font=('Microsoft YaHei', 9),
            fg='white',
            bg='#34495e',
            anchor=tk.W,
            padx=10
        )
        status_label.pack(fill=tk.X)
    
    def update_unit_list(self):
        """更新单位列表"""
        # 获取选中的类别
        selected_categories = [cat for cat, var in self.category_vars.items() if var.get()]
        
        # 获取选中的单位
        selected_units = []
        for category in selected_categories:
            selected_units.extend(self.unit_categories[category])
        
        # 更新下拉框
        unit_list = [self.weight_units[u]['full_name'] for u in selected_units if u in self.weight_units]
        self.from_unit['values'] = unit_list
        
        # 如果当前单位不在列表中，设置为第一个可用单位
        current = self.from_unit.get()
        if current not in unit_list and unit_list:
            self.from_unit.set(unit_list[0])
        
        # 重新转换
        self.convert_weight()
    
    def get_current_unit(self):
        """获取当前选择的单位"""
        full_name = self.from_unit.get()
        for key, unit_info in self.weight_units.items():
            if unit_info['full_name'] == full_name:
                return key
        return 'kg'  # 默认返回千克
    
    def convert_to_kg(self, value, from_unit):
        """将任意单位转换为千克"""
        if from_unit in self.weight_units:
            return value * self.weight_units[from_unit]['to_kg']
        return value
    
    def convert_from_kg(self, kg, to_unit):
        """将千克转换为任意单位"""
        if to_unit in self.weight_units and self.weight_units[to_unit]['to_kg'] != 0:
            return kg / self.weight_units[to_unit]['to_kg']
        return kg
    
    def format_number(self, number, precision=None):
        """格式化数字显示"""
        if number == 0:
            return "0"
        
        if abs(number) < 0.000000001:  # 非常小的数
            return f"{number:.2e}"
        elif abs(number) >= 1e12:  # 非常大的数
            return f"{number:.2e}"
        elif precision is not None:
            if number.is_integer():
                return f"{int(number):,}"
            formatted = f"{number:,.{precision}f}"
            # 去除多余的零和小数点
            if '.' in formatted:
                formatted = formatted.rstrip('0').rstrip('.')
            return formatted
        else:
            if number.is_integer():
                return f"{int(number):,}"
            return f"{number:,.4f}".rstrip('0').rstrip('.')
    
    def get_weight_description(self, value, unit_key):
        """获取重量描述"""
        unit_info = self.weight_units[unit_key]
        value_in_kg = self.convert_to_kg(1, unit_key) * value
        
        if value_in_kg < 0.00001:  # < 0.01g
            return "极轻"
        elif value_in_kg < 0.001:  # < 1g
            return "很轻"
        elif value_in_kg < 0.01:  # < 10g
            return "轻"
        elif value_in_kg < 0.1:  # < 100g
            return "较轻"
        elif value_in_kg < 1:  # < 1kg
            return "中等"
        elif value_in_kg < 10:  # < 10kg
            return "较重"
        elif value_in_kg < 100:  # < 100kg
            return "重"
        elif value_in_kg < 1000:  # < 1吨
            return "很重"
        else:
            return "极重"
    
    def convert_weight(self, event=None):
        """执行重量转换"""
        try:
            # 获取输入
            weight_str = self.weight_var.get().strip()
            if not weight_str:
                return
            
            try:
                weight = float(weight_str)
            except ValueError:
                if weight_str.startswith('-') and weight_str[1:].replace('.', '', 1).isdigit():
                    weight = float(weight_str)
                else:
                    messagebox.showwarning("输入错误", "请输入有效的数字")
                    return
            
            from_unit = self.get_current_unit()
            
            # 转换为千克
            kilograms = self.convert_to_kg(weight, from_unit)
            
            # 清空表格
            for item in self.results_tree.get_children():
                self.results_tree.delete(item)
            
            # 获取选中的单位类别
            selected_categories = [cat for cat, var in self.category_vars.items() if var.get()]
            selected_units = []
            for category in selected_categories:
                selected_units.extend(self.unit_categories[category])
            
            # 计算并显示所有选中的单位
            for unit_key in selected_units:
                if unit_key in self.weight_units:
                    unit_info = self.weight_units[unit_key]
                    
                    # 转换数值
                    converted_value = self.convert_from_kg(kilograms, unit_key)
                    
                    # 格式化显示
                    formatted_value = self.format_number(converted_value, unit_info['precision'])
                    
                    # 获取描述
                    description = self.get_weight_description(converted_value, unit_key)
                    
                    # 添加到表格
                    self.results_tree.insert('', 'end', values=(
                        unit_info['full_name'].split(' ')[-1].strip('()'),
                        unit_info['name'],
                        formatted_value,
                        description
                    ))
            
            # 更新状态
            input_unit_info = self.weight_units[from_unit]
            self.status_var.set(f"✅ 已转换: {weight} {input_unit_info['full_name'].split(' ')[-1].strip('()')} → 共 {len(self.results_tree.get_children())} 种单位")
            
        except Exception as e:
            self.status_var.set(f"❌ 转换错误: {str(e)}")
    
    def on_result_double_click(self, event):
        """双击结果行时设置该单位"""
        items = self.results_tree.selection()
        if not items:
            return
        
        item = items[0]
        values = self.results_tree.item(item, 'values')
        
        if values:
            unit_symbol = values[0]  # 单位符号
            
            # 查找完整的单位名称
            for unit_key, unit_info in self.weight_units.items():
                if unit_info['full_name'].split(' ')[-1].strip('()') == unit_symbol:
                    # 先获取当前值在新单位下的值
                    try:
                        current_weight = float(self.weight_var.get())
                        current_unit = self.get_current_unit()
                        
                        # 转换到千克
                        kilograms = self.convert_to_kg(current_weight, current_unit)
                        # 从千克转换到新单位
                        new_weight = self.convert_from_kg(kilograms, unit_key)
                        
                        # 设置新值和单位
                        self.weight_var.set(self.format_number(new_weight, unit_info['precision']))
                        self.from_unit.set(unit_info['full_name'])
                        
                        # 重新转换
                        self.convert_weight()
                        
                        self.status_var.set(f"🔄 已切换到: {unit_info['full_name']}")
                        
                    except:
                        self.from_unit.set(unit_info['full_name'])
                        self.convert_weight()
                    break
    
    def apply_preset(self, value, unit):
        """应用预设值"""
        self.weight_var.set(value)
        
        # 设置对应的单位
        if unit in self.weight_units:
            self.from_unit.set(self.weight_units[unit]['full_name'])
        
        self.convert_weight()
        self.status_var.set(f"📋 已应用预设: {value} {self.weight_units[unit]['name']}")
    
    def quick_compare(self, weight, unit, name):
        """快速比较重量"""
        try:
            current_weight = float(self.weight_var.get())
            current_unit = self.get_current_unit()
            
            # 都转换为千克进行比较
            current_kg = self.convert_to_kg(current_weight, current_unit)
            compare_kg = self.convert_to_kg(float(weight), unit)
            
            if compare_kg == 0:
                messagebox.showinfo("比较", "参照物重量为0，无法比较")
                return
            
            ratio = current_kg / compare_kg
            
            if ratio < 0.001:
                result = f"当前重量相当于 {ratio*1000000:.1f} 个{name}的百万分之一"
            elif ratio < 0.01:
                result = f"当前重量相当于 {ratio*10000:.1f} 个{name}的万分之一"
            elif ratio < 0.1:
                result = f"当前重量相当于 {ratio*1000:.1f} 个{name}的千分之一"
            elif ratio < 1:
                result = f"当前重量相当于 {ratio*100:.1f}% 个{name}"
            elif ratio == 1:
                result = f"当前重量正好等于1个{name}"
            elif ratio <= 10:
                result = f"当前重量相当于 {ratio:.1f} 个{name}"
            elif ratio <= 100:
                result = f"当前重量相当于 {ratio:.0f} 个{name}"
            else:
                result = f"当前重量相当于 {ratio:.0f} 个{name}"
            
            self.status_var.set(f"📊 比较结果: {result}")
            
        except:
            messagebox.showwarning("错误", "请输入有效的重量值进行比较")
    
    def show_comparison_dialog(self):
        """显示详细比较对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title("详细重量比较")
        dialog.geometry("400x500")
        dialog.configure(bg=self.colors['bg'])
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = self.root.winfo_x() + (self.root.winfo_width() - dialog.winfo_width()) // 2
        y = self.root.winfo_y() + (self.root.winfo_height() - dialog.winfo_height()) // 2
        dialog.geometry(f"+{x}+{y}")
        
        # 标题
        tk.Label(
            dialog,
            text="📊 详细重量比较",
            font=('Microsoft YaHei', 14, 'bold'),
            fg=self.colors['primary'],
            bg=self.colors['bg']
        ).pack(pady=10)
        
        # 当前重量显示
        try:
            current_weight = float(self.weight_var.get())
            current_unit = self.get_current_unit()
            current_kg = self.convert_to_kg(current_weight, current_unit)
            
            current_text = f"当前重量: {current_weight} {current_unit} ({current_kg:.3f} kg)"
            tk.Label(
                dialog,
                text=current_text,
                font=('Microsoft YaHei', 11),
                fg=self.colors['text'],
                bg=self.colors['bg']
            ).pack(pady=5)
            
            # 比较结果
            results_frame = tk.Frame(dialog, bg=self.colors['bg'])
            results_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
            
            for name, weight, unit, emoji in self.comparisons:
                compare_kg = self.convert_to_kg(float(weight), unit)
                if compare_kg > 0:
                    ratio = current_kg / compare_kg
                    
                    if ratio >= 1000:
                        display_ratio = f"{ratio/1000:.1f}千"
                    elif ratio >= 1:
                        display_ratio = f"{ratio:.2f}"
                    elif ratio >= 0.001:
                        display_ratio = f"{1/ratio:.2f}分之1"
                    else:
                        display_ratio = "极小"
                    
                    frame = tk.Frame(results_frame, bg=self.colors['card_bg'], relief=tk.RAISED, bd=1)
                    frame.pack(fill=tk.X, pady=2)
                    
                    tk.Label(
                        frame,
                        text=f"{emoji} {name}",
                        font=('Microsoft YaHei', 9),
                        bg=self.colors['card_bg'],
                        width=12,
                        anchor='w'
                    ).pack(side=tk.LEFT, padx=5)
                    
                    tk.Label(
                        frame,
                        text=f"{weight} {unit}",
                        font=('Microsoft YaHei', 8),
                        fg=self.colors['light_text'],
                        bg=self.colors['card_bg']
                    ).pack(side=tk.LEFT, padx=5)
                    
                    if ratio >= 1:
                        result_text = f"相当于 {display_ratio} 个"
                    else:
                        result_text = f"相当于 1/{display_ratio} 个"
                    
                    tk.Label(
                        frame,
                        text=result_text,
                        font=('Microsoft YaHei', 9),
                        fg=self.colors['primary'],
                        bg=self.colors['card_bg']
                    ).pack(side=tk.RIGHT, padx=5)
            
        except:
            tk.Label(
                dialog,
                text="无法比较：请输入有效的重量值",
                font=('Microsoft YaHei', 10),
                fg='#e74c3c',
                bg=self.colors['bg']
            ).pack(pady=20)
        
        # 关闭按钮
        tk.Button(
            dialog,
            text="关闭",
            command=dialog.destroy,
            font=('Microsoft YaHei', 10),
            bg=self.colors['primary'],
            fg='white',
            bd=0,
            padx=20,
            pady=8
        ).pack(pady=10)
    
    def swap_units(self):
        """交换单位（与第一个结果单位交换）"""
        items = self.results_tree.get_children()
        if items:
            first_item = items[0]
            values = self.results_tree.item(first_item, 'values')
            
            if values:
                unit_symbol = values[0]
                
                # 查找对应的完整单位名称
                for unit_key, unit_info in self.weight_units.items():
                    if unit_info['full_name'].split(' ')[-1].strip('()') == unit_symbol:
                        current_value = self.weight_var.get()
                        
                        # 计算新值
                        try:
                            current_weight = float(current_value)
                            current_unit = self.get_current_unit()
                            
                            kilograms = self.convert_to_kg(current_weight, current_unit)
                            new_weight = self.convert_from_kg(kilograms, unit_key)
                            
                            # 设置新值和单位
                            self.weight_var.set(self.format_number(new_weight))
                            self.from_unit.set(unit_info['full_name'])
                            
                            # 重新转换
                            self.convert_weight()
                            
                            self.status_var.set(f"⇄ 已交换到: {unit_info['full_name']}")
                            
                        except:
                            pass
                        break
    
    def clear_all(self):
        """清空所有"""
        self.weight_var.set("1")
        self.from_unit.set(self.weight_units['kg']['full_name'])
        
        for item in self.results_tree.get_children():
            self.results_tree.delete(item)
        
        # 重置所有复选框
        for var in self.category_vars.values():
            var.set(True)
        
        self.update_unit_list()
        self.status_var.set("🔄 已重置 | 输入重量值并选择单位进行转换")

def main():
    root = tk.Tk()
    
    # 设置窗口图标
    try:
        root.iconbitmap(default='icon.ico')
    except:
        pass
    
    # 设置窗口居中
    window_width = 750
    window_height = 700
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    center_x = int(screen_width/2 - window_width/2)
    center_y = int(screen_height/2 - window_height/2)
    root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
    
    # 设置样式
    style = ttk.Style()
    style.theme_use('clam')
    
    # 创建应用
    app = WeightConverter(root)
    
    # 运行主循环
    root.mainloop()

if __name__ == "__main__":
    main()