# app.py - 主应用程序
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import os
import json
import shutil
import datetime
import hashlib
import uuid
import sqlite3
from PIL import Image, ImageTk
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import threading
import time

class FileManager:
    def __init__(self, root):
        self.root = root
        self.root.title("文件管理器")
        self.root.geometry("1200x700")
        
        # 设置暗色主题颜色
        self.bg_color = "#1e1e1e"
        self.fg_color = "#ffffff"
        self.accent_color = "#007acc"
        self.secondary_bg = "#252526"
        self.hover_color = "#2d2d30"
        
        self.root.configure(bg=self.bg_color)
        
        # 初始化数据库
        self.init_database()
        
        # 当前用户（默认为游客）
        self.current_user = None
        
        # 当前路径
        self.current_path = ""
        
        # 选中的文件
        self.selected_files = []
        
        # 视图模式：list 或 grid
        self.view_mode = "list"
        
        # 分享服务器运行状态
        self.share_server_running = False
        
        self.setup_ui()
        self.show_login_screen()
    
    def init_database(self):
        """初始化数据库"""
        self.conn = sqlite3.connect('file_manager.db')
        self.cursor = self.conn.cursor()
        
        # 创建用户表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                storage_path TEXT
            )
        ''')
        
        # 创建分享表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS shares (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                token TEXT UNIQUE NOT NULL,
                user_id INTEGER NOT NULL,
                file_path TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                download_count INTEGER DEFAULT 0,
                expires_at TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
        ''')
        
        # 创建默认用户（如果不存在）
        self.cursor.execute("SELECT * FROM users WHERE username='admin'")
        if not self.cursor.fetchone():
            default_hash = hashlib.sha256("admin123".encode()).hexdigest()
            self.cursor.execute(
                "INSERT INTO users (username, password_hash) VALUES (?, ?)",
                ("admin", default_hash)
            )
        
        self.conn.commit()
    
    def setup_ui(self):
        """设置主界面"""
        # 顶部菜单栏
        self.menu_bar = tk.Menu(self.root, bg=self.secondary_bg, fg=self.fg_color)
        self.root.config(menu=self.menu_bar)
        
        # 文件菜单
        file_menu = tk.Menu(self.menu_bar, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
        file_menu.add_command(label="新建文件夹", command=self.new_folder)
        file_menu.add_command(label="新建文件", command=self.new_file)
        file_menu.add_command(label="上传文件", command=self.upload_file)
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.root.quit)
        self.menu_bar.add_cascade(label="文件", menu=file_menu)
        
        # 编辑菜单
        edit_menu = tk.Menu(self.menu_bar, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
        edit_menu.add_command(label="复制", command=self.copy_files)
        edit_menu.add_command(label="移动", command=self.move_files)
        edit_menu.add_command(label="删除", command=self.delete_files)
        edit_menu.add_command(label="重命名", command=self.rename_file)
        edit_menu.add_separator()
        edit_menu.add_command(label="全选", command=self.select_all)
        self.menu_bar.add_cascade(label="编辑", menu=edit_menu)
        
        # 视图菜单
        view_menu = tk.Menu(self.menu_bar, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
        view_menu.add_command(label="列表视图", command=lambda: self.change_view("list"))
        view_menu.add_command(label="网格视图", command=lambda: self.change_view("grid"))
        self.menu_bar.add_cascade(label="视图", menu=view_menu)
        
        # 分享菜单
        share_menu = tk.Menu(self.menu_bar, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
        share_menu.add_command(label="生成分享链接", command=self.create_share_link)
        share_menu.add_command(label="我的分享", command=self.show_my_shares)
        self.menu_bar.add_cascade(label="分享", menu=share_menu)
        
        # 用户菜单
        self.user_menu = tk.Menu(self.menu_bar, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
        self.user_menu.add_command(label="登录", command=self.show_login_screen)
        self.user_menu.add_command(label="注册", command=self.show_register_screen)
        self.user_menu.add_command(label="注销", command=self.logout)
        self.menu_bar.add_cascade(label="用户", menu=self.user_menu)
        
        # 工具栏
        toolbar_frame = tk.Frame(self.root, bg=self.secondary_bg, height=40)
        toolbar_frame.pack(side=tk.TOP, fill=tk.X)
        toolbar_frame.pack_propagate(False)
        
        # 工具栏按钮
        buttons = [
            ("新建文件夹", self.new_folder),
            ("新建文件", self.new_file),
            ("上传", self.upload_file),
            ("下载", self.download_file),
            ("分享", self.create_share_link),
            ("删除", self.delete_files),
            ("刷新", self.refresh_files)
        ]
        
        for text, command in buttons:
            btn = tk.Button(
                toolbar_frame,
                text=text,
                command=command,
                bg=self.accent_color,
                fg=self.fg_color,
                relief=tk.FLAT,
                padx=10,
                pady=5
            )
            btn.pack(side=tk.LEFT, padx=5, pady=5)
        
        # 搜索框
        search_frame = tk.Frame(toolbar_frame, bg=self.secondary_bg)
        search_frame.pack(side=tk.RIGHT, padx=10)
        
        tk.Label(search_frame, text="搜索:", bg=self.secondary_bg, fg=self.fg_color).pack(side=tk.LEFT)
        self.search_var = tk.StringVar()
        self.search_entry = tk.Entry(
            search_frame,
            textvariable=self.search_var,
            bg=self.bg_color,
            fg=self.fg_color,
            insertbackground=self.fg_color,
            width=30
        )
        self.search_entry.pack(side=tk.LEFT, padx=5)
        self.search_entry.bind('<Return>', lambda e: self.search_files())
        
        # 主内容区域
        main_frame = tk.Frame(self.root, bg=self.bg_color)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 左侧导航栏
        self.nav_frame = tk.Frame(main_frame, bg=self.secondary_bg, width=200)
        self.nav_frame.pack(side=tk.LEFT, fill=tk.Y)
        self.nav_frame.pack_propagate(False)
        
        # 路径显示
        self.path_label = tk.Label(
            self.nav_frame,
            text="路径:",
            bg=self.secondary_bg,
            fg=self.fg_color,
            anchor='w'
        )
        self.path_label.pack(fill=tk.X, padx=10, pady=5)
        
        self.path_text = tk.Text(
            self.nav_frame,
            height=3,
            bg=self.bg_color,
            fg=self.fg_color,
            relief=tk.FLAT
        )
        self.path_text.pack(fill=tk.X, padx=10, pady=5)
        
        # 导航按钮
        nav_buttons = [
            ("我的文件", self.go_home),
            ("最近访问", self.show_recent),
            ("收藏夹", self.show_favorites),
            ("回收站", self.show_trash)
        ]
        
        for text, command in nav_buttons:
            btn = tk.Button(
                self.nav_frame,
                text=text,
                command=command,
                bg=self.hover_color,
                fg=self.fg_color,
                relief=tk.FLAT,
                anchor='w',
                padx=20
            )
            btn.pack(fill=tk.X, pady=2)
            btn.bind("<Enter>", lambda e, b=btn: b.config(bg=self.accent_color))
            btn.bind("<Leave>", lambda e, b=btn: b.config(bg=self.hover_color))
        
        # 文件列表区域
        self.file_frame = tk.Frame(main_frame, bg=self.bg_color)
        self.file_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 文件列表（Treeview）
        self.tree_frame = tk.Frame(self.file_frame, bg=self.bg_color)
        self.tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建带滚动条的Treeview
        self.tree_scroll = tk.Scrollbar(self.tree_frame)
        self.tree_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.tree = ttk.Treeview(
            self.tree_frame,
            yscrollcommand=self.tree_scroll.set,
            selectmode="extended",
            columns=("名称", "大小", "修改时间", "类型", "分享链接"),
            show="headings"
        )
        
        # 配置样式
        style = ttk.Style()
        style.theme_use('clam')
        style.configure("Treeview",
            background=self.bg_color,
            foreground=self.fg_color,
            fieldbackground=self.bg_color,
            rowheight=25
        )
        style.configure("Treeview.Heading",
            background=self.secondary_bg,
            foreground=self.fg_color,
            relief=tk.FLAT
        )
        style.map("Treeview",
            background=[('selected', self.accent_color)],
            foreground=[('selected', self.fg_color)]
        )
        
        # 设置列
        columns = [("名称", 300), ("大小", 100), ("修改时间", 150), ("类型", 100), ("分享链接", 200)]
        for col, width in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=width)
        
        self.tree.pack(fill=tk.BOTH, expand=True)
        self.tree_scroll.config(command=self.tree.yview)
        
        # 绑定事件
        self.tree.bind('<Double-1>', self.on_double_click)
        self.tree.bind('<Button-3>', self.show_context_menu)
        
        # 状态栏
        self.status_bar = tk.Label(
            self.root,
            text="就绪",
            bg=self.secondary_bg,
            fg=self.fg_color,
            anchor=tk.W,
            relief=tk.SUNKEN
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    def show_login_screen(self):
        """显示登录窗口"""
        self.login_window = tk.Toplevel(self.root)
        self.login_window.title("登录")
        self.login_window.geometry("300x200")
        self.login_window.configure(bg=self.bg_color)
        self.login_window.transient(self.root)
        self.login_window.grab_set()
        
        tk.Label(self.login_window, text="用户名:", bg=self.bg_color, fg=self.fg_color).pack(pady=10)
        self.login_username = tk.Entry(self.login_window, bg=self.bg_color, fg=self.fg_color)
        self.login_username.pack(pady=5)
        
        tk.Label(self.login_window, text="密码:", bg=self.bg_color, fg=self.fg_color).pack(pady=10)
        self.login_password = tk.Entry(self.login_window, show="*", bg=self.bg_color, fg=self.fg_color)
        self.login_password.pack(pady=5)
        
        tk.Button(
            self.login_window,
            text="登录",
            command=self.login,
            bg=self.accent_color,
            fg=self.fg_color
        ).pack(pady=20)
    
    def show_register_screen(self):
        """显示注册窗口"""
        self.register_window = tk.Toplevel(self.root)
        self.register_window.title("注册")
        self.register_window.geometry("300x250")
        self.register_window.configure(bg=self.bg_color)
        self.register_window.transient(self.root)
        self.register_window.grab_set()
        
        tk.Label(self.register_window, text="用户名:", bg=self.bg_color, fg=self.fg_color).pack(pady=5)
        self.register_username = tk.Entry(self.register_window, bg=self.bg_color, fg=self.fg_color)
        self.register_username.pack(pady=5)
        
        tk.Label(self.register_window, text="密码:", bg=self.bg_color, fg=self.fg_color).pack(pady=5)
        self.register_password = tk.Entry(self.register_window, show="*", bg=self.bg_color, fg=self.fg_color)
        self.register_password.pack(pady=5)
        
        tk.Label(self.register_window, text="确认密码:", bg=self.bg_color, fg=self.fg_color).pack(pady=5)
        self.register_confirm = tk.Entry(self.register_window, show="*", bg=self.bg_color, fg=self.fg_color)
        self.register_confirm.pack(pady=5)
        
        tk.Button(
            self.register_window,
            text="注册",
            command=self.register,
            bg=self.accent_color,
            fg=self.fg_color
        ).pack(pady=20)
    
    def login(self):
        """用户登录"""
        username = self.login_username.get()
        password = self.login_password.get()
        
        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return
        
        password_hash = hashlib.sha256(password.encode()).hexdigest()
        
        self.cursor.execute(
            "SELECT id, username FROM users WHERE username=? AND password_hash=?",
            (username, password_hash)
        )
        user = self.cursor.fetchone()
        
        if user:
            self.current_user = {
                'id': user[0],
                'username': user[1]
            }
            
            # 创建用户目录
            user_dir = os.path.join('user_data', str(user[0]))
            if not os.path.exists(user_dir):
                os.makedirs(user_dir)
            
            self.current_path = user_dir
            self.update_path_display()
            self.refresh_files()
            self.login_window.destroy()
            messagebox.showinfo("成功", f"欢迎回来，{user[1]}！")
        else:
            messagebox.showerror("错误", "用户名或密码错误")
    
    def register(self):
        """用户注册"""
        username = self.register_username.get()
        password = self.register_password.get()
        confirm = self.register_confirm.get()
        
        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return
        
        if password != confirm:
            messagebox.showerror("错误", "两次输入的密码不一致")
            return
        
        try:
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            self.cursor.execute(
                "INSERT INTO users (username, password_hash) VALUES (?, ?)",
                (username, password_hash)
            )
            self.conn.commit()
            
            # 获取新用户ID
            self.cursor.execute("SELECT id FROM users WHERE username=?", (username,))
            user_id = self.cursor.fetchone()[0]
            
            # 创建用户目录
            user_dir = os.path.join('user_data', str(user_id))
            os.makedirs(user_dir, exist_ok=True)
            
            self.register_window.destroy()
            messagebox.showinfo("成功", "注册成功！请登录")
            self.show_login_screen()
        except sqlite3.IntegrityError:
            messagebox.showerror("错误", "用户名已存在")
    
    def logout(self):
        """用户注销"""
        self.current_user = None
        self.current_path = ""
        self.selected_files = []
        self.tree.delete(*self.tree.get_children())
        self.update_status("已注销")
        messagebox.showinfo("信息", "已成功注销")
    
    def new_folder(self):
        """新建文件夹"""
        if not self.current_user:
            messagebox.showerror("错误", "请先登录")
            return
        
        folder_name = simpledialog.askstring("新建文件夹", "请输入文件夹名称:")
        if folder_name:
            folder_path = os.path.join(self.current_path, folder_name)
            try:
                os.makedirs(folder_path, exist_ok=False)
                self.refresh_files()
                self.update_status(f"已创建文件夹: {folder_name}")
            except FileExistsError:
                messagebox.showerror("错误", "文件夹已存在")
    
    def new_file(self):
        """新建文件"""
        if not self.current_user:
            messagebox.showerror("错误", "请先登录")
            return
        
        file_name = simpledialog.askstring("新建文件", "请输入文件名:")
        if file_name:
            file_path = os.path.join(self.current_path, file_name)
            try:
                with open(file_path, 'w') as f:
                    f.write("")
                self.refresh_files()
                self.update_status(f"已创建文件: {file_name}")
            except Exception as e:
                messagebox.showerror("错误", f"创建文件失败: {str(e)}")
    
    def upload_file(self):
        """上传文件"""
        if not self.current_user:
            messagebox.showerror("错误", "请先登录")
            return
        
        file_path = filedialog.askopenfilename()
        if file_path:
            file_name = os.path.basename(file_path)
            dest_path = os.path.join(self.current_path, file_name)
            
            # 如果文件已存在，询问是否覆盖
            if os.path.exists(dest_path):
                if not messagebox.askyesno("确认", "文件已存在，是否覆盖？"):
                    return
            
            try:
                shutil.copy2(file_path, dest_path)
                self.refresh_files()
                self.update_status(f"已上传文件: {file_name}")
            except Exception as e:
                messagebox.showerror("错误", f"上传失败: {str(e)}")
    
    def download_file(self):
        """下载文件"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择文件")
            return
        
        file_name = self.tree.item(selected[0])['values'][0]
        file_path = os.path.join(self.current_path, file_name)
        
        if not os.path.isfile(file_path):
            messagebox.showerror("错误", "只能下载文件")
            return
        
        dest_path = filedialog.asksaveasfilename(
            initialfile=file_name,
            title="保存文件"
        )
        
        if dest_path:
            try:
                shutil.copy2(file_path, dest_path)
                self.update_status(f"已下载文件: {file_name}")
            except Exception as e:
                messagebox.showerror("错误", f"下载失败: {str(e)}")
    
    def refresh_files(self):
        """刷新文件列表"""
        self.tree.delete(*self.tree.get_children())
        
        if not self.current_path or not os.path.exists(self.current_path):
            return
        
        try:
            items = os.listdir(self.current_path)
            
            for item in items:
                item_path = os.path.join(self.current_path, item)
                stats = os.stat(item_path)
                mod_time = datetime.datetime.fromtimestamp(stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
                
                if os.path.isdir(item_path):
                    item_type = "文件夹"
                    size = ""
                else:
                    item_type = "文件"
                    size = self.format_size(stats.st_size)
                
                # 获取分享信息
                share_info = self.get_share_info(item_path)
                share_link = share_info['link'] if share_info else ""
                
                self.tree.insert("", "end", values=(
                    item, size, mod_time, item_type, share_link
                ))
        except Exception as e:
            messagebox.showerror("错误", f"无法读取目录: {str(e)}")
    
    def format_size(self, size):
        """格式化文件大小"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size < 1024.0:
                return f"{size:.2f} {unit}"
            size /= 1024.0
        return f"{size:.2f} PB"
    
    def get_share_info(self, file_path):
        """获取文件分享信息"""
        if not self.current_user:
            return None
        
        self.cursor.execute(
            "SELECT token, download_count FROM shares WHERE user_id=? AND file_path=?",
            (self.current_user['id'], file_path)
        )
        result = self.cursor.fetchone()
        
        if result:
            return {
                'token': result[0],
                'download_count': result[1],
                'link': f"http://localhost:8000/share/{result[0]}"
            }
        return None
    
    def on_double_click(self, event):
        """双击文件或文件夹"""
        selected = self.tree.selection()
        if not selected:
            return
        
        item = self.tree.item(selected[0])
        item_name = item['values'][0]
        item_path = os.path.join(self.current_path, item_name)
        
        if os.path.isdir(item_path):
            self.current_path = item_path
            self.update_path_display()
            self.refresh_files()
        else:
            self.open_file(item_path)
    
    def open_file(self, file_path):
        """打开文件"""
        # 如果是文本文件，在编辑器中打开
        if file_path.endswith(('.txt', '.json', '.py', '.js', '.html', '.css', '.md', '.php', '.m3u')):
            self.open_editor(file_path)
        else:
            # 使用系统默认程序打开
            try:
                os.startfile(file_path)  # Windows
            except:
                try:
                    os.system(f'xdg-open "{file_path}"')  # Linux
                except:
                    try:
                        os.system(f'open "{file_path}"')  # macOS
                    except:
                        messagebox.showinfo("提示", "无法打开此文件类型")
    
    def open_editor(self, file_path):
        """打开文本编辑器"""
        editor = tk.Toplevel(self.root)
        editor.title(f"编辑 - {os.path.basename(file_path)}")
        editor.geometry("800x600")
        editor.configure(bg=self.bg_color)
        
        # 文本区域
        text_area = tk.Text(
            editor,
            bg=self.bg_color,
            fg=self.fg_color,
            insertbackground=self.fg_color,
            font=("Consolas", 11)
        )
        text_area.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 加载文件内容
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                text_area.insert('1.0', content)
        except Exception as e:
            text_area.insert('1.0', f"无法读取文件: {str(e)}")
        
        # 保存按钮
        def save_file():
            content = text_area.get('1.0', 'end-1c')
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                messagebox.showinfo("成功", "文件已保存")
                editor.destroy()
                self.refresh_files()
            except Exception as e:
                messagebox.showerror("错误", f"保存失败: {str(e)}")
        
        tk.Button(
            editor,
            text="保存",
            command=save_file,
            bg=self.accent_color,
            fg=self.fg_color
        ).pack(pady=10)
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        # 获取选中的项目
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            
            # 创建菜单
            menu = tk.Menu(self.root, tearoff=0, bg=self.secondary_bg, fg=self.fg_color)
            
            selected_count = len(self.tree.selection())
            if selected_count == 1:
                menu.add_command(label="打开", command=self.open_selected)
                menu.add_command(label="重命名", command=self.rename_file)
                menu.add_command(label="属性", command=self.show_properties)
            else:
                menu.add_command(label="批量操作", state='disabled')
            
            menu.add_separator()
            menu.add_command(label="复制", command=self.copy_files)
            menu.add_command(label="移动", command=self.move_files)
            menu.add_command(label="删除", command=self.delete_files)
            menu.add_separator()
            menu.add_command(label="分享", command=self.create_share_link)
            menu.add_command(label="下载", command=self.download_file)
            
            menu.post(event.x_root, event.y_root)
    
    def open_selected(self):
        """打开选中的文件"""
        selected = self.tree.selection()
        if selected:
            item = self.tree.item(selected[0])
            item_name = item['values'][0]
            item_path = os.path.join(self.current_path, item_name)
            
            if os.path.isfile(item_path):
                self.open_file(item_path)
    
    def rename_file(self):
        """重命名文件"""
        selected = self.tree.selection()
        if not selected:
            return
        
        old_name = self.tree.item(selected[0])['values'][0]
        new_name = simpledialog.askstring("重命名", "请输入新名称:", initialvalue=old_name)
        
        if new_name and new_name != old_name:
            old_path = os.path.join(self.current_path, old_name)
            new_path = os.path.join(self.current_path, new_name)
            
            try:
                os.rename(old_path, new_path)
                self.refresh_files()
                self.update_status(f"已重命名: {old_name} -> {new_name}")
            except Exception as e:
                messagebox.showerror("错误", f"重命名失败: {str(e)}")
    
    def copy_files(self):
        """复制文件"""
        selected = self.tree.selection()
        if not selected:
            return
        
        self.selected_files = []
        for item in selected:
            file_name = self.tree.item(item)['values'][0]
            self.selected_files.append(file_name)
        
        self.update_status(f"已复制 {len(self.selected_files)} 个项目")
    
    def move_files(self):
        """移动文件"""
        selected = self.tree.selection()
        if not selected:
            return
        
        dest = filedialog.askdirectory(title="选择目标文件夹")
        if dest:
            try:
                for item in selected:
                    file_name = self.tree.item(item)['values'][0]
                    src = os.path.join(self.current_path, file_name)
                    dst = os.path.join(dest, file_name)
                    
                    if os.path.exists(dst):
                        if not messagebox.askyesno("确认", f"{file_name} 已存在，是否覆盖？"):
                            continue
                    
                    shutil.move(src, dst)
                
                self.refresh_files()
                self.update_status(f"已移动 {len(selected)} 个项目到 {dest}")
            except Exception as e:
                messagebox.showerror("错误", f"移动失败: {str(e)}")
    
    def delete_files(self):
        """删除文件"""
        selected = self.tree.selection()
        if not selected:
            return
        
        file_list = "\n".join([self.tree.item(item)['values'][0] for item in selected])
        if messagebox.askyesno("确认删除", f"确定要删除以下 {len(selected)} 个项目吗？\n\n{file_list}"):
            try:
                for item in selected:
                    file_name = self.tree.item(item)['values'][0]
                    path = os.path.join(self.current_path, file_name)
                    
                    if os.path.isdir(path):
                        shutil.rmtree(path)
                    else:
                        os.remove(path)
                
                self.refresh_files()
                self.update_status(f"已删除 {len(selected)} 个项目")
            except Exception as e:
                messagebox.showerror("错误", f"删除失败: {str(e)}")
    
    def select_all(self):
        """全选"""
        self.tree.selection_set(self.tree.get_children())
    
    def create_share_link(self):
        """创建分享链接"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要分享的文件")
            return
        
        if not self.current_user:
            messagebox.showerror("错误", "请先登录")
            return
        
        # 生成唯一token
        token = str(uuid.uuid4())
        
        for item in selected:
            file_name = self.tree.item(item)['values'][0]
            file_path = os.path.join(self.current_path, file_name)
            
            # 检查是否已分享
            self.cursor.execute(
                "SELECT id FROM shares WHERE user_id=? AND file_path=?",
                (self.current_user['id'], file_path)
            )
            
            if self.cursor.fetchone():
                # 更新token
                self.cursor.execute(
                    "UPDATE shares SET token=? WHERE user_id=? AND file_path=?",
                    (token, self.current_user['id'], file_path)
                )
            else:
                # 插入新记录
                expires_at = datetime.datetime.now() + datetime.timedelta(days=7)
                self.cursor.execute(
                    "INSERT INTO shares (token, user_id, file_path, expires_at) VALUES (?, ?, ?, ?)",
                    (token, self.current_user['id'], file_path, expires_at)
                )
        
        self.conn.commit()
        
        # 显示分享链接
        share_url = f"http://localhost:8000/share/{token}"
        messagebox.showinfo("分享链接", f"分享链接已创建:\n\n{share_url}\n\n链接有效期7天")
        
        self.refresh_files()
    
    def show_my_shares(self):
        """显示我的分享"""
        if not self.current_user:
            messagebox.showerror("错误", "请先登录")
            return
        
        shares_window = tk.Toplevel(self.root)
        shares_window.title("我的分享")
        shares_window.geometry("800x400")
        shares_window.configure(bg=self.bg_color)
        
        # 创建Treeview显示分享
        tree_frame = tk.Frame(shares_window, bg=self.bg_color)
        tree_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        tree_scroll = tk.Scrollbar(tree_frame)
        tree_scroll.pack(side=tk.RIGHT, fill=tk.Y)
        
        tree = ttk.Treeview(
            tree_frame,
            yscrollcommand=tree_scroll.set,
            columns=("文件", "分享链接", "下载次数", "创建时间", "过期时间"),
            show="headings"
        )
        
        # 设置列
        columns = [("文件", 200), ("分享链接", 300), ("下载次数", 100), ("创建时间", 150), ("过期时间", 150)]
        for col, width in columns:
            tree.heading(col, text=col)
            tree.column(col, width=width)
        
        tree.pack(fill=tk.BOTH, expand=True)
        tree_scroll.config(command=tree.yview)
        
        # 获取分享数据
        self.cursor.execute(
            "SELECT file_path, token, download_count, created_at, expires_at FROM shares WHERE user_id=?",
            (self.current_user['id'],)
        )
        
        for share in self.cursor.fetchall():
            file_name = os.path.basename(share[0])
            share_link = f"http://localhost:8000/share/{share[1]}"
            tree.insert("", "end", values=(
                file_name,
                share_link,
                share[2],
                share[3],
                share[4]
            ))
    
    def search_files(self):
        """搜索文件"""
        keyword = self.search_var.get().strip()
        if not keyword:
            self.refresh_files()
            return
        
        self.tree.delete(*self.tree.get_children())
        
        if not self.current_path or not os.path.exists(self.current_path):
            return
        
        try:
            for root, dirs, files in os.walk(self.current_path):
                for name in dirs + files:
                    if keyword.lower() in name.lower():
                        path = os.path.join(root, name)
                        stats = os.stat(path)
                        mod_time = datetime.datetime.fromtimestamp(stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
                        
                        if os.path.isdir(path):
                            item_type = "文件夹"
                            size = ""
                        else:
                            item_type = "文件"
                            size = self.format_size(stats.st_size)
                        
                        # 显示相对路径
                        rel_path = os.path.relpath(path, self.current_path)
                        self.tree.insert("", "end", values=(
                            rel_path, size, mod_time, item_type, ""
                        ))
        except Exception as e:
            messagebox.showerror("错误", f"搜索失败: {str(e)}")
    
    def show_properties(self):
        """显示文件属性"""
        selected = self.tree.selection()
        if not selected:
            return
        
        file_name = self.tree.item(selected[0])['values'][0]
        file_path = os.path.join(self.current_path, file_name)
        
        try:
            stats = os.stat(file_path)
            size = self.format_size(stats.st_size)
            created = datetime.datetime.fromtimestamp(stats.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
            modified = datetime.datetime.fromtimestamp(stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
            
            if os.path.isdir(file_path):
                file_type = "文件夹"
                # 计算文件夹大小
                total_size = 0
                for dirpath, dirnames, filenames in os.walk(file_path):
                    for f in filenames:
                        fp = os.path.join(dirpath, f)
                        if os.path.exists(fp):
                            total_size += os.path.getsize(fp)
                size = self.format_size(total_size)
            else:
                file_type = "文件"
            
            # 获取分享信息
            share_info = self.get_share_info(file_path)
            
            properties = f"""
文件名称: {file_name}
文件类型: {file_type}
文件大小: {size}
创建时间: {created}
修改时间: {modified}
文件路径: {file_path}
            """
            
            if share_info:
                properties += f"""
分享链接: {share_info['link']}
下载次数: {share_info['download_count']}
                """
            
            messagebox.showinfo("属性", properties)
        except Exception as e:
            messagebox.showerror("错误", f"无法获取属性: {str(e)}")
    
    def change_view(self, mode):
        """切换视图模式"""
        self.view_mode = mode
        # 这里可以实现不同的视图显示方式
        self.update_status(f"切换到{mode}视图")
    
    def go_home(self):
        """返回主目录"""
        if self.current_user:
            self.current_path = os.path.join('user_data', str(self.current_user['id']))
            self.update_path_display()
            self.refresh_files()
    
    def update_path_display(self):
        """更新路径显示"""
        self.path_text.delete('1.0', tk.END)
        self.path_text.insert('1.0', self.current_path)
    
    def update_status(self, message):
        """更新状态栏"""
        timestamp = datetime.datetime.now().strftime('%H:%M:%S')
        self.status_bar.config(text=f"[{timestamp}] {message}")
    
    def show_recent(self):
        """显示最近访问"""
        messagebox.showinfo("最近访问", "此功能正在开发中...")
    
    def show_favorites(self):
        """显示收藏夹"""
        messagebox.showinfo("收藏夹", "此功能正在开发中...")
    
    def show_trash(self):
        """显示回收站"""
        messagebox.showinfo("回收站", "此功能正在开发中...")

def main():
    root = tk.Tk()
    app = FileManager(root)
    root.mainloop()

if __name__ == "__main__":
    # 创建必要的目录
    os.makedirs('user_data', exist_ok=True)
    main()