import tkinter as tk
import tkinter.font as tkfont
import math

# ============ 配色 ============
BG        = "#0f1117"
PANEL     = "#181b24"
PANEL_2   = "#20242f"
AXIS      = "#3a3f52"
TEXT      = "#e6e9f0"
TEXT_DIM  = "#8b93a7"
ACCENT    = "#7aa2f7"
OBJ_COLOR = "#7dcfff"
RAY1      = "#7aa2f7"
RAY2      = "#9ece6a"
RAY3      = "#e0af68"
REAL_IMG  = "#f7768e"
VIRT_IMG  = "#bb9af7"
LENS_CVX  = "#5ccfe6"
LENS_CCV  = "#bb9af7"
FOCUS_CLR = "#e0af68"


class LensDemo:
    def __init__(self, root):
        self.root = root
        self.root.title("凹凸透镜成像演示")
        self.root.geometry("1240x780")
        self.root.minsize(1020, 660)
        self.root.configure(bg=BG)

        # 物理参数（不变）
        self.lens_type = "convex"
        self.f = 180
        self.u = 320
        self.obj_h = 90

        # 布局量（_layout 里算）
        self.lens_x = 600
        self.axis_y = 380
        self.scale = 1.0          # 画布几何缩放系数
        self._resize_job = None

        self._build_ui()
        self.root.update_idletasks()
        self._layout()
        self.redraw()

    # ================= UI =================
    def _build_ui(self):
        # 根用 grid：第0行标题，第1行主体
        self.root.rowconfigure(1, weight=1)
        self.root.columnconfigure(0, weight=1)

        # ---------- 标题栏 ----------
        header = tk.Frame(self.root, bg=BG)
        header.grid(row=0, column=0, sticky="ew", padx=18, pady=(14, 6))
        header.columnconfigure(1, weight=1)

        tk.Label(header, text="凹凸透镜成像演示", bg=BG, fg=TEXT,
                 font=("Microsoft YaHei UI", 18, "bold")).grid(
                 row=0, column=0, sticky="w")
        tk.Label(header, text="Convex / Concave Lens", bg=BG, fg=TEXT_DIM,
                 font=("Segoe UI", 10)).grid(
                 row=0, column=1, sticky="w", padx=10, pady=(8, 0))

        btns = tk.Frame(header, bg=BG)
        btns.grid(row=0, column=2, sticky="e")
        self.type_btns = {}
        for text, val in [("凸透镜", "convex"), ("凹透镜", "concave")]:
            b = tk.Label(btns, text=text, bg=PANEL, fg=TEXT_DIM,
                         font=("Microsoft YaHei UI", 11, "bold"),
                         padx=16, pady=6, cursor="hand2")
            b.pack(side="left", padx=4)
            b.bind("<Button-1>", lambda e, v=val: self._set_type(v))
            self.type_btns[val] = b

        # ---------- 主体：左面板 + 右画布 ----------
        body = tk.Frame(self.root, bg=BG)
        body.grid(row=1, column=0, sticky="nsew", padx=14, pady=6)
        body.rowconfigure(0, weight=1)
        body.columnconfigure(0, weight=0, minsize=260)   # 面板最小宽
        body.columnconfigure(1, weight=1)                # 画布吃剩余

        # 控制面板卡片
        self.card = tk.Frame(body, bg=PANEL)
        self.card.grid(row=0, column=0, sticky="nsw", padx=(0, 12), pady=4)

        tk.Label(self.card, text="参数调节", bg=PANEL, fg=TEXT,
                 font=("Microsoft YaHei UI", 12, "bold")).pack(
                 anchor="w", padx=16, pady=(14, 8))

        self.u_var = tk.IntVar(value=self.u)
        self.f_var = tk.IntVar(value=self.f)
        self.h_var = tk.IntVar(value=self.obj_h)

        self._slider(self.card, "物距  u", 40, 520, self.u_var, self._on_u)
        self._slider(self.card, "焦距  |f|", 80, 300, self.f_var, self._on_f)
        self._slider(self.card, "物高  h", 30, 160, self.h_var, self._on_h)

        tk.Frame(self.card, bg=PANEL_2, height=1).pack(fill="x", padx=16, pady=10)

        # 信息卡
        info = tk.Frame(self.card, bg=PANEL)
        info.pack(fill="x", padx=16, pady=(0, 14))
        tk.Label(info, text="成像信息", bg=PANEL, fg=TEXT,
                 font=("Microsoft YaHei UI", 11, "bold")).pack(anchor="w")
        self.info_kind = tk.Label(info, text="", bg=PANEL, fg=REAL_IMG,
                                  font=("Microsoft YaHei UI", 13, "bold"),
                                  wraplength=240, justify="left")
        self.info_kind.pack(anchor="w", pady=(6, 2))
        self.info_detail = tk.Label(info, text="", bg=PANEL, fg=TEXT_DIM,
                                    font=("Consolas", 10), justify="left",
                                    wraplength=240)
        self.info_detail.pack(anchor="w")

        # 图例
        legend = tk.Frame(self.card, bg=PANEL)
        legend.pack(fill="x", padx=16, pady=(4, 16))
        tk.Label(legend, text="光线图例", bg=PANEL, fg=TEXT,
                 font=("Microsoft YaHei UI", 11, "bold")).pack(anchor="w")
        self._legend_item(legend, RAY1, "平行主光轴 → 过焦点")
        self._legend_item(legend, RAY2, "过光心 → 方向不变")
        self._legend_item(legend, RAY3, "过焦点 → 平行射出")

        # 画布
        self.canvas = tk.Canvas(body, bg="#0a0c10", highlightthickness=0)
        self.canvas.grid(row=0, column=1, sticky="nsew")
        self.canvas.bind("<Configure>", self._on_resize)

    def _legend_item(self, parent, color, text):
        f = tk.Frame(parent, bg=PANEL)
        f.pack(anchor="w", pady=2)
        c = tk.Canvas(f, width=22, height=10, bg=PANEL, highlightthickness=0)
        c.pack(side="left")
        c.create_line(0, 5, 22, 5, fill=color, width=2)
        tk.Label(f, text=text, bg=PANEL, fg=TEXT_DIM,
                 font=("Microsoft YaHei UI", 9)).pack(side="left", padx=6)

    def _slider(self, parent, label, lo, hi, var, cmd):
        wrap = tk.Frame(parent, bg=PANEL)
        wrap.pack(fill="x", padx=16, pady=6)
        top = tk.Frame(wrap, bg=PANEL)
        top.pack(fill="x")
        tk.Label(top, text=label, bg=PANEL, fg=TEXT,
                 font=("Microsoft YaHei UI", 10)).pack(side="left")
        val = tk.Label(top, text=str(var.get()), bg=PANEL, fg=ACCENT,
                       font=("Consolas", 10, "bold"))
        val.pack(side="right")
        s = tk.Scale(wrap, from_=lo, to=hi, orient="horizontal",
                     variable=var, command=lambda v: (cmd(), val.config(text=v)),
                     bg=PANEL, fg=TEXT, troughcolor=PANEL_2,
                     activebackground=ACCENT, highlightthickness=0,
                     bd=0, sliderrelief="flat", showvalue=False)
        s.pack(fill="x", pady=(2, 0))
        wrap.slider = s   # 保存引用，resize 时改长度

    # ================= 事件 =================
    def _set_type(self, val):
        self.lens_type = val
        for k, b in self.type_btns.items():
            b.config(bg=ACCENT, fg="#0f1117") if k == val else \
                b.config(bg=PANEL, fg=TEXT_DIM)
        self.redraw()

    def _on_u(self): self.u = self.u_var.get(); self.redraw()
    def _on_f(self): self.f = self.f_var.get(); self.redraw()
    def _on_h(self): self.obj_h = self.h_var.get(); self.redraw()

    def _on_resize(self, e):
        # 防抖：拖动中不频繁重绘
        if self._resize_job:
            self.root.after_cancel(self._resize_job)
        self._resize_job = self.root.after(30, self._do_resize)

    def _do_resize(self):
        self._resize_job = None
        self._layout()
        self.redraw()

    # ================= 自适应布局 =================
    def _layout(self):
        W = self.canvas.winfo_width() or 900
        H = self.canvas.winfo_height() or 600

        # 画布几何缩放：以 900x600 为基准，限制在 0.75~1.35
        self.scale = max(0.75, min(1.35, min(W / 900, H / 600)))

        # 透镜在画布 52% 宽处；光轴略低于中心
        self.lens_x = W * 0.52
        self.axis_y = H * 0.5 + 20 * self.scale

        # 面板宽度随窗口微调（窗口宽时略宽）
        total_w = self.root.winfo_width() or 1240
        panel_w = max(260, min(320, int(total_w * 0.22)))
        self.card.configure(width=panel_w)

        # 滑杆长度跟随面板
        for child in self.card.winfo_children():
            for sub in child.winfo_children():
                if hasattr(sub, "slider"):
                    sub.slider.configure(length=panel_w - 52)

    # ================= 物理 =================
    def compute(self):
        u, f0 = self.u, self.f
        f = f0 if self.lens_type == "convex" else -f0
        if abs(u - f) < 1e-6:
            return None, None, "不成像（出射平行光）"
        v = u * f / (u - f)
        m = -v / u
        img_h = m * self.obj_h
        size = "放大" if abs(m) > 1.01 else ("等大" if abs(m-1) <= 0.01 else "缩小")
        if v > 0:
            kind = f"倒立 · {size} · 实像"
        else:
            kind = f"正立 · {size} · 虚像"
        return v, img_h, kind

    # ================= 绘制 =================
    def redraw(self):
        c = self.canvas
        c.delete("all")
        W = c.winfo_width() or 900
        H = c.winfo_height() or 600
        cy = self.axis_y
        lx = self.lens_x
        s = self.scale

        # 背景渐变
        for i in range(0, H, 4):
            t = i / H
            r = int(10 + 6*t); g = int(12 + 8*t); b = int(16 + 14*t)
            c.create_rectangle(0, i, W, i+4, outline="",
                               fill=f"#{r:02x}{g:02x}{b:02x}", tags="bg")

        # 主光轴
        c.create_line(0, cy, W, cy, fill=AXIS, width=1, dash=(2, 6))
        c.create_text(W-14, cy-14*s, text="主光轴", fill=TEXT_DIM, anchor="e",
                      font=("Microsoft YaHei UI", max(8, int(9*s))))

        # 焦点
        for side in (-1, 1):
            for k, name in [(1, "F"), (2, "2F")]:
                fx = lx + side * k * self.f * s
                if 20 < fx < W-20:
                    c.create_oval(fx-4*s, cy-4*s, fx+4*s, cy+4*s,
                                  fill=FOCUS_CLR, outline="")
                    c.create_text(fx, cy+16*s, text=name, fill=FOCUS_CLR,
                                  font=("Segoe UI", max(8, int(9*s)), "bold"))

        # 透镜（底层）
        self._draw_lens(c, lx, cy, s)

        # 光线（中层）
        obj_x = lx - self.u * s
        obj_top = cy - self.obj_h * s
        self._draw_rays(c, lx, cy, obj_x, obj_top, W, s)

        # 物体/像（顶层）
        if 10 < obj_x < W-10:
            self._draw_arrow(c, obj_x, cy, obj_top, OBJ_COLOR, "物", s)

        v, img_h, kind = self.compute()
        if v is not None and img_h is not None:
            img_x = lx + v * s
            if -400 < img_x < W + 400:
                color = REAL_IMG if v > 0 else VIRT_IMG
                img_y = cy - img_h * s
                self._draw_arrow(c, img_x, cy, img_y, color,
                                 "实像" if v > 0 else "虚像",
                                 dashed=(v < 0), scale=s)

        # 透镜标签
        c.create_text(lx, cy - 158*s,
                      text="凸透镜" if self.lens_type=="convex" else "凹透镜",
                      fill=LENS_CVX if self.lens_type=="convex" else LENS_CCV,
                      font=("Microsoft YaHei UI", max(9, int(11*s)), "bold"))

        self._update_info(v, img_h, kind)

    def _draw_lens(self, c, lx, cy, s):
        h = 130 * s
        if self.lens_type == "convex":
            pts = [
                lx, cy - h,
                lx + 10*s, cy - h*0.55, lx + 14*s, cy,
                lx + 10*s, cy + h*0.55, lx, cy + h,
                lx - 10*s, cy + h*0.55, lx - 14*s, cy,
                lx - 10*s, cy - h*0.55,
            ]
            edge, fill = LENS_CVX, "#0f2a30"
        else:
            pts = [
                lx - 10*s, cy - h, lx + 10*s, cy - h,
                lx + 5*s, cy - h*0.5, lx + 5*s, cy + h*0.5,
                lx + 10*s, cy + h, lx - 10*s, cy + h,
                lx - 5*s, cy + h*0.5, lx - 5*s, cy - h*0.5,
            ]
            edge, fill = LENS_CCV, "#221a2e"

        c.create_polygon(*pts, smooth=True, fill=fill, outline="")
        c.create_polygon(*pts, smooth=True, fill="", outline=edge, width=max(1, int(2*s)))

    def _draw_arrow(self, c, x, base_y, tip_y, color, label, scale=1.0,
                    dashed=False):
        w_main = max(2, int(3*scale))
        w_out  = max(4, int(6*scale))
        c.create_line(x, base_y, x, tip_y, fill="#000000", width=w_out,
                      dash=(7, 5) if dashed else ())
        c.create_line(x, base_y, x, tip_y, fill=color, width=w_main,
                      dash=(7, 5) if dashed else ())
        d = 1 if tip_y < base_y else -1
        a = 9 * scale
        c.create_polygon(x, tip_y - d*2*scale, x-a, tip_y + d*a,
                         x+a, tip_y + d*a, fill="#000000", outline="")
        c.create_polygon(x, tip_y - d*1*scale, x-a*0.75, tip_y + d*a*0.8,
                         x+a*0.75, tip_y + d*a*0.8, fill=color, outline="")
        ly = tip_y - 20*scale if tip_y < base_y else tip_y + 20*scale
        c.create_text(x, ly, text=label, fill=color,
                      font=("Microsoft YaHei UI", max(8, int(10*scale)), "bold"))

    def _draw_rays(self, c, lx, cy, obj_x, obj_top, W, s):
        end_x = W + 200
        gap = 16 * s
        f = self.f * s

        def seg(x1, y1, x2, y2, color, dash=None):
            if x1 > x2:
                x1, y1, x2, y2 = x2, y2, x1, y1
            if x1 < lx - gap and x2 > lx + gap:
                t1 = (lx - gap - x1) / (x2 - x1)
                t2 = (lx + gap - x1) / (x2 - x1)
                c.create_line(x1, y1, x1 + (x2-x1)*t1, y1 + (y2-y1)*t1,
                              fill=color, width=max(1, int(1*s)), dash=dash)
                c.create_line(x1 + (x2-x1)*t2, y1 + (y2-y1)*t2, x2, y2,
                              fill=color, width=max(1, int(1*s)), dash=dash)
            else:
                c.create_line(x1, y1, x2, y2, fill=color,
                              width=max(1, int(1*s)), dash=dash)

        # 光线1
        seg(obj_x, obj_top, lx, obj_top, RAY1)
        if self.lens_type == "convex":
            fx = lx + f
            if abs(fx - lx) > 1e-3:
                slope = (cy - obj_top) / (fx - lx)
                y_end = obj_top + slope * (end_x - lx)
                seg(lx, obj_top, end_x, y_end, RAY1)
        else:
            fx = lx - f
            dx, dy = lx - fx, obj_top - cy
            n = math.hypot(dx, dy) or 1
            y_end = obj_top + (dy/n)/(dx/n) * (end_x - lx) if dx else obj_top
            seg(lx, obj_top, end_x, y_end, RAY1)
            c.create_line(lx, obj_top, fx, cy, fill=RAY1,
                          width=max(1, int(1*s)), dash=(3, 5))

        # 光线2
        dx, dy = lx - obj_x, cy - obj_top
        if dx:
            slope = dy / dx
            y_end = cy + slope * (end_x - lx)
            seg(obj_x, obj_top, end_x, y_end, RAY2)

        # 光线3
        if self.lens_type == "convex":
            fx = lx - f
            if fx != obj_x:
                slope = (cy - obj_top) / (fx - obj_x)
                y_l = obj_top + slope * (lx - obj_x)
                seg(obj_x, obj_top, lx, y_l, RAY3)
                seg(lx, y_l, end_x, y_l, RAY3)
        else:
            fx = lx + f
            if fx != obj_x:
                slope = (cy - obj_top) / (fx - obj_x)
                y_l = obj_top + slope * (lx - obj_x)
                seg(obj_x, obj_top, lx, y_l, RAY3)
                seg(lx, y_l, end_x, y_l, RAY3)
                c.create_line(lx, y_l, fx, cy, fill=RAY3,
                              width=max(1, int(1*s)), dash=(3, 5))

    def _update_info(self, v, img_h, kind):
        self.info_kind.config(text=kind,
                              fg=REAL_IMG if (v is not None and v > 0) else VIRT_IMG)
        if v is None:
            self.info_detail.config(
                text=f"u = {self.u}\nf = {self.f}\n物高 = {self.obj_h}")
        else:
            m = abs(v / self.u)
            pos = "右侧" if v > 0 else "左侧(虚)"
            self.info_detail.config(
                text=(f"u = {self.u}    f = {self.f}\n"
                      f"v = {v:.1f}  ({pos})\n"
                      f"像高 = {abs(img_h):.1f}\n"
                      f"放大率 |m| = {m:.2f}"))


def main():
    root = tk.Tk()
    try:
        root.tk.call("tk", "scaling", 1.2)
    except Exception:
        pass
    LensDemo(root)
    root.mainloop()


if __name__ == "__main__":
    main()