import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import random
import time
import threading

class LotteryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("🏮古风随机抽签点名器")
        self.root.geometry("720x520")
        self.root.resizable(False, False)

        # 名单数据
        self.name_list = []
        self.is_running = False

        # 画布绘制古风渐变背景
        self.canvas = tk.Canvas(root, width=720, height=520, highlightthickness=0)
        self.canvas.pack()
        self.draw_gradient()

        # 标题
        self.title_label = tk.Label(
            root, text="古风抽签点名器",
            font=("楷体", 28, "bold"),
            fg="#f8eada", bg="#594c42"
        )
        self.title_label.place(x=220, y=30)

        # 抽签结果大字
        self.result_var = tk.StringVar(value="静待开签")
        self.result_label = tk.Label(
            root, textvariable=self.result_var,
            font=("楷体", 42, "bold"),
            fg="#d65c5c", bg="#594c42", width=12
        )
        self.result_label.place(x=160, y=110)

        # 左侧名单面板
        frame_left = tk.Frame(root, bg="#706053")
        frame_left.place(x=30, y=220, width=320, height=240)

        tk.Label(frame_left, text="📜名单名录", font=("楷体",14), fg="#f8eada", bg="#706053").pack()
        self.listbox = tk.Listbox(frame_left, font=("楷体",12), width=22, height=10, bg="#f8f2e4", fg="#3a3029")
        self.listbox.pack(pady=5)

        # 添加名字输入框
        self.add_entry = ttk.Entry(root, font=("楷体",12), width=16)
        self.add_entry.place(x=30, y=470)

        ttk.Button(root, text="添加", command=self.add_name).place(x=170, y=468)
        ttk.Button(root, text="删除选中", command=self.del_name).place(x=230, y=468)

        # 右侧按钮面板
        frame_right = tk.Frame(root, bg="#706053")
        frame_right.place(x=380, y=220, width=300, height=240)

        self.start_btn = tk.Button(
            frame_right, text="🎲开始抽签",
            font=("楷体",16,"bold"),
            width=12, height=2,
            bg="#8c4c42", fg="#f8eada",
            command=self.start_lottery
        )
        self.start_btn.pack(pady=12)

        ttk.Button(frame_right, text="清空全部名单", command=self.clear_all).pack(pady=4)
        ttk.Button(frame_right, text="导入文本名单", command=self.load_file).pack(pady=4)
        ttk.Button(frame_right, text="保存名单", command=self.save_file).pack(pady=4)

    # 古风渐变：深棕→浅茶
    def draw_gradient(self):
        r1, g1, b1 = 69, 58, 50
        r2, g2, b2 = 112, 96, 83
        height = 520
        for y in range(height):
            ratio = y / height
            r = int(r1 * (1 - ratio) + r2 * ratio)
            g = int(g1 * (1 - ratio) + g2 * ratio)
            b = int(b1 * (1 - ratio) + b2 * ratio)
            color = f"#{r:02x}{g:02x}{b:02x}"
            self.canvas.create_line(0, y, 720, y, fill=color)

    def add_name(self):
        name = self.add_entry.get().strip()
        if name and name not in self.name_list:
            self.name_list.append(name)
            self.listbox.insert(tk.END, name)
            self.add_entry.delete(0, tk.END)

    def del_name(self):
        sel = self.listbox.curselection()
        if sel:
            idx = sel[0]
            self.name_list.pop(idx)
            self.listbox.delete(idx)

    def clear_all(self):
        self.name_list.clear()
        self.listbox.delete(0, tk.END)
        self.result_var.set("静待开签")

    def load_file(self):
        path = filedialog.askopenfilename(filetypes=[("文本文件","*.txt")])
        if not path:
            return
        try:
            with open(path, "r", encoding="utf-8") as f:
                lines = f.readlines()
            for line in lines:
                n = line.strip()
                if n and n not in self.name_list:
                    self.name_list.append(n)
                    self.listbox.insert(tk.END, n)
        except Exception as e:
            messagebox.showerror("错误", f"读取失败：{e}")

    def save_file(self):
        path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("文本文件","*.txt")])
        if not path:
            return
        with open(path, "w", encoding="utf-8") as f:
            f.write("\n".join(self.name_list))
        messagebox.showinfo("成功", "名单已保存！")

    # 抽签滚动动画
    def start_lottery(self):
        if self.is_running:
            self.is_running = False
            self.start_btn.config(text="🎲开始抽签", bg="#8c4c42")
            return

        if len(self.name_list) == 0:
            messagebox.showwarning("提醒", "请先添加名单！")
            return

        self.is_running = True
        self.start_btn.config(text="🛑停止抽签", bg="#a83c3c")

        def roll():
            while self.is_running:
                random_name = random.choice(self.name_list)
                self.result_var.set(random_name)
                time.sleep(0.06)
        threading.Thread(target=roll, daemon=True).start()

if __name__ == "__main__":
    window = tk.Tk()
    app = LotteryApp(window)
    window.mainloop()