yyl
2026-05-11 51b0f6ed9f4e1d3bb6f8144470b46908c7699a96
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using DG.Tweening;
using Cysharp.Threading.Tasks;
using UnityEngine.EventSystems;
 
/// <summary>
/// UI管理器 - 负责管理所有UI界面的显示、隐藏和层级
/// </summary>
public class UIManager : ManagerBase<UIManager>
{
    #region 常量和枚举
    
    // 基础排序顺序
    private const int BASE_SORTING_ORDER = 10;
    
    #endregion
 
    #region 字段和属性
    
    // UI根节点
    private Transform uiRoot;
    
    // 各层级的Transform
    private Transform staticTrans;
    private Transform bottomTrans;
    private Transform midTrans;
    private Transform systemTrans;
    private Transform loadingTrans;
 
    // UI字典,存储所有已加载的UI,键为UI名称,值为UI实例
#if UNITY_EDITOR
    public
#else
    private
#endif 
    Dictionary<string, List<UIBase>> uiDict = new Dictionary<string, List<UIBase>>();
 
    // 存储关闭但未销毁的UI,键为UI名称,值为UI实例
    private Dictionary<string, List<UIBase>> closedUIDict = new Dictionary<string, List<UIBase>>();
 
    // UI栈,用于管理UI的显示顺序
    private Stack<UIBase> uiStack = new Stack<UIBase>();
    
    // 当前最高的排序顺序
    private int currentHighestSortingOrder = 0;
    
    // 排序缓存,避免每次UpdateUISortingOrder分配
    private List<UIBase> _sortTempList = new List<UIBase>(32);
    private Dictionary<UIBase, int> _sortOrderDict = new Dictionary<UIBase, int>(32);
    
    // 当前回合数,用于记录UI的使用情况
    private int currentRound = 0;
    
    // 缓存层级对应的排序顺序
    private static Dictionary<UILayer, int> layerSortingOrderCache = new Dictionary<UILayer, int>();
    
    // 缓存层级对应的Transform
    private Dictionary<UILayer, Transform> layerTransformCache = new Dictionary<UILayer, Transform>();
    
    // UI实例计数器,用于为同类型UI生成唯一标识
    private Dictionary<string, int> uiInstanceCounter = new Dictionary<string, int>();
    
    // 上次检查时间
    private float lastCheckTime = 0f;
    // 检查间隔(秒)
    private const float CHECK_INTERVAL = 5f;
    
    public Action<UIBase> OnOpenWindow;
 
    public Action<UIBase> OnCloseWindow;
 
    public Action OnAfterSortWinLayer;
 
    #endregion
 
    #region 初始化
 
    /// <summary>
    /// 初始化UI管理器
    /// </summary>
    public override async UniTask Init()
    {
        await InitUIRoot();
        // 初始化缓存
        layerSortingOrderCache.Clear();
        layerTransformCache.Clear();
        uiInstanceCounter.Clear();
        DOTween.SetTweensCapacity(500, 50);
        Debug.Log("UI管理器初始化完成");
    }
    
    /// <summary>
    /// 初始化UI根节点
    /// </summary>
    private async UniTask InitUIRoot()
    {
        // 查找UI根节点
        GameObject root = GameObject.Find("UIRoot");
        
        // 如果场景中没有UI根节点,则创建一个
        if (root == null)
        {
            var prefab = await BuiltInLoader.LoadPrefabAsync("UIRoot");
            root = GameObject.Instantiate(prefab);
            root.name = "UIRoot";
            if (root == null)
            {
                Debug.LogError("无法找到UI根节点");
                return;
            }
        }
 
        // 无论是从场景找到还是新实例化的,都确保跨场景不被销毁
        GameObject.DontDestroyOnLoad(root);
 
        uiRoot = root.transform;
        uiRoot.position = Vector3.zero;
 
        staticTrans = uiRoot.Find("Static");
        bottomTrans = uiRoot.Find("Bottom");
        midTrans = uiRoot.Find("Middle");
        loadingTrans = uiRoot.Find("Loading");
        systemTrans = uiRoot.Find("System");
 
        layerTransformCache.Clear();
        layerTransformCache.Add(UILayer.Static, staticTrans);
        layerTransformCache.Add(UILayer.Bottom, bottomTrans);
        layerTransformCache.Add(UILayer.Mid, midTrans);
        layerTransformCache.Add(UILayer.System, systemTrans);
        layerTransformCache.Add(UILayer.Loading, loadingTrans);
 
        LogUIRootEventSystemState("InitUIRoot");
    }
    
    public Transform GetUIRoot()
    {
        return uiRoot;
    }
    
    #endregion
 
    #region 辅助方法
 
    // 获取UI层级对应的基础排序顺序
    public static int GetBaseSortingOrderForLayer(UILayer layer)
    {
        // 尝试从缓存中获取排序顺序
        if (layerSortingOrderCache.TryGetValue(layer, out int order))
            return order;
 
        // 如果缓存中没有,使用原来的方法计算并缓存结果
        int result;
        switch (layer)
        {
            case UILayer.Static:
                result = BASE_SORTING_ORDER;
                break;
            case UILayer.Bottom:
                result = BASE_SORTING_ORDER * 100;
                break;
            case UILayer.Mid:
                result = BASE_SORTING_ORDER * 1000;
                break;
            case UILayer.System:
                result = BASE_SORTING_ORDER * 2000;
                break;
            case UILayer.Loading:
                result = BASE_SORTING_ORDER * 3000;
                break;
            default:
                result = BASE_SORTING_ORDER * 10;
                break;
        }
 
        // 将结果存入缓存
        layerSortingOrderCache[layer] = result;
        return result;
    }
 
    // 获取层级对应的Transform
    public Transform GetTransForLayer(UILayer layer)
    {
        // 尝试从缓存中获取Transform
        if (layerTransformCache.TryGetValue(layer, out Transform trans))
            return trans;
            
        // 如果缓存中没有,使用原来的方法获取并缓存结果
        Transform result;
        switch (layer)
        {
            case UILayer.Static:
                result = staticTrans;
                break;
            case UILayer.Bottom:
                result = bottomTrans;
                break;
            case UILayer.Mid:
                result = midTrans;
                break;
            case UILayer.System:
                result = systemTrans;
                break;
            case UILayer.Loading:
                result = loadingTrans;
                break;
            default:
                result = bottomTrans;
                break;
        }
        
        // 将结果存入缓存
        layerTransformCache[layer] = result;
        return result;
    }
    
    // 获取UI实例,如果不存在则返回null
    public T GetUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return null;
        }
 
        // 尝试从字典中获取UI实例列表
        if (uiDict.TryGetValue(uiName, out List<UIBase> uiList) && uiList.Count > 0)
        {
            // 返回第一个实例
            return uiList[0] as T;
        }
 
        // 如果不存在,返回null
        return null;
    }
 
    public UIBase GetUI(string uiName)
    {
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return null;
        }
 
        // 尝试从字典中获取UI实例列表
        if (uiDict.TryGetValue(uiName, out List<UIBase> uiList) && uiList.Count > 0)
        {
            // 返回第一个实例
            return uiList[0];
        }
 
        // 如果不存在,返回null
        return null;
    }
 
    public List<T> GetUIList<T>() where T : UIBase
    {
        List<T> uiList = new List<T>();
 
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return uiList;
        }
 
        // 尝试从字典中获取UI实例列表
        List<UIBase> tempList = null;
        uiDict.TryGetValue(uiName, out tempList);
 
        if (tempList != null)
        {
            for (int i = 0; i < tempList.Count; i++)
            {
                UIBase ui = tempList[i];
                if (null != ui)
                {
                    uiList.Add(ui as T);
                }
            }
        }
 
        return uiList;
    }
 
    public bool IsOpenedInList<T>() where T : UIBase
    {
        List<T> uiList = GetUIList<T>();
 
        foreach (T ui in uiList)
        {
            if (ui.IsActive())
            {
                return true;
            }
        }
 
        return false;
    }
 
    public bool IsOpened<T>() where T : UIBase
    {
        T ui = GetUI<T>();
 
        if (null != ui)
        {
            return ui.IsActive();
        }
 
        return false;
    }
 
    public bool IsOpened(string uiName)
    {
        UIBase ui = GetUI(uiName);
 
        if (null != ui)
        {
            return ui.IsActive();
        }
 
        return false;
    }
 
    // 检查是否存在任何全屏或遮罩窗口, 有screenMask 即可代表全屏
    public bool ExistAnyFullScreenOrMaskWin(string excludeUIName)
    {
        var exist = false;
        foreach (var uiList in uiDict.Values)
        {
            // 遍历该类型的所有UI实例
            foreach (var ui in uiList)
            {
                // 刷新UI
                if (ui.IsActive() && ui.name != excludeUIName)
                {
                    if (ui.screenMask != null)
                    {
                        exist = true;
                        break;
                    }
                }
            }
        }
 
        return exist;
    }
    
    //在此界面上有没任何全屏或遮罩窗口
    public bool ExistAnyFullScreenOrMaskWinAbove(string uiName)
    {
        var ui = GetUI(uiName);
        if (ui == null || !ui.IsActive())
        {
            // 如果UI不存在或未打开,默认为有被挡住 
            return true;
        }
 
        foreach (var uiBase in uiStack)
        {
            if (uiBase == null)
            {
                continue;
            }
            if (uiBase.name == uiName)
            {
                break;
            }
            if (uiBase.IsActive() && uiBase.screenMask != null)
            {
                return true;
            }
        }
 
        return false;
    }
 
    // 检查是否存在任何同层级sortingOrde大于我的窗口
    public bool ExistAnySameLevelWinHigherSortingOrder(UILayer uiLayer, string excludeUIName)
    {
        int mySortingOrder = 0;
        if (uiDict.TryGetValue(excludeUIName, out List<UIBase> excludeList) && excludeList.Count > 0)
        {
            foreach (var ui in excludeList)
            {
                if (ui.IsActive())
                {
                    mySortingOrder = ui.GetSortingOrder();
                    break;
                }
            }
        }
 
        if (mySortingOrder == 0)
            return false;
 
        foreach (var uiList in uiDict.Values)
        {
            foreach (var ui in uiList)
            {
                if (!ui.IsActive())
                    continue;
                if (ui.uiName == excludeUIName)
                    continue;
                if (ui.uiLayer != uiLayer)
                    continue;
                if (ui.GetSortingOrder() > mySortingOrder)
                    return true;
            }
        }
 
        return false;
    }
 
 
    // 获取指定类型的所有UI实例
    public List<T> GetAllUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        if (string.IsNullOrEmpty(uiName))
        {
            // 记录错误日志
            Debug.LogError("UI名称为空");
            return new List<T>();
        }
 
        // 尝试从字典中获取UI实例列表
        if (uiDict.TryGetValue(uiName, out List<UIBase> uiList) && uiList.Count > 0)
        {
            // 将列表中的所有实例转换为指定类型并返回
            return uiList.Cast<T>().ToList();
        }
 
        // 如果不存在,返回空列表
        return new List<T>();
    }
    
    // 更新父级UI的回合数
    private void UpdateParentUIRounds(UIBase ui)
    {
        // 如果UI为空或不支持父子关系,直接返回
        if (ui == null || !ui.supportParentChildRelation)
            return;
            
        // 获取父级UI
        UIBase parentUI = ui.parentUI;
        // 遍历所有父级UI,更新回合数
        while (parentUI != null)
        {
            // 更新父级UI的最后使用回合数
            parentUI.lastUsedRound = currentRound;
            // 继续向上查找父级UI
            parentUI = parentUI.parentUI;
        }
    }
    
    // 递归收集所有子UI
    private void CollectChildrenUI(UIBase ui, List<UIBase> result)
    {
        // 如果UI为空或没有子UI或不支持父子关系,直接返回
        if (ui == null || !ui.supportParentChildRelation || ui.childrenUI == null || ui.childrenUI.Count == 0)
            return;
        
        // 遍历所有子UI
        foreach (var childUI in ui.childrenUI)
        {
            // 如果结果列表中不包含当前子UI,则添加
            if (!result.Contains(childUI))
            {
                // 添加到结果列表
                result.Add(childUI);
                // 递归收集子UI的子UI
                CollectChildrenUI(childUI, result);
            }
        }
    }
    
    /// <summary>
    /// 检查并关闭长时间未使用的UI
    /// </summary>
    public void CheckAndCloseIdleUI()
    {
        // 如果没有UI,直接返回
        if (uiDict.Count == 0 && closedUIDict.Count == 0)
            return;
            
        // 创建需要关闭的UI列表
        List<UIBase> uiToClose = new List<UIBase>();
        
        // 遍历所有活跃UI
        foreach (var uiList in uiDict.Values)
        {
            foreach (var ui in uiList)
            {
                // 如果UI是持久化的,跳过
                if (ui.isPersistent)
                    continue;
                    
                if (ui.IsActive())
                    continue;
 
                // 计算UI空闲的回合数
                int idleRounds = currentRound - ui.lastUsedRound;
                
                // 如果空闲回合数超过最大空闲回合数,添加到关闭列表
                if (idleRounds > ui.maxIdleRounds)
                {
                    uiToClose.Add(ui);
                }
            }
        }
        
        // 遍历所有关闭的UI
        List<string> emptyKeys = new List<string>();
        foreach (var kvp in closedUIDict)
        {
            string uiName = kvp.Key;
            List<UIBase> uiList = kvp.Value;
            List<UIBase> uiToRemove = new List<UIBase>();
            
            foreach (var ui in uiList)
            {
                // 计算UI空闲的回合数
                int idleRounds = currentRound - ui.lastUsedRound;
                
                // 如果空闲回合数超过最大空闲回合数,添加到关闭列表
                //  2025 11/13 修复 持久化UI被销毁的问题
                if (idleRounds > ui.maxIdleRounds && !ui.isPersistent)
                {
                    uiToClose.Add(ui);
                    uiToRemove.Add(ui);
                }
            }
            
            // 从关闭列表中移除需要销毁的UI
            foreach (var ui in uiToRemove)
            {
                uiList.Remove(ui);
            }
            
            // 如果列表为空,记录需要从字典中移除的键
            if (uiList.Count == 0)
            {
                emptyKeys.Add(uiName);
            }
        }
        
        // 从字典中移除空列表
        foreach (var key in emptyKeys)
        {
            closedUIDict.Remove(key);
        }
        
        // 销毁所有需要关闭的UI
        foreach (var ui in uiToClose)
        {
            // 记录日志
#if UNITY_EDITOR
            Debug.Log($"销毁长时间未使用的UI: {ui.uiName}, 空闲回合数: {currentRound - ui.lastUsedRound}");
#endif
            // 销毁UI对象
            GameObject.Destroy(ui.gameObject);
        }
    }
    
    // // 生成UI实例的唯一标识
    // private string GenerateUIInstanceID(string uiName)
    // {
    //     // 如果计数器中不存在该UI类型,初始化为0
    //     if (!uiInstanceCounter.ContainsKey(uiName))
    //     {
    //         uiInstanceCounter[uiName] = 0;
    //     }
        
    //     // 递增计数器
    //     uiInstanceCounter[uiName]++;
        
    //     // 返回带有计数的唯一标识
    //     return $"{uiName}_{uiInstanceCounter[uiName]}";
    // }
    
    #endregion
 
    #region UI资源管理
 
    // private UIBase LoadUIResource(string uiName)
    // {
        
    //     // 从资源管理器加载UI预制体
    //     GameObject prefab;
    //     if (uiName == "LaunchWin" || uiName == "DownLoadWin" || uiName == "RequestSecretWin" || uiName == "GameAgeWarnWin")
    //     {
    //         prefab = await BuiltInLoader.LoadPrefabAsync(uiName);
    //     }
    //     else
    //     {
    //         prefab = await ResManager.Instance.LoadAssetAsync<GameObject>("UI", uiName);
    //     }
 
    //     // 检查预制体是否加载成功
    //     if (prefab == null)
    //     {
    //         // 记录错误日志
    //         Debug.LogError($"加载UI预制体失败: {uiName}");
    //         return null;
    //     }
 
    //     // 实例化UI对象
    //     GameObject uiObject = GameObject.Instantiate(prefab);
    //     // 设置对象名称
    //     uiObject.name = uiName;
 
    //     // 通过uiName映射Type
    //     Type uiType = Type.GetType(uiName);
    //     if (uiType == null)
    //     {
    //         Debug.LogError($"找不到UI类型: {uiName}");
    //         return null;
    //     }
 
    //     // 获取UI基类组件
    //     UIBase uiBase = uiObject.GetComponent(uiType) as UIBase;
 
    //     // 检查UI基类组件是否存在
    //     if (uiBase == null)
    //     {
    //         // 记录错误日志
    //         Debug.LogError($"UI预制体 {uiName} 没有 UIBase 组件或类型不匹配");
    //         return null;
    //     }
 
    //     // 设置UI名称
    //     uiBase.uiName = uiName;
 
    //     // 设置父节点为UI根节点
    //     Transform parentTrans = GetTransForLayer(uiBase.uiLayer);
 
    //     uiObject.transform.SetParent(parentTrans, false);
 
    //     // 设置排序顺序
    //     int baseSortingOrder = GetBaseSortingOrderForLayer(uiBase.uiLayer);
    //     uiBase.SetSortingOrder(baseSortingOrder);
 
    //     return uiBase;
    // }
 
    // 加载UI预制体
    private async UniTask<T> LoadUIResource<T>(string uiName) where T : UIBase
    {
        return await LoadUIResourceAsync(uiName) as T;
    }
 
    // ====================================================================
    // US2: Async variants — InitUIRootAsync, LoadUIResourceAsync, OpenWindowAsync
    // ====================================================================
 
    /// <summary>
    /// US2: 异步初始化 UI 根节点。
    /// </summary>
    public async UniTask InitUIRootAsync()
    {
        GameObject root = GameObject.Find("UIRoot");
        if (root == null)
        {
            var prefab = await BuiltInLoader.LoadPrefabAsync("UIRoot"); // 已异步,无需修改
            root = GameObject.Instantiate(prefab);
            root.name = "UIRoot";
            if (root == null)
            {
                Debug.LogError("无法加载UI根节点");
                return;
            }
        }
 
        // 无论是从场景找到还是新实例化的,都确保跨场景不被销毁
        GameObject.DontDestroyOnLoad(root);
    }
 
    /// <summary>
    /// US2: 异步加载 UI 资源。
    /// </summary>
    private async UniTask<UIBase> LoadUIResourceAsync(string uiName)
    {
        GameObject prefab;
        if (uiName == "LaunchWin" || uiName == "DownLoadWin" || uiName == "RequestSecretWin" || uiName == "GameAgeWarnWin")
        {
            prefab = await BuiltInLoader.LoadPrefabAsync(uiName);
        }
        else
        {
            prefab = await ResManager.Instance.LoadAssetAsync<GameObject>("UI", uiName, true);
        }
 
        if (prefab == null)
        {
            Debug.LogError($"加载UI预制体失败: {uiName}");
            return null;
        }
 
        GameObject uiObject = GameObject.Instantiate(prefab);
        uiObject.name = uiName;
 
        Type uiType = Type.GetType(uiName);
        if (uiType == null)
        {
            Debug.LogError($"找不到UI类型: {uiName}");
            return null;
        }
 
        UIBase uiBase = uiObject.GetComponent(uiType) as UIBase;
        if (uiBase == null)
        {
            Debug.LogError($"UI预制体 {uiName} 没有 UIBase 组件或类型不匹配");
            return null;
        }
 
        uiBase.uiName = uiName;
 
        Transform parentTrans = GetTransForLayer(uiBase.uiLayer);
        uiObject.transform.SetParent(parentTrans, false);
 
        int baseSortingOrder = GetBaseSortingOrderForLayer(uiBase.uiLayer);
        uiBase.SetSortingOrder(baseSortingOrder);
 
        return uiBase;
    }
 
    /// <summary>
    /// US2: 异步打开窗口。
    /// </summary>
    public async UniTask<UIBase> OpenWindowAsync(string uiName, int functionOrder = 0)
    {
        UIBase returnValue = null;
        UIBase parentUI = null;
 
        // Check closed cache
        if (closedUIDict.TryGetValue(uiName, out var closedUIList) && closedUIList.Count > 0)
        {
            returnValue = closedUIList[0] as UIBase;
            closedUIList.RemoveAt(0);
            if (closedUIList.Count == 0)
            {
                closedUIDict.Remove(uiName);
            }
        }
        else
        {
            // US3: Show loading indicator while loading UI prefab (auto-hide after load)
            ShowLoadingIndicator();
            try
            {
                returnValue = await LoadUIResourceAsync(uiName);
            }
            finally
            {
                HideLoadingIndicator();
            }
 
            if (returnValue == null)
            {
                Debug.LogError($"打开UI失败: {uiName}");
                return null;
            }
        }
 
        returnValue.gameObject.SetActive(true);
 
        if (returnValue.supportParentChildRelation && uiStack.Count > 0 && !returnValue.isMainUI)
        {
            parentUI = GetLastSupportParentChildRelationUI();
        }
 
        if (parentUI != null)
        {
            returnValue.parentUI = parentUI;
            if (parentUI.childrenUI == null)
            {
                parentUI.childrenUI = new List<UIBase>();
            }
            parentUI.childrenUI.Add(returnValue);
        }
 
        currentRound++;
        returnValue.lastUsedRound = currentRound;
        UpdateParentUIRounds(returnValue);
 
        if (!uiDict.ContainsKey(uiName))
        {
            uiDict[uiName] = new List<UIBase>();
        }
        uiDict[uiName].Add(returnValue);
 
        uiStack.Push(returnValue);
        UpdateUISortingOrder();
 
        returnValue.functionOrder = functionOrder;
        returnValue.HandleOpen();
        OnOpenWindow?.Invoke(returnValue);
        CheckAndCloseIdleUI();
 
        return returnValue;
    }
 
    /// <summary>
    /// US2: 泛型 异步打开窗口。
    /// </summary>
    public async UniTask<T> OpenWindowAsync<T>(int functionOrder = 0) where T : UIBase
    {
        if (typeof(T).Name == "MainWin")
        {
            //MainWin 比较关键且唯一,做安全防范
            var ui = GetUI<MainWin>();
            if (ui != null)
            {
                ui.ClickFunc(0);
                return ui as T;
            }
        }
        string uiName = typeof(T).Name;
        var result = await OpenWindowAsync(uiName, functionOrder);
        return result as T;
    }
 
    // ====================================================================
    // US3: Loading indicator for async UI loading
    // ====================================================================
 
    private GameObject _loadingIndicatorGO;
    private int _loadingRefCount;
 
    /// <summary>
    /// US3: 显示加载指示器(引用计数,支持重入)。
    /// </summary>
    public void ShowLoadingIndicator()
    {
        _loadingRefCount++;
        if (_loadingRefCount == 1)
        {
            EnsureLoadingIndicator();
            if (_loadingIndicatorGO != null)
            {
                _loadingIndicatorGO.SetActive(true);
            }
        }
    }
 
    /// <summary>
    /// US3: 隐藏加载指示器。
    /// </summary>
    public void HideLoadingIndicator()
    {
        _loadingRefCount = Mathf.Max(0, _loadingRefCount - 1);
        if (_loadingRefCount == 0 && _loadingIndicatorGO != null)
        {
            _loadingIndicatorGO.SetActive(false);
        }
    }
 
    public void DumpUIDiagnostics(string context)
    {
        var eventSystem = EventSystem.current;
        Debug.Log($"[UIManager][Diag] {context} EventSystem={(eventSystem != null ? eventSystem.name : "<null>")} selected={(eventSystem != null && eventSystem.currentSelectedGameObject != null ? eventSystem.currentSelectedGameObject.name : "<null>")} loadingIndicatorActive={(_loadingIndicatorGO != null && _loadingIndicatorGO.activeSelf)} loadingRefCount={_loadingRefCount} uiStackCount={uiStack.Count}");
        LogUIRootEventSystemState(context);
 
        var uiArray = new UIBase[uiStack.Count];
        uiStack.CopyTo(uiArray, 0);
        foreach (var ui in uiArray)
        {
            if (ui == null)
            {
                continue;
            }
 
            var uiCanvas = ui.GetComponent<Canvas>();
            var uiCanvasGroup = ui.GetComponent<CanvasGroup>();
            Debug.Log($"[UIManager][Diag] {context} ui={ui.GetType().Name} active={ui.gameObject.activeInHierarchy} layer={ui.uiLayer} sortingOrder={(uiCanvas != null ? uiCanvas.sortingOrder : -1)} siblingIndex={ui.transform.GetSiblingIndex()} canvasGroup.blocksRaycasts={(uiCanvasGroup != null ? uiCanvasGroup.blocksRaycasts : false)} canvasGroup.interactable={(uiCanvasGroup != null ? uiCanvasGroup.interactable : false)}");
        }
    }
 
    private void LogUIRootEventSystemState(string context)
    {
        if (uiRoot == null)
        {
            Debug.Log($"[UIManager][Diag] {context} uiRoot=<null>");
            return;
        }
 
        var eventSystemTransform = uiRoot.Find("EventSystem");
        if (eventSystemTransform == null)
        {
            Debug.Log($"[UIManager][Diag] {context} uiRoot.EventSystem child=<null>");
            return;
        }
 
        var eventSystemComponent = eventSystemTransform.GetComponent<EventSystem>();
        var standaloneInputModule = eventSystemTransform.GetComponent<StandaloneInputModule>();
        var baseInputModule = eventSystemTransform.GetComponent<BaseInputModule>();
        Debug.Log($"[UIManager][Diag] {context} uiRoot.EventSystem childExists=true activeSelf={eventSystemTransform.gameObject.activeSelf} activeInHierarchy={eventSystemTransform.gameObject.activeInHierarchy} eventSystemComponent={(eventSystemComponent != null)} standaloneInputModule={(standaloneInputModule != null)} baseInputModuleType={(baseInputModule != null ? baseInputModule.GetType().Name : "<null>")} currentMatchesChild={(EventSystem.current == eventSystemComponent)}");
    }
 
    private void EnsureLoadingIndicator()
    {
        if (_loadingIndicatorGO != null) return;
 
        // 创建简易加载指示器: 半透明遮罩 + 旋转图标
        var canvas = uiRoot != null ? uiRoot.GetComponentInChildren<Canvas>() : null;
        if (canvas == null) return;
 
        _loadingIndicatorGO = new GameObject("UILoadingIndicator");
        _loadingIndicatorGO.transform.SetParent(canvas.transform, false);
 
        // 全屏半透明遮罩
        var maskRT = _loadingIndicatorGO.AddComponent<RectTransform>();
        maskRT.anchorMin = Vector2.zero;
        maskRT.anchorMax = Vector2.one;
        maskRT.offsetMin = Vector2.zero;
        maskRT.offsetMax = Vector2.zero;
 
        var maskImage = _loadingIndicatorGO.AddComponent<UnityEngine.UI.Image>();
        maskImage.color = new Color(0, 0, 0, 0.3f);
        maskImage.raycastTarget = true; // 拦截点击
 
        // 加载提示文字
        var textGO = new GameObject("LoadingText");
        textGO.transform.SetParent(_loadingIndicatorGO.transform, false);
        var textRT = textGO.AddComponent<RectTransform>();
        textRT.anchorMin = new Vector2(0.5f, 0.5f);
        textRT.anchorMax = new Vector2(0.5f, 0.5f);
        textRT.sizeDelta = new Vector2(300, 60);
 
        var text = textGO.AddComponent<UnityEngine.UI.Text>();
        text.text = "Loading...";
        text.alignment = TextAnchor.MiddleCenter;
        text.fontSize = 28;
        text.color = Color.white;
        text.font = UnityEngine.Font.CreateDynamicFontFromOSFont("Arial", 28);
 
        // 确保在最上层
        var sortCanvas = _loadingIndicatorGO.AddComponent<Canvas>();
        sortCanvas.overrideSorting = true;
        sortCanvas.sortingOrder = 30000;
        _loadingIndicatorGO.AddComponent<UnityEngine.UI.GraphicRaycaster>();
 
        _loadingIndicatorGO.SetActive(false);
    }
    
    #endregion
 
    #region UI排序管理
    
    // 更新UI排序顺序
    private void UpdateUISortingOrder()
    {
        // 重置当前最高排序顺序
        currentHighestSortingOrder = 0;
        
        // 复用临时列表,避免每次分配数组
        _sortTempList.Clear();
        _sortOrderDict.Clear();
        
        int index = 0;
        foreach (var ui in uiStack)
        {
            if (ui != null)
            {
                _sortTempList.Add(ui);
                _sortOrderDict[ui] = index;
                index++;
            }
        }
 
        _sortTempList.Sort((a, b) =>
        {
            if (a == null || b == null) return 0;
            int layerCompare = a.uiLayer.CompareTo(b.uiLayer);
            if (layerCompare != 0)
                return layerCompare;
 
            return _sortOrderDict[b].CompareTo(_sortOrderDict[a]);
        });
 
        // 遍历排序后的UI列表,设置排序顺序
        for (int i = 0; i < _sortTempList.Count; i++)
        {
            var ui = _sortTempList[i];
            if (ui == null) continue;
            // 获取基础排序顺序
            int baseSortingOrder = GetBaseSortingOrderForLayer(ui.uiLayer);
            // 计算当前UI的排序顺序
            int sortingOrder = baseSortingOrder + currentHighestSortingOrder;
            // 设置UI的排序顺序
            ui.SetSortingOrder(sortingOrder);
            // 更新当前最高排序顺序
            currentHighestSortingOrder += ui.uiLayer == UILayer.Static ? 155/*这里是角色+特效之上的层级*/ : 10;
 
            // Debug.Log(ui.uiName + " order is " + sortingOrder + " " + currentHighestSortingOrder);
        }
        OnAfterSortWinLayer?.Invoke();
    }
    
    #endregion
 
    #region UI操作
 
 
 
    private UIBase GetLastSupportParentChildRelationUI()
    {
 
        foreach (var uiBase in uiStack)
        {
            if (uiBase != null && uiBase.supportParentChildRelation)
            {
                return uiBase;
            }
        }
 
        return null;
    }
 
    /// <summary>
    /// 关闭UI
    /// </summary>
    public void CloseWindow<T>(bool destroy = false) where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        CloseWindow(uiName, destroy);
        
    }
 
    public void CloseWindow(string uiName, bool destroy = false)
    {
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试关闭不存在的UI: {uiName}");
            return;
        }
        
        // 获取第一个UI实例
        UIBase ui = uiDict[uiName][0];
        
        // 关闭UI
        CloseWindow(ui, destroy);
    }
    
    /// <summary>
    /// 关闭指定的UI实例
    /// </summary>
    public void CloseWindow(UIBase ui, bool destroy = false)
    {
        // 检查UI是否为空
        if (ui == null)
        {
            // 记录警告日志
            Debug.LogWarning("尝试关闭空UI");
            return;
        }
 
        if (!ui.IsActive())
        {
            return;
        }
        
        // 获取UI类型名称
        string uiName = ui.uiName;
#if UNITY_EDITOR
        Debug.Log("CloseWindow " + uiName + " destroy : " + destroy.ToString());
#endif
 
        // 收集所有子UI
        List<UIBase> childrenUI = new List<UIBase>();
        if (ui.supportParentChildRelation)
        {
            CollectChildrenUI(ui, childrenUI);
        }
        
        // 先关闭所有子UI
        foreach (var childUI in childrenUI)
        {
            // 关闭子UI
            CloseWindow(childUI, destroy);
        }
        
        // 从栈中移除UI
        Stack<UIBase> tempStack = new Stack<UIBase>();
        while (uiStack.Count > 0)
        {
            // 弹出栈顶UI
            UIBase tempUI = uiStack.Pop();
            // 如果不是要关闭的UI,则保存到临时栈中
            if (tempUI != ui)
            {
                tempStack.Push(tempUI);
            }
            else
            {
                break;
            }
        }
        
        // 将临时栈中的UI重新压入栈中
        while (tempStack.Count > 0)
        {
            uiStack.Push(tempStack.Pop());
        }
        
        // 从字典中移除UI
        if (uiDict.ContainsKey(uiName))
        {
            // 从UI列表中移除
            uiDict[uiName].Remove(ui);
            // 如果列表为空,从字典中移除该类型
            if (uiDict[uiName].Count == 0)
            {
                uiDict.Remove(uiName);
            }
        }
        
        // 从父级UI的子UI列表中移除
        if (ui.supportParentChildRelation && ui.parentUI != null && ui.parentUI.childrenUI != null)
        {
            // 从父级UI的子UI列表中移除
            ui.parentUI.childrenUI.Remove(ui);
        }
        
        // 关闭UI
        ui.HandleClose();
        OnCloseWindow?.Invoke(ui);
 
        if (destroy)
        {
            // 销毁UI对象
            GameObject.Destroy(ui.gameObject);
        }
        else
        {
            // 添加到closedUIDict
            if (!closedUIDict.ContainsKey(uiName))
            {
                closedUIDict[uiName] = new List<UIBase>();
            }
            closedUIDict[uiName].Add(ui);
 
#if UNITY_EDITOR
            Debug.Log("CloseWindow " + uiName + " destroy : " + destroy.ToString() + " push to closedUIDict");
#endif
 
            // 隐藏UI (交给handle close内部自己去做)
            // ui.gameObject.SetActive(false);
        }
        
        // 更新UI排序顺序
        UpdateUISortingOrder();
    }
    
    /// <summary>
    /// 关闭指定类型的所有UI实例
    /// </summary>
    public void CloseAllWindows<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试关闭不存在的UI: {uiName}");
            return;
        }
        
        // 创建UI实例列表的副本,因为在关闭过程中会修改原列表
        List<UIBase> uiListCopy = new List<UIBase>(uiDict[uiName]);
        
        // 关闭所有UI实例
        foreach (var ui in uiListCopy)
        {
            // 关闭UI实例
            CloseWindow(ui, false);
        }
    }
 
    
    /// <summary>
    /// 关闭所有UI
    /// </summary>
    public void DestroyAllUI()
    {
        // 创建UI栈的副本,因为在关闭过程中会修改原栈
        UIBase[] uiArray = new UIBase[uiStack.Count];
        uiStack.CopyTo(uiArray, 0);
        
        // 关闭所有UI
        foreach (var ui in uiArray)
        {
            // 关闭UI
            CloseWindow(ui, true);
        }
        
        foreach (var uiList in closedUIDict.Values)
        {
            foreach (var ui in uiList)
            {
                GameObject.Destroy(ui.gameObject);
            }
        }
 
        // 清空UI字典和栈
        uiDict.Clear();
        uiStack.Clear();
        closedUIDict.Clear();
    }
    
    /// <summary>
    /// 刷新UI
    /// </summary>
    public void RefreshUI<T>() where T : UIBase
    {
        // 获取UI类型名称
        string uiName = typeof(T).Name;
        
        // 检查UI是否存在
        if (!uiDict.ContainsKey(uiName) || uiDict[uiName].Count == 0)
        {
            // 记录警告日志
            Debug.LogWarning($"尝试刷新不存在的UI: {uiName}");
            return;
        }
        
        // 刷新所有该类型的UI实例
        foreach (var ui in uiDict[uiName])
        {
            // 刷新UI
            ui.Refresh();
        }
    }
    
    /// <summary>
    /// 刷新所有UI
    /// </summary>
    public void RefreshAllUI()
    {
        // 遍历所有UI类型
        foreach (var uiList in uiDict.Values)
        {
            // 遍历该类型的所有UI实例
            foreach (var ui in uiList)
            {
                // 刷新UI
                ui.Refresh();
            }
        }
    }
    
    private void Update()
    {
        // 如果距离上次检查的时间超过了检查间隔
        if (Time.time - lastCheckTime > CHECK_INTERVAL)
        {
            // 更新上次检查时间
            lastCheckTime = Time.time;
            // 检查并关闭长时间未使用的UI
            CheckAndCloseIdleUI();
        }
    }
    
    #endregion
 
    #region 释放资源
    
    /// <summary>
    /// 释放资源
    /// </summary>
    public override void Release()
    {
        // 关闭所有UI
        DestroyAllUI();
        
        // 清空缓存
        layerSortingOrderCache.Clear();
        layerTransformCache.Clear();
        uiInstanceCounter.Clear();
        
        Debug.Log("UI管理器资源释放完成");
    }
    
    #endregion
}