File size: 44,428 Bytes
1a4f459
 
2531a51
 
b91600d
b023ca4
1a4f459
 
eaf8a72
 
fa65f84
 
 
1a4f459
b023ca4
 
eaf8a72
 
2531a51
eaf8a72
2531a51
 
8298afb
 
2531a51
 
eaf8a72
 
c23f217
1a4f459
8298afb
91ddf5f
 
 
 
 
 
 
 
8298afb
91ddf5f
 
 
 
 
 
aafd67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa65f84
6c40522
af56508
 
eaf8a72
 
 
fa65f84
515c03a
b023ca4
eaf8a72
 
8298afb
 
 
 
6c40522
 
 
aafd67d
 
6c40522
aafd67d
 
 
 
 
 
 
 
 
 
 
6c40522
aafd67d
6c40522
aafd67d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c40522
 
eaf8a72
54dd3bf
b023ca4
58ac763
54dd3bf
 
 
 
b023ca4
58ac763
b023ca4
58ac763
d6f1b28
b023ca4
8298afb
58ac763
d6f1b28
b023ca4
 
8298afb
58ac763
706540f
58ac763
54dd3bf
 
b023ca4
 
58ac763
 
706540f
340f0c7
58ac763
706540f
 
 
 
 
 
 
 
04b4614
 
 
58ac763
04b4614
58ac763
706540f
58ac763
706540f
58ac763
7071f35
 
706540f
7071f35
 
340f0c7
 
7071f35
58ac763
706540f
4c0c588
58ac763
706540f
340f0c7
58ac763
706540f
 
 
 
 
 
 
 
04b4614
58ac763
706540f
58ac763
 
 
706540f
 
58ac763
 
 
04b4614
 
 
 
7071f35
 
706540f
04b4614
 
340f0c7
 
7071f35
58ac763
706540f
4c0c588
b023ca4
afe3dd1
 
 
340f0c7
 
afe3dd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ed8d69
7071f35
 
 
 
 
501ec50
340f0c7
 
7071f35
afe3dd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04997f2
 
 
 
 
 
 
501ec50
 
afe3dd1
 
 
04997f2
afe3dd1
 
 
340f0c7
afe3dd1
655c7b4
 
e16a815
340f0c7
 
655c7b4
 
 
 
e16a815
 
 
 
655c7b4
e16a815
 
655c7b4
 
 
 
 
 
 
 
 
 
 
 
 
 
e16a815
655c7b4
 
 
 
 
 
 
 
340f0c7
 
655c7b4
 
 
 
 
 
 
 
 
 
 
 
 
 
5eae97b
655c7b4
 
e16a815
 
655c7b4
845230e
 
 
 
 
 
655c7b4
 
 
 
845230e
655c7b4
845230e
655c7b4
 
 
e16a815
 
 
655c7b4
8ed8d69
 
 
 
340f0c7
 
8ed8d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340f0c7
144b79c
8ed8d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144b79c
 
8ed8d69
 
c1316e0
 
 
 
 
 
afe3dd1
706540f
 
 
 
 
 
 
 
655c7b4
 
 
 
 
 
 
 
e16a815
 
 
 
 
 
8ed8d69
 
 
 
 
 
 
 
73c98ae
 
 
 
 
 
 
8ed8d69
b023ca4
eaf8a72
1a4f459
8298afb
eaf8a72
b91600d
 
eaf8a72
d8db146
1a4f459
fa65f84
91ddf5f
eaf8a72
fa65f84
 
73c98ae
 
fa65f84
4c0c588
af56508
1a4f459
fa65f84
b023ca4
 
 
b91600d
 
 
 
d41e41d
87f7435
d41e41d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e16a815
 
 
d41e41d
 
 
 
 
 
e16a815
 
d41e41d
 
 
 
 
 
87f7435
d41e41d
 
 
87f7435
 
d41e41d
 
afe3dd1
58ac763
 
285aa9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58ac763
 
 
 
706540f
 
 
 
04b4614
8f71c34
04b4614
8f71c34
 
58ac763
 
 
 
 
 
 
 
706540f
 
 
 
8f71c34
 
 
 
58ac763
 
 
 
 
afe3dd1
87f7435
285aa9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afe3dd1
 
 
 
 
 
 
 
 
 
 
87f7435
afe3dd1
 
 
 
 
 
87f7435
afe3dd1
 
 
87f7435
 
afe3dd1
b91600d
8ed8d69
 
87f7435
aeb2168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ed8d69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87f7435
8ed8d69
 
87f7435
 
8ed8d69
 
b91600d
655c7b4
6c40522
 
f1dbd4d
c23f217
d6f1b28
b91600d
c23f217
 
b1cd099
b91600d
d6f1b28
b91600d
b1cd099
b91600d
afe3dd1
6c40522
c23f217
d6f1b28
eaf8a72
afe3dd1
73c98ae
 
 
340f0c7
706540f
 
c1316e0
340f0c7
 
afe3dd1
340f0c7
 
b1cd099
340f0c7
655c7b4
e16a815
 
655c7b4
340f0c7
8ed8d69
 
340f0c7
8ed8d69
 
afe3dd1
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
import gradio as gr
import pandas as pd
import json
import os
import math
import matplotlib.pyplot as plt
from datetime import datetime

# --- 系統變數與檔案設定 ---
COMPANY_NAME = "RZF Laser Tech"
CONFIG_JSON = "rzf_config.json"
ORDERS_CSV = "rzf_orders.csv"
DEFAULT_WAVELENGTHS = ["650nm", "532nm", "405nm", "850nm"]

# --- 1. 核心邏輯與計算函數 ---

def load_rzf_config():
    if os.path.exists(CONFIG_JSON):
        try:
            with open(CONFIG_JSON, "r", encoding="utf-8") as f:
                data = json.load(f)
                return data.get("wavelengths", DEFAULT_WAVELENGTHS)
        except: 
            return DEFAULT_WAVELENGTHS
    return DEFAULT_WAVELENGTHS

def save_rzf_config(w_list):
    with open(CONFIG_JSON, "w", encoding="utf-8") as f:
        json.dump({"company": COMPANY_NAME, "wavelengths": w_list, "last_update": str(datetime.now())}, f, indent=4, ensure_ascii=False)

# 獲取訂單報表資料
def get_order_data():
    if os.path.exists(ORDERS_CSV):
        try:
            return pd.read_csv(ORDERS_CSV, encoding="utf-8-sig")
        except:
            return pd.DataFrame({"錯誤": ["無法讀取 CSV 檔案"]})
    return pd.DataFrame(columns=["提示"], data=[["目前尚無訂單紀錄"]])

# 獲取備份檔案路徑
def get_backup_files():
    files = []
    if os.path.exists(ORDERS_CSV): files.append(ORDERS_CSV)
    if os.path.exists(CONFIG_JSON): files.append(CONFIG_JSON)
    return files

# --- 新增:取得光斑樣式的 SVG 圖示 ---
def get_spot_icon(style):
    base_svg = '<svg width="80" height="80" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" style="background:#263238; border-radius:10px; border: 2px solid #37474F; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">'
    # 科技感背景格線
    grid = '<line x1="50" y1="0" x2="50" y2="100" stroke="#37474F" stroke-width="1"/><line x1="0" y1="50" x2="100" y2="50" stroke="#37474F" stroke-width="1"/>'
    
    if style == "點狀":
        content = '<circle cx="50" cy="50" r="14" fill="rgba(255, 23, 68, 0.3)"/><circle cx="50" cy="50" r="5" fill="#FF1744"/>'
    elif style == "線狀":
        content = '<rect x="10" y="46" width="80" height="8" rx="4" fill="rgba(255, 23, 68, 0.3)"/><rect x="15" y="48" width="70" height="4" rx="2" fill="#FF1744"/>'
    elif style == "十字線":
        content = '<rect x="46" y="10" width="8" height="80" rx="4" fill="rgba(255, 23, 68, 0.3)"/><rect x="10" y="46" width="80" height="8" rx="4" fill="rgba(255, 23, 68, 0.3)"/><rect x="48" y="15" width="4" height="70" rx="2" fill="#FF1744"/><rect x="15" y="48" width="70" height="4" rx="2" fill="#FF1744"/>'
    elif style == "DOE":
        content = ""
        for x in [25, 50, 75]:
            for y in [25, 50, 75]:
                content += f'<circle cx="{x}" cy="{y}" r="6" fill="rgba(255, 23, 68, 0.3)"/><circle cx="{x}" cy="{y}" r="2.5" fill="#FF1744"/>'
    else:
        content = '<circle cx="50" cy="50" r="5" fill="#FF1744"/>'
        
    return base_svg + grid + content + '</svg>'

def submit_rzf_order(w, p, s, q, focus, spot, coaxial, ellipse, dim_d, dim_l, wire_m, wire_l, wire_c, connector):
    if not w: return "❌ 錯誤:未選取波長規格", "⚠️ 尚未提交有效訂單"
    if focus < 0: return "❌ 錯誤:焦距不能為負值!", "⚠️ 尚未提交有效訂單"
    
    new_data = {
        "訂單編號": datetime.now().strftime("RZF%Y%m%d%H%M%S"),
        "提交時間": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "波長": w, "功率(mW)": p, "光斑樣式": s, "數量": q,
        "焦距(mm)": focus, "光點大小/長度": spot, "同軸度(mRad/°)": coaxial, "橢圓率": ellipse,
        "機構尺寸(D*L)": f"{dim_d}*{dim_l}", "線材材質": wire_m, "線材長度(mm)": wire_l, "線材顏色": wire_c, "連接器規格": connector
    }
    df = pd.DataFrame([new_data])
    if not os.path.isfile(ORDERS_CSV): 
        df.to_csv(ORDERS_CSV, index=False, encoding="utf-8-sig")
    else: 
        df.to_csv(ORDERS_CSV, mode='a', index=False, header=False, encoding="utf-8-sig")
        
    order_msg = f"🚀 {COMPANY_NAME} 訂單已受理!\n編號:{new_data['訂單編號']}"
    
    # 產生對應光斑 SVG 圖示
    svg_icon = get_spot_icon(s)
    
    # 產生圖文並茂且包含表格的規格說明
    spec_summary = f"""
### 📝 最新訂單規格書 (編號:`{new_data['訂單編號']}`)

<div style="display: flex; align-items: center; gap: 20px; padding: 15px; background: #f8f9fa; border-radius: 10px; margin-bottom: 20px; border: 1px solid #e0e0e0;">
    <div>{svg_icon}</div>
    <div>
        <h3 style="margin: 0; color: #1976D2;">光斑樣式:{s}雷射</h3>
        <p style="margin: 5px 0 0 0; color: #555; font-size: 14px;">中心波長:<b>{w}</b> &nbsp;|&nbsp; 輸出功率:<b>{p} mW</b></p>
    </div>
</div>

#### 📊 詳細規格參數表

| 參數類別 | 項目名稱 | 規格設定 |
| :--- | :--- | :--- |
| 🔦 **光學核心** | 雷射波長 | **{w}** |
| | 輸出功率 | **{p} mW** |
| | 光斑樣式 | **{s}** |
| | 焦距 | {focus} mm |
| | 光點大小/長度 | {spot} |
| | 同軸度 | {coaxial} |
| | 橢圓率 | {ellipse} |
| 🔩 **機構與線材** | 機構尺寸 (D×L) | {dim_d} × {dim_l} mm |
| | 線材材質 | {wire_m} |
| | 線材長度 | {wire_l} mm |
| | 線材顏色 | <span style="display:inline-block; width:12px; height:12px; background-color:{wire_c}; border-radius:50%; border:1px solid #999; vertical-align:middle; margin-right:4px;"></span> {wire_c} |
| | 連接器規格 | {connector if connector else '未指定'} |
| 📦 **訂購資訊** | 訂購數量 | **{q}** |
| | 提交時間 | {new_data['提交時間']} |
"""
    return order_msg, spec_summary

# --- 同軸度與繪圖邏輯 ---

def draw_coaxiality_plot(distance, r):
    # 將繪圖顯示用的數值改為「度數」
    rad = math.atan(r / distance)
    deg = math.degrees(rad)
    
    fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
    ax.set_title(f"{COMPANY_NAME} - Coaxiality Diagram", fontsize=12)
    ax.set_xlim(-0.1 * distance, 1.1 * distance)
    ax.set_ylim(-0.2 * r, 1.2 * r)
    ax.axis('off')
    
    # 繪製三角形
    triangle_coords = [[0, 0], [distance, 0], [distance, r]]
    poly = plt.Polygon(triangle_coords, closed=True, facecolor='#F1F8E9', edgecolor='#388E3C', linewidth=2)
    ax.add_patch(poly)
    
    # 標註參數
    ax.plot([0, distance], [0, r], color='#D32F2F', linestyle='--', linewidth=1.5)
    ax.text(distance / 2, -0.1 * r, f"L = {distance:.2f} mm", ha='center', color='#2E7D32')
    ax.text(distance * 1.05, r / 2, f"r = {r:.3f} mm", va='center', rotation=90, color='#2E7D32')
    # 圖表上的標註改為顯示度數
    ax.text(distance * 0.15, r * 0.05, f"θ ≈ {deg:.4f}°", fontsize=11, color='#C62828', fontweight='bold')
    
    plt.tight_layout()
    return fig

def calc_angle_from_offset(distance, dist_unit, offset, off_type, off_unit):
    if distance <= 0: return "❌ 距離必須大於 0", None, gr.update()
    
    # 統一將測試距離轉換為 mm 計算
    if dist_unit == "公分 (cm)":
        distance_mm = distance * 10.0
    elif dist_unit == "公尺 (m)":
        distance_mm = distance * 1000.0
    else:
        distance_mm = distance
        
    # 統一將偏移量轉換為 mm 計算
    offset_mm = offset if off_unit == "毫米 (mm)" else offset / 1000.0
    
    # 半徑直接使用,直徑則除以 2
    r = offset_mm if off_type == "半徑 (Radius)" else offset_mm / 2.0
    
    rad = math.atan(r / distance_mm)
    deg = math.degrees(rad)
    mrad = (r / distance_mm) * 1000
    
    text_result = (
        f"### 💡 偏移量計算角度:\n"
        f"- 輸入條件: 距離 **{distance} {dist_unit}** ({distance_mm:.2f} mm), 偏移 **{offset} {off_unit}** ({off_type})\n"
        f"- 實際半徑偏移 (r): **{r:.4f} mm**\n"
        f"- 偏移角度: **{deg:.4f}°**\n"
        f"- 同軸度: **{mrad:.4f} mRad**\n\n"
        f"*(✨ 同軸度參數已自動同步至「產品訂購」表單!)*"
    )

    fig = draw_coaxiality_plot(distance_mm, r)
    return text_result, fig, f"{mrad:.4f} mRad"

def calc_offset_from_angle(distance, dist_unit, angle, ang_type):
    if distance <= 0: return "❌ 距離必須大於 0", None, gr.update()
    
    # 統一將測試距離轉換為 mm 計算
    if dist_unit == "公分 (cm)":
        distance_mm = distance * 10.0
    elif dist_unit == "公尺 (m)":
        distance_mm = distance * 1000.0
    else:
        distance_mm = distance
        
    # 根據角度單位計算半徑長度 (mm)
    if ang_type == "mRad":
        r = (angle / 1000.0) * distance_mm
        mrad = angle
    else:
        rad = math.radians(angle)
        r = math.tan(rad) * distance_mm
        mrad = (r / distance_mm) * 1000
        
    diameter = r * 2
    
    # 轉換為 um 方便顯示
    r_um = r * 1000
    diameter_um = diameter * 1000
    
    text_result = (
        f"### 💡 角度計算偏移量:\n"
        f"- 輸入條件: 距離 **{distance} {dist_unit}** ({distance_mm:.2f} mm), 角度 **{angle}** ({ang_type})\n"
        f"- **半徑長度** (半徑偏移): **{r:.4f} mm** / **{r_um:.2f} µm**\n"
        f"- **直徑長度** (直徑偏移): **{diameter:.4f} mm** / **{diameter_um:.2f} µm**\n"
        f"- 等效 mRad: **{mrad:.4f} mRad**\n\n"
        f"*(✨ 同軸度參數已自動同步至「產品訂購」表單!)*"
    )

    fig = draw_coaxiality_plot(distance_mm, r)
    return text_result, fig, f"{mrad:.4f} mRad"

# --- 光束發散 (Beam Divergence) 邏輯 ---

def calculate_and_plot_divergence(z1, d1, z2, d2, size_type):
    if z1 >= z2: return "❌ 錯誤:第二個位置 (z2) 必須大於第一個位置 (z1)", None, gr.update()
    if d1 < 0 or d2 < 0: return "❌ 錯誤:光斑尺寸不能為負數", None, gr.update()

    delta_L = z2 - z1
    
    # 轉換為半徑 (作為直角三角形的高度)
    r1 = d1 if size_type == "半徑 (Radius)" else d1 / 2.0
    r2 = d2 if size_type == "半徑 (Radius)" else d2 / 2.0
    
    delta_r = r2 - r1
    
    # 計算半角 (Half-Angle)
    half_rad = math.atan(delta_r / delta_L)
    half_deg = math.degrees(half_rad)
    half_mrad = (delta_r / delta_L) * 1000

    # 計算全角 (Full-Angle)
    full_rad = half_rad * 2
    full_deg = half_deg * 2
    full_mrad = half_mrad * 2

    # 結果文字
    text_result = (
        f"### 💡 光束發散計算結果:\n"
        f"- 測量距離差 (${{\\Delta L}}$): **{delta_L:.2f} mm**\n"
        f"- 半徑尺寸差 (${{\\Delta r}}$): **{delta_r:.4f} mm**\n\n"
        f"#### 📐 角度結果\n"
        f"- **半角發散 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°** / **{half_mrad:.4f} mRad**\n"
        f"- **全角發散 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°** / **{full_mrad:.4f} mRad**\n\n"
        f"*(✨ 光點大小已自動同步至「產品訂購」表單!)*"
    )

    # 繪製圖表
    fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
    ax.set_title(f"{COMPANY_NAME} - Beam Divergence", fontsize=12)

    # 繪製光束形狀 (多邊形)
    beam_coords = [[z1, r1], [z2, r2], [z2, -r2], [z1, -r1]]
    poly = plt.Polygon(beam_coords, closed=True, facecolor='#FFF9C4', edgecolor='#FBC02D', linewidth=2, alpha=0.6)
    ax.add_patch(poly)

    # 畫中心線
    ax.plot([z1 - delta_L*0.1, z2 + delta_L*0.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)

    # 標註參數
    ax.plot([z1, z1], [-r1, r1], color='#1976D2', linewidth=2)
    ax.plot([z2, z2], [-r2, r2], color='#1976D2', linewidth=2)
    ax.text(z1, r1 * 1.1 + 0.1, f"size 1: {d1}", ha='center', color='#1976D2', fontsize=9)
    ax.text(z2, r2 * 1.1 + 0.1, f"size 2: {d2}", ha='center', color='#1976D2', fontsize=9)
    
    # 標註距離長度 (加入絕對偏移量與 va='top' 避免與標示線重疊)
    dim_y = -max(r1, r2) * 1.2 - 0.2
    ax.plot([z1, z2], [dim_y, dim_y], color='#555', linestyle='-', linewidth=1)
    ax.plot([z1, z1], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
    ax.plot([z2, z2], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
    ax.text((z1 + z2) / 2, dim_y - 0.1, f"ΔL = {delta_L:.1f} mm", ha='center', va='top', color='#555')

    # 標註角度 (顯示全角與 mRad)
    ax.text(z2 * 1.02, r2 / 2, f"Θ ≈ {full_deg:.4f}°\n({full_mrad:.4f} mRad)", color='#D32F2F', fontweight='bold', fontsize=11)
    
    # 調整圖表邊界
    ax.set_xlim(z1 - delta_L*0.2, z2 + delta_L*0.3)
    ax.set_ylim(dim_y - 0.8, max(r1, r2)*1.5 + 0.5)
    ax.axis('off')

    plt.tight_layout()
    return text_result, fig, str(d2)

# --- 光束焦距收斂 (Focus Beam Divergence) 邏輯 ---

def calculate_and_plot_focus_divergence(focal_length, dist_unit, d1, d2, spot_unit, size_type):
    if focal_length <= 0: return "❌ 錯誤:焦距必須大於 0", None, gr.update(), gr.update()
    if d1 < 0 or d2 < 0: return "❌ 錯誤:光斑尺寸不能為負數", None, gr.update(), gr.update()

    # 單位轉換至 mm
    focal_length_mm = focal_length * 10.0 if dist_unit == "公分 (cm)" else (focal_length * 1000.0 if dist_unit == "公尺 (m)" else focal_length)

    # 將光斑尺寸統一轉換至 mm
    d1_mm = d1 if spot_unit == "毫米 (mm)" else d1 / 1000.0
    d2_mm = d2 if spot_unit == "毫米 (mm)" else d2 / 1000.0

    # 轉換為半徑 (作為直角三角形的高度)
    r1 = d1_mm if size_type == "半徑 (Radius)" else d1_mm / 2.0
    r2 = d2_mm if size_type == "半徑 (Radius)" else d2_mm / 2.0
    
    delta_r = r1 - r2
    
    # 計算半角 (Half-Angle)
    half_rad = math.atan(delta_r / focal_length_mm)
    half_deg = math.degrees(half_rad)
    half_mrad = (delta_r / focal_length_mm) * 1000

    # 計算全角 (Full-Angle)
    full_rad = half_rad * 2
    full_deg = half_deg * 2
    full_mrad = half_mrad * 2

    # 結果文字
    unit_label = "mm" if spot_unit == "毫米 (mm)" else "µm"
    text_result = (
        f"### 💡 光束焦距收斂計算結果:\n"
        f"- 焦距 ($L$): **{focal_length_mm:.2f} mm**\n"
        f"- 雷射出光半徑 ($r_1$): **{r1:.4f} mm**\n"
        f"- 焦距光斑半徑 ($r_2$): **{r2:.4f} mm**\n"
        f"- 半徑收斂差 ($r_1 - r_2$): **{delta_r:.4f} mm**\n\n"
        f"#### 📐 收斂角度結果\n"
        f"- **半收斂角 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°** / **{half_mrad:.4f} mRad**\n"
        f"- **全收斂角 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°** / **{full_mrad:.4f} mRad**\n\n"
        f"*(✨ 焦距與光點大小已自動同步至「產品訂購」表單!)*"
    )

    # 繪製圖表
    fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
    ax.set_title(f"{COMPANY_NAME} - Focus Beam Convergence", fontsize=12)

    # 繪製光束形狀 (多邊形)
    beam_coords = [[0, r1], [focal_length_mm, r2], [focal_length_mm, -r2], [0, -r1]]
    poly = plt.Polygon(beam_coords, closed=True, facecolor='#E3F2FD', edgecolor='#1976D2', linewidth=2, alpha=0.6)
    ax.add_patch(poly)

    # 畫中心線
    ax.plot([-focal_length_mm*0.1, focal_length_mm*1.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)

    # 標註參數 (避免使用中文體,解決伺服器顯示框框的問題)
    ax.plot([0, 0], [-r1, r1], color='#388E3C', linewidth=2)
    ax.plot([focal_length_mm, focal_length_mm], [-r2, r2], color='#388E3C', linewidth=2)
    ax.text(0, r1 * 1.1 + 0.1, f"d1: {d1} {unit_label}", ha='center', color='#388E3C', fontsize=9)
    ax.text(focal_length_mm, r2 * 1.1 + 0.1, f"d2: {d2} {unit_label}", ha='center', color='#388E3C', fontsize=9)
    
    # 標註焦距長度 (加入絕對偏移量與 va='top' 避免與標示線重疊)
    dim_y = -max(r1, r2) * 1.2 - 0.2
    ax.plot([0, focal_length_mm], [dim_y, dim_y], color='#555', linestyle='-', linewidth=1)
    ax.plot([0, 0], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
    ax.plot([focal_length_mm, focal_length_mm], [dim_y + 0.1, dim_y - 0.1], color='#555', linewidth=1)
    ax.text(focal_length_mm / 2, dim_y - 0.1, f"L = {focal_length_mm:.1f} mm", ha='center', va='top', color='#555')
    
    # 標註角度 (顯示全角與 mRad)
    ax.text(focal_length_mm * 1.05, 0, f"Θ ≈ {full_deg:.4f}°\n({full_mrad:.4f} mRad)", color='#1976D2', fontweight='bold', fontsize=11, va='center')
    
    # 調整圖表邊界,確保下方的文字 L 不會被切除
    ax.set_xlim(-focal_length_mm*0.1, focal_length_mm*1.3)
    ax.set_ylim(dim_y - 0.8, max(r1, r2)*1.5 + 0.5)
    ax.axis('off')

    plt.tight_layout()
    # 將轉換為 mm 的結果轉為字串並回填表單
    d2_sync_str = f"{d2_mm:g} mm"
    return text_result, fig, round(focal_length_mm, 2), d2_sync_str


# --- 線光斑長度與角度 (Line Laser Angle) 邏輯 ---

def calculate_and_plot_line_angle(distance, dist_unit, line_length, length_unit):
    if distance <= 0: return "❌ 錯誤:距離必須大於 0", None, gr.update(), gr.update()
    if line_length < 0: return "❌ 錯誤:線長不能為負數", None, gr.update(), gr.update()

    # 單位轉換至 mm
    dist_mm = distance * 10.0 if dist_unit == "公分 (cm)" else (distance * 1000.0 if dist_unit == "公尺 (m)" else distance)
    len_mm = line_length * 10.0 if length_unit == "公分 (cm)" else (line_length * 1000.0 if length_unit == "公尺 (m)" else line_length)

    # 半線長
    half_l = len_mm / 2.0
    
    # 計算半角
    half_rad = math.atan(half_l / dist_mm)
    half_deg = math.degrees(half_rad)
    
    # 計算全角
    full_deg = half_deg * 2

    text_result = (
        f"### 💡 線斑角度計算結果:\n"
        f"- 測試距離 ($L$): **{dist_mm:.2f} mm**\n"
        f"- 線光斑總長 ($l$): **{len_mm:.2f} mm**\n"
        f"- 半線長 ($l/2$): **{half_l:.2f} mm**\n\n"
        f"#### 📐 發散角度結果\n"
        f"- **半角 (Half-Angle, ${{\\theta/2}}$)**: **{half_deg:.4f}°**\n"
        f"- **發散全角 (Full-Angle, ${{\\theta}}$)**: **{full_deg:.4f}°**\n\n"
        f"*(✨ 光斑樣式、尺寸與角度已自動同步至「產品訂購」表單!)*"
    )

    # 繪製圖表
    fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
    ax.set_title(f"{COMPANY_NAME} - Line Laser Angle", fontsize=12)

    # 繪製等腰三角形 (模擬線光斑展開)
    triangle_coords = [[0, 0], [dist_mm, half_l], [dist_mm, -half_l]]
    poly = plt.Polygon(triangle_coords, closed=True, facecolor='#FFEBEE', edgecolor='#D32F2F', linewidth=2, alpha=0.6)
    ax.add_patch(poly)

    # 中心線
    ax.plot([0, dist_mm*1.1], [0, 0], color='#9E9E9E', linestyle='-.', linewidth=1)
    
    # 標註雷射光線 (紅線)
    ax.plot([dist_mm, dist_mm], [-half_l, half_l], color='#B71C1C', linewidth=3)
    
    # 文字標註
    ax.text(dist_mm / 2, -half_l * 0.1, f"L = {dist_mm:.1f} mm", ha='center', va='top', color='#424242')
    ax.text(dist_mm * 1.05, 0, f"l = {len_mm:.1f} mm", va='center', rotation=90, color='#B71C1C')
    ax.text(dist_mm * 0.15, half_l * 0.05, f"Θ ≈ {full_deg:.2f}°", fontsize=11, color='#D32F2F', fontweight='bold')

    # 動態調整邊界避免圖形過於狹長被裁切
    y_limit = max(half_l, dist_mm * 0.2) * 1.2
    ax.set_xlim(-0.1 * dist_mm, 1.3 * dist_mm)
    ax.set_ylim(-y_limit, y_limit)
    ax.axis('off')

    plt.tight_layout()
    # 回傳光斑樣式「線狀」與光點大小「長度 mm (角度°)」以供連動
    return text_result, fig, "線狀", f"{len_mm:.2f} mm ({full_deg:.2f}°)"


# --- 更新輸入框標籤函數 ---
def update_offset_label(unit):
    if unit == "毫米 (mm)":
        return gr.update(label="光斑偏移量 (mm)")
    else:
        return gr.update(label="光斑偏移量 (um)")

def update_dist_label(unit):
    if unit == "公分 (cm)":
        return gr.update(label="測試距離 L (cm)")
    elif unit == "公尺 (m)":
        return gr.update(label="測試距離 L (m)")
    else:
        return gr.update(label="測試距離 L (mm)")

def update_focal_label(unit):
    if unit == "公分 (cm)":
        return gr.update(label="焦距長度 (cm)")
    elif unit == "公尺 (m)":
        return gr.update(label="焦距長度 (m)")
    else:
        return gr.update(label="焦距長度 (mm)")

def update_focus_spot_labels(unit):
    if unit == "毫米 (mm)":
        return gr.update(label="雷射出光尺寸 d1 (mm)"), gr.update(label="焦距光斑尺寸 d2 (mm)")
    else:
        return gr.update(label="雷射出光尺寸 d1 (um)"), gr.update(label="焦距光斑尺寸 d2 (um)")

def update_line_length_label(unit):
    if unit == "公分 (cm)":
        return gr.update(label="線光斑長度 l (cm)")
    elif unit == "公尺 (m)":
        return gr.update(label="線光斑長度 l (m)")
    else:
        return gr.update(label="線光斑長度 l (mm)")

# --- 新增:動態切換光點大小/光線長度標籤 ---
def update_spot_input_label(style):
    if style in ["線狀", "十字線"]:
        return gr.update(label="光線長度")
    else:
        return gr.update(label="光點大小")


# --- 2. Gradio 介面設計 ---
init_ws = load_rzf_config()

with gr.Blocks(title=COMPANY_NAME) as demo:
    ws_state = gr.State(init_ws)
    gr.Markdown(f"# 🛰️ {COMPANY_NAME} 專業系統")

    with gr.Tab("🛒 產品訂購"):
        with gr.Row():
            with gr.Column():
                gr.Markdown("### 🔦 光學核心參數")
                w_select = gr.Dropdown(choices=init_ws, label="雷射波長", value=init_ws[0] if init_ws else None)
                p_slider = gr.Slider(1, 1000, label="輸出功率 (mW)", value=5)
                s_radio = gr.Radio(["點狀", "線狀", "十字線", "DOE"], label="光斑樣式", value="點狀")
                with gr.Row():
                    focus_in = gr.Number(label="焦距 (mm)", value=0)
                    spot_in = gr.Textbox(label="光點大小") # 標籤會動態改變
                with gr.Row():
                    coaxial_in = gr.Dropdown(choices=["≤ 1 mRad", "≤ 3 mRad", "≤ 5 mRad", "≤ 8 mRad", "≤ 10 mRad"], label="同軸度 (mRad/°)", value="≤ 3 mRad", allow_custom_value=True)
                    ellipse_in = gr.Textbox(label="橢圓率", value="0")
            with gr.Column():
                gr.Markdown("### 🔩 機構與線材規格")
                with gr.Row(): dim_d = gr.Number(label="直徑", value=10); dim_l = gr.Number(label="長度", value=30)
                wire_m = gr.Dropdown(["PVC", "矽膠線", "鐵氟龍線"], label="材質", value="PVC")
                with gr.Row(): wire_l = gr.Number(label="長度(mm)", value=100); wire_c = gr.ColorPicker(label="顏色", value="#FF0000")
                connector = gr.Textbox(label="連接器規格"); q_input = gr.Number(label="數量", value=1)
                submit_btn = gr.Button("✅ 提交 RZF 訂單", variant="primary")
                order_status = gr.Textbox(label="通知", interactive=False)

    with gr.Tab("🎯 光束焦距收斂計算"):
        gr.Markdown(r"""## 🎯 計算焦距光斑收斂角度 (Focus Beam Convergence)""")
        
        # 加入焦距光斑雷射模組示意圖 (內建 SVG)
        gr.HTML("""
        <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 20px; background-color: #fcfcfc; padding: 15px; border-radius: 8px; border: 1px solid #eee;">
            <svg width="500" height="200" viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
                <!-- Laser Module & Lens -->
                <rect x="10" y="80" width="70" height="40" rx="5" fill="#607D8B" stroke="#455A64" stroke-width="2"/>
                <rect x="80" y="85" width="15" height="30" rx="2" fill="#37474F"/>
                <ellipse cx="105" cy="100" rx="5" ry="30" fill="rgba(135, 206, 235, 0.6)" stroke="#0288D1" stroke-width="1.5"/> <!-- Lens -->
                <text x="45" y="105" fill="white" font-size="12" font-weight="bold" text-anchor="middle" font-family="sans-serif">LASER</text>
                
                <!-- Converging Beam (Blue) -->
                <polygon points="105,70 105,130 380,110 380,90" fill="rgba(33, 150, 243, 0.2)" stroke="#1976D2" stroke-width="1.5"/>
                
                <!-- Center Line -->
                <line x1="105" y1="100" x2="480" y2="100" stroke="#9E9E9E" stroke-width="1.5" stroke-dasharray="5,5"/>
                
                <!-- D1 (Laser Output) Plane & Dimension -->
                <line x1="105" y1="30" x2="105" y2="170" stroke="#388E3C" stroke-width="1" stroke-dasharray="3,3"/>
                <line x1="115" y1="70" x2="115" y2="130" stroke="#388E3C" stroke-width="2"/>
                <text x="105" y="25" fill="#388E3C" font-size="12" text-anchor="middle" font-family="sans-serif">出光面</text>
                <text x="125" y="105" fill="#388E3C" font-size="12" font-weight="bold" font-family="sans-serif">d1</text>
                
                <!-- D2 (Focal Spot) Plane & Dimension -->
                <line x1="380" y1="30" x2="380" y2="170" stroke="#388E3C" stroke-width="1" stroke-dasharray="3,3"/>
                <line x1="390" y1="90" x2="390" y2="110" stroke="#388E3C" stroke-width="2"/>
                <text x="380" y="25" fill="#388E3C" font-size="12" text-anchor="middle" font-family="sans-serif">焦平面</text>
                <text x="400" y="105" fill="#388E3C" font-size="12" font-weight="bold" font-family="sans-serif">d2</text>
                
                <!-- Focal Length L -->
                <line x1="105" y1="185" x2="380" y2="185" stroke="#555" stroke-width="1"/>
                <line x1="105" y1="180" x2="105" y2="190" stroke="#555" stroke-width="1"/>
                <line x1="380" y1="180" x2="380" y2="190" stroke="#555" stroke-width="1"/>
                <text x="242" y="180" fill="#555" font-size="13" text-anchor="middle" font-family="sans-serif">焦距 (L)</text>
                
                <!-- Angle notation -->
                <path d="M 280 100 A 100 100 0 0 0 278 111" fill="none" stroke="#D32F2F" stroke-width="1"/>
                <path d="M 280 100 A 100 100 0 0 1 278 89" fill="none" stroke="#D32F2F" stroke-width="1"/>
                <text x="265" y="104" fill="#D32F2F" font-size="12" font-weight="bold" font-family="sans-serif">θ</text>
            </svg>
        </div>
        """)

        with gr.Row():
            with gr.Column():
                gr.Markdown("### 輸入焦距與光斑參數")
                with gr.Row():
                    size_type_focus = gr.Radio(["直徑 (Diameter)", "半徑 (Radius)"], label="光斑尺寸類型", value="直徑 (Diameter)")
                    spot_unit_focus = gr.Radio(["毫米 (mm)", "微米 (um)"], label="光斑尺寸單位", value="毫米 (mm)")
                
                with gr.Row():
                    focal_input = gr.Number(label="焦距長度 (mm)", value=50.0)
                    focal_unit = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")

                with gr.Row():
                    d1_focus_in = gr.Number(label="雷射出光尺寸 d1 (mm)", value=3.0)
                    d2_focus_in = gr.Number(label="焦距光斑尺寸 d2 (mm)", value=0.5)
                
                focus_calc_btn = gr.Button("開始計算收斂角度", variant="primary")
                focus_out_text = gr.Markdown("等待輸入...")
            
            with gr.Column():
                focus_out_plot = gr.Plot(label="Focus Beam Convergence Plot")
                gr.Markdown(r"""
                **計算原理說明**:
                1. 設定雷射出光為起始點,焦平面光斑為終點,測試距離為焦距 $L$。
                2. 計算光束半徑收斂差:${\Delta r = r_1 - r_2}$
                3. **半收斂角**:$\theta_{half} = \arctan(\frac{\Delta r}{L})$
                4. **全收斂角**:$\theta_{full} = 2 \times \theta_{half}$
                """)

    with gr.Tab("📐 同軸度計算"):
        gr.Markdown("## 📐 雷射同軸度與 mRad 雙向換算")
        
        # 加入同軸度雷射模組示意圖 (內建 SVG)
        gr.HTML("""
        <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 20px; background-color: #fcfcfc; padding: 15px; border-radius: 8px; border: 1px solid #eee;">
            <svg width="500" height="200" viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
                <!-- Laser Module -->
                <rect x="20" y="80" width="80" height="40" rx="5" fill="#607D8B" stroke="#455A64" stroke-width="2"/>
                <rect x="100" y="85" width="15" height="30" rx="2" fill="#37474F"/>
                <text x="60" y="105" fill="white" font-size="14" font-weight="bold" text-anchor="middle" font-family="sans-serif">LASER</text>
                
                <!-- Center Line (Ideal) -->
                <line x1="115" y1="100" x2="420" y2="100" stroke="#9E9E9E" stroke-width="1.5" stroke-dasharray="5,5"/>
                
                <!-- Deviated Laser Beam (Actual) -->
                <line x1="115" y1="100" x2="420" y2="40" stroke="#E53935" stroke-width="2"/>
                <circle cx="420" cy="40" r="5" fill="#E53935"/>
                <text x="445" y="45" fill="#E53935" font-size="12" font-family="sans-serif">實際光斑</text>
                
                <!-- Dimension L (Distance) -->
                <line x1="115" y1="160" x2="420" y2="160" stroke="#555" stroke-width="1"/>
                <line x1="115" y1="155" x2="115" y2="165" stroke="#555" stroke-width="1"/>
                <line x1="420" y1="155" x2="420" y2="165" stroke="#555" stroke-width="1"/>
                <text x="267" y="155" fill="#555" font-size="14" text-anchor="middle" font-family="sans-serif">測試距離 (L)</text>
                
                <!-- Dimension r (Offset) -->
                <line x1="420" y1="45" x2="420" y2="95" stroke="#1976D2" stroke-width="2" stroke-dasharray="3,3"/>
                <text x="430" y="75" fill="#1976D2" font-size="14" font-weight="bold" font-family="sans-serif">偏移量 (r)</text>
                
                <!-- Angle Arc -->
                <path d="M 160 100 A 50 50 0 0 0 156 89" fill="none" stroke="#D32F2F" stroke-width="1.5"/>
                <text x="168" y="93" fill="#D32F2F" font-size="14" font-weight="bold" font-family="sans-serif">θ</text>
            </svg>
        </div>
        """)

        with gr.Tabs():
            with gr.Tab("已知偏移量 ➜ 求角度"):
                with gr.Row():
                    with gr.Column():
                        with gr.Row():
                            dist_input_1 = gr.Number(label="測試距離 L (mm)", value=1000)
                            dist_unit_1 = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
                        
                        with gr.Row():
                            off_input = gr.Number(label="光斑偏移量 (mm)", value=1)
                            off_unit = gr.Radio(["毫米 (mm)", "微米 (um)"], label="偏移量單位", value="毫米 (mm)")
                        
                        off_type = gr.Radio(["半徑 (Radius)", "直徑 (Diameter)"], label="偏移量類型", value="半徑 (Radius)")
                        calc_btn_1 = gr.Button("計算角度與 mRad", variant="primary")
                        calc_output_text_1 = gr.Markdown("等待輸入...")
                    with gr.Column():
                        calc_output_plot_1 = gr.Plot(label="Coaxiality Plot")
                        
            with gr.Tab("已知角度 ➜ 求偏移量"):
                with gr.Row():
                    with gr.Column():
                        with gr.Row():
                            dist_input_2 = gr.Number(label="測試距離 L (mm)", value=1000)
                            dist_unit_2 = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
                            
                        with gr.Row():
                            angle_input = gr.Number(label="角度數值", value=1)
                            ang_type = gr.Radio(["mRad", "度 (Degree)"], label="角度單位", value="mRad")
                            
                        calc_btn_2 = gr.Button("計算半徑與直徑長度", variant="primary")
                        calc_output_text_2 = gr.Markdown("等待輸入...")
                    with gr.Column():
                        calc_output_plot_2 = gr.Plot(label="Coaxiality Plot")

    with gr.Tab("🔦 光束發散計算"):
        gr.Markdown(r"""## 🔦 測量兩點計算光束發散角 (Beam Divergence)""")
        
        # 加入光束發散雷射模組示意圖 (內建 SVG)
        gr.HTML("""
        <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 20px; background-color: #fcfcfc; padding: 15px; border-radius: 8px; border: 1px solid #eee;">
            <svg width="500" height="200" viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
                <!-- Laser Module -->
                <rect x="10" y="80" width="70" height="40" rx="5" fill="#607D8B" stroke="#455A64" stroke-width="2"/>
                <rect x="80" y="85" width="15" height="30" rx="2" fill="#37474F"/>
                <text x="45" y="105" fill="white" font-size="12" font-weight="bold" text-anchor="middle" font-family="sans-serif">LASER</text>
                
                <!-- Expanding Beam (Yellow) -->
                <polygon points="95,97 95,103 450,150 450,50" fill="rgba(255, 235, 59, 0.4)" stroke="#FBC02D" stroke-width="1.5"/>
                
                <!-- Center Line -->
                <line x1="95" y1="100" x2="480" y2="100" stroke="#9E9E9E" stroke-width="1.5" stroke-dasharray="5,5"/>
                
                <!-- Z1 Plane & d1 -->
                <line x1="220" y1="30" x2="220" y2="170" stroke="#1976D2" stroke-width="1" stroke-dasharray="3,3"/>
                <line x1="230" y1="83" x2="230" y2="117" stroke="#1976D2" stroke-width="2"/> <!-- rough d1 height -->
                <text x="220" y="25" fill="#1976D2" font-size="12" text-anchor="middle" font-family="sans-serif">位置 1 (z1)</text>
                <text x="240" y="105" fill="#1976D2" font-size="12" font-weight="bold" font-family="sans-serif">d1</text>
                
                <!-- Z2 Plane & d2 -->
                <line x1="400" y1="30" x2="400" y2="170" stroke="#1976D2" stroke-width="1" stroke-dasharray="3,3"/>
                <line x1="410" y1="58" x2="410" y2="142" stroke="#1976D2" stroke-width="2"/> <!-- rough d2 height -->
                <text x="400" y="25" fill="#1976D2" font-size="12" text-anchor="middle" font-family="sans-serif">位置 2 (z2)</text>
                <text x="420" y="105" fill="#1976D2" font-size="12" font-weight="bold" font-family="sans-serif">d2</text>
                
                <!-- Delta L (Distance Difference) -->
                <line x1="220" y1="185" x2="400" y2="185" stroke="#555" stroke-width="1"/>
                <line x1="220" y1="180" x2="220" y2="190" stroke="#555" stroke-width="1"/>
                <line x1="400" y1="180" x2="400" y2="190" stroke="#555" stroke-width="1"/>
                <text x="310" y="180" fill="#555" font-size="13" text-anchor="middle" font-family="sans-serif">距離差 (ΔL)</text>
                
                <!-- Angle notation -->
                <path d="M 140 100 A 40 40 0 0 1 138 106" fill="none" stroke="#D32F2F" stroke-width="1"/>
                <path d="M 140 100 A 40 40 0 0 0 138 94" fill="none" stroke="#D32F2F" stroke-width="1"/>
                <text x="148" y="104" fill="#D32F2F" font-size="12" font-weight="bold" font-family="sans-serif">θ</text>
            </svg>
        </div>
        """)

        with gr.Row():
            with gr.Column():
                gr.Markdown("### 輸入測量數據")
                size_type_div = gr.Radio(["直徑 (Diameter)", "半徑 (Radius)"], label="光斑尺寸類型", value="直徑 (Diameter)")
                
                with gr.Row():
                    z1_in = gr.Number(label="位置 1 距離 (z1) mm", value=100)
                    d1_in = gr.Number(label="位置 1 尺寸 (d1) mm", value=2.0)
                
                with gr.Row():
                    z2_in = gr.Number(label="位置 2 距離 (z2) mm", value=1000)
                    d2_in = gr.Number(label="位置 2 尺寸 (d2) mm", value=4.0)
                
                div_calc_btn = gr.Button("開始計算發散角", variant="primary")
                div_out_text = gr.Markdown("等待輸入...")
            
            with gr.Column():
                div_out_plot = gr.Plot(label="Beam Divergence Plot")
                gr.Markdown(r"""
                **計算原理說明**:
                1. 測量距離差:${\Delta L = z_2 - z_1}$
                2. 光束半徑差:${\Delta r = r_2 - r_1}$ (直角三角形高度)
                3. **半角發散**:$\theta_{half} = \arctan(\frac{\Delta r}{\Delta L})$
                4. **全角發散** (業界標準):$\theta_{full} = 2 \times \theta_{half}$
                """)

    # 新增:線斑角度計算分頁
    with gr.Tab("📏 線斑角度計算"):
        gr.Markdown(r"""## 📏 測量線光斑長度計算發散角度 (Line Laser Angle)""")
        
        # 加入雷射模組與線斑示意圖 (內建 SVG)
        gr.HTML("""
        <div style="display: flex; justify-content: center; align-items: center; margin-bottom: 20px; background-color: #fcfcfc; padding: 15px; border-radius: 8px; border: 1px solid #eee;">
            <svg width="500" height="200" viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
                <!-- Laser Module -->
                <rect x="20" y="80" width="80" height="40" rx="5" fill="#607D8B" stroke="#455A64" stroke-width="2"/>
                <rect x="100" y="85" width="15" height="30" rx="2" fill="#37474F"/>
                <text x="60" y="105" fill="white" font-size="14" font-weight="bold" text-anchor="middle" font-family="sans-serif">LASER</text>
                
                <!-- Red Laser Beam (Fan) -->
                <polygon points="115,100 400,20 400,180" fill="rgba(244, 67, 54, 0.15)" stroke="#E53935" stroke-width="1.5"/>
                <line x1="115" y1="100" x2="400" y2="100" stroke="#E53935" stroke-width="1" stroke-dasharray="5,5"/>
                
                <!-- Dimension L (Distance) -->
                <line x1="115" y1="190" x2="400" y2="190" stroke="#555" stroke-width="1"/>
                <line x1="115" y1="185" x2="115" y2="195" stroke="#555" stroke-width="1"/>
                <line x1="400" y1="185" x2="400" y2="195" stroke="#555" stroke-width="1"/>
                <text x="257" y="185" fill="#555" font-size="14" text-anchor="middle" font-family="sans-serif">測試距離 (L)</text>
                
                <!-- Dimension l (Line Length) -->
                <line x1="420" y1="20" x2="420" y2="180" stroke="#555" stroke-width="1"/>
                <line x1="415" y1="20" x2="425" y2="20" stroke="#555" stroke-width="1"/>
                <line x1="415" y1="180" x2="425" y2="180" stroke="#555" stroke-width="1"/>
                <text x="430" y="105" fill="#555" font-size="14" font-family="sans-serif">線斑長度 (l)</text>
                
                <!-- Angle Arc -->
                <path d="M 160 88 A 50 50 0 0 0 160 112" fill="none" stroke="#D32F2F" stroke-width="1.5"/>
                <text x="170" y="104" fill="#D32F2F" font-size="14" font-weight="bold" font-family="sans-serif">θ</text>
            </svg>
        </div>
        """)
        
        with gr.Row():
            with gr.Column():
                with gr.Row():
                    dist_input_line = gr.Number(label="測試距離 L (mm)", value=100)
                    dist_unit_line = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="距離單位", value="毫米 (mm)")
                
                with gr.Row():
                    length_input_line = gr.Number(label="線光斑長度 l (mm)", value=100)
                    length_unit_line = gr.Radio(["毫米 (mm)", "公分 (cm)", "公尺 (m)"], label="長度單位", value="毫米 (mm)")
                
                calc_btn_line = gr.Button("開始計算角度", variant="primary")
                calc_output_text_line = gr.Markdown("等待輸入...")
            
            with gr.Column():
                calc_output_plot_line = gr.Plot(label="Line Laser Angle Plot")
                gr.Markdown(r"""
                **計算原理說明**:
                1. 將打出的線光斑切半,與光源形成直角三角形:對邊為半線長 $l / 2$,鄰邊為測試距離 $L$。
                2. **半角**:$\theta_{half} = \arctan(\frac{l / 2}{L})$
                3. **全角 (發散角)**:$\theta_{full} = 2 \times \theta_{half}$
                """)

    with gr.Tab("📖 規格說明"):
        gr.Markdown("### 📘 術語定義\n- **mRad**: 毫弧度,雷射發散角與同軸度常用的專業單位。\n- **發散角**: 光束隨距離擴散的程度,通常以全角 (Full-Angle) 標示。\n- **收斂角**: 光束通過透鏡聚焦後,逐漸匯聚變小的角度。")
        gr.Markdown("---")
        latest_spec_md = gr.Markdown("### 📝 最新訂單規格確認\n*尚未提交任何訂單,提交後將顯示於此處。*")

    with gr.Tab("📋 訂單報表"):
        refresh_table_btn = gr.Button("🔄 重新整理")
        order_table = gr.DataFrame(value=get_order_data())

    with gr.Tab("⚙️ 系統設定"):
        with gr.Row():
            new_w_input = gr.Textbox(label="新增波長"); add_w_btn = gr.Button("新增規格")
        download_btn = gr.Button("🔄 生成下載連結")
        file_output = gr.File(label="下載資料", file_count="multiple")

    # --- 邏輯綁定 ---
    # 訂單與系統
    submit_btn.click(submit_rzf_order, [w_select, p_slider, s_radio, q_input, focus_in, spot_in, coaxial_in, ellipse_in, dim_d, dim_l, wire_m, wire_l, wire_c, connector], [order_status, latest_spec_md])
    refresh_table_btn.click(get_order_data, outputs=order_table)
    add_w_btn.click(lambda n, c: (gr.update(choices=c+[n], value=n), c+[n], f"已新增: {n}"), [new_w_input, ws_state], [w_select, ws_state, order_status])
    download_btn.click(get_backup_files, outputs=file_output)
    
    # 動態變更光點大小/光線長度標籤
    s_radio.change(update_spot_input_label, inputs=s_radio, outputs=spot_in)

    # 同軸度計算 (連動同軸度參數至表單)
    dist_unit_1.change(update_dist_label, inputs=dist_unit_1, outputs=dist_input_1)
    dist_unit_2.change(update_dist_label, inputs=dist_unit_2, outputs=dist_input_2)
    off_unit.change(update_offset_label, inputs=off_unit, outputs=off_input)
    calc_btn_1.click(calc_angle_from_offset, [dist_input_1, dist_unit_1, off_input, off_type, off_unit], [calc_output_text_1, calc_output_plot_1, coaxial_in])
    calc_btn_2.click(calc_offset_from_angle, [dist_input_2, dist_unit_2, angle_input, ang_type], [calc_output_text_2, calc_output_plot_2, coaxial_in])
    
    # 光束發散計算 (連動光點大小至表單)
    div_calc_btn.click(calculate_and_plot_divergence, [z1_in, d1_in, z2_in, d2_in, size_type_div], [div_out_text, div_out_plot, spot_in])

    # 焦距收斂計算 (連動焦距與光點大小至表單)
    focal_unit.change(update_focal_label, inputs=focal_unit, outputs=focal_input)
    spot_unit_focus.change(update_focus_spot_labels, inputs=spot_unit_focus, outputs=[d1_focus_in, d2_focus_in])
    focus_calc_btn.click(calculate_and_plot_focus_divergence, [focal_input, focal_unit, d1_focus_in, d2_focus_in, spot_unit_focus, size_type_focus], [focus_out_text, focus_out_plot, focus_in, spot_in])

    # 線斑角度計算 (連動光斑樣式與長度尺寸至表單)
    dist_unit_line.change(update_dist_label, inputs=dist_unit_line, outputs=dist_input_line)
    length_unit_line.change(update_line_length_label, inputs=length_unit_line, outputs=length_input_line)
    calc_btn_line.click(calculate_and_plot_line_angle, [dist_input_line, dist_unit_line, length_input_line, length_unit_line], [calc_output_text_line, calc_output_plot_line, s_radio, spot_in])


# 部署在 Hugging Face Spaces 時不需加 share=True
demo.launch(theme=gr.themes.Soft())