wujingjing
2025-02-27 f996c7437b0a7d4e7bafeb7c71b7c86b7170c8bd
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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
import axios from 'axios';
import { defaultsDeep } from 'lodash-es';
import type { Overlay } from 'ol';
import { Feature, Map as OpenLayerMap, View } from 'ol';
import type { Extent } from 'ol/extent';
import { extend, getCenter, getTopLeft, getWidth } from 'ol/extent';
import type { FeatureLike } from 'ol/Feature';
import MVT from 'ol/format/MVT.js';
import WKT from 'ol/format/WKT';
import { Point } from 'ol/geom';
import type Geometry from 'ol/geom/Geometry';
import { Draw, defaults as olDefaults } from 'ol/interaction';
import { createBox } from 'ol/interaction/Draw';
import type Layer from 'ol/layer/Layer';
import Tile from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import VectorTileLayer from 'ol/layer/VectorTile';
import { fromLonLat, get as getProjection } from 'ol/proj';
import type LayerRenderer from 'ol/renderer/Layer';
import type { Source } from 'ol/source';
import { XYZ } from 'ol/source';
import VectorSource from 'ol/source/Vector';
import VectorTileSource from 'ol/source/VectorTile';
import WMTS from 'ol/source/WMTS';
import { Circle, Fill, Stroke, Style, Text } from 'ol/style';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import type { ViewOptions } from 'ol/View';
import type { Ref, ShallowRef } from 'vue';
import { markRaw, ref } from 'vue';
import { Logger } from '../logger/Logger';
import { MarkerOverlay } from './overlay/marker';
import { getCurrentPosition } from '/@/utils/brower';
import { travelTree } from '/@/utils/util';
import { ElLoadingService } from 'element-plus';
import { switchMapTheme } from '/@/api/map';
import { formatDate } from '/@/utils/formatTime';
 
export type LangType = 'zh_cn' | 'en';
export const enum GaoDeSourceType {
    /** @description 默认地图 */
    Default = 'default',
    /** @description 影像地图 */
    Satellite = 'satellite',
    /** @description 矢量地图 */
    Vector = 'standard',
    /** @description 影像路网 */
    SatelliteRoad = 'road_network',
}
export const enum OverlayType {
    Marker = 'marker',
}
export const MARKER_OVERLAY_CLASS_NAME = 'marker-overlay';
 
export const gaoDeSourceTypeMap = {
    // [GaoDeSourceType.Default]: '默认地图',
    [GaoDeSourceType.Vector]: '标准地图',
 
    [GaoDeSourceType.Satellite]: '卫星地图',
    [GaoDeSourceType.SatelliteRoad]: '路网地图',
};
 
export const getGaoDeSourceUrl = (type: GaoDeSourceType, lang: LangType = 'zh_cn') => {
    const urlMap = {
        [GaoDeSourceType.Satellite]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=6`,
        [GaoDeSourceType.Vector]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=7`,
        [GaoDeSourceType.SatelliteRoad]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=1&style=8`,
        [GaoDeSourceType.Default]: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=${lang}&size=1&scl=2&style=7`,
    };
    return urlMap[type];
};
type MapConfig = {
    sourceType: GaoDeSourceType;
};
 
type OLEventType = 'blackClick' | 'featureChange' | 'featureHoverChange';
type OLMapOptions = {
    container: HTMLDivElement;
 
    view?: ViewOptions;
} & MapConfig;
 
const resolutions = [];
for (let i = 0; i <= 8; ++i) {
    resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
}
export class OLMap {
    map: OpenLayerMap;
    source: XYZ;
    private eventMap: Map<OLEventType, Function[]>;
    /** @description 排除未做的layer,后续全部做好,可以不做判断 */
    unsupportedLayers = [];
 
    /** @description 图层控制信息 */
    layerInfo = ref([] as any[]);
 
    /** @description 图层控制信息 */
    legendList = ref([] as any[]);
 
    drawStyles = ref([] as any[]);
 
    /** @description 主题信息 */
    themeInfo = ref([] as any[]);
 
    activeSourceType: Ref<GaoDeSourceType> = ref(GaoDeSourceType.Vector);
    interactLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
    searchHighlightLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
    /** @description 当前激活状态 feature */
    activeFeature: ShallowRef<FeatureLike> = ref(null);
    private emit(eventName: OLEventType, ...args: any[]) {
        const handlers = this.eventMap?.get(eventName);
        if (handlers) {
            handlers.forEach((handler) => handler(...args));
        }
    }
 
    on(eventName: OLEventType, handler: Function) {
        if (!this.eventMap) {
            this.eventMap = new Map();
        }
 
        if (!this.eventMap.has(eventName)) {
            this.eventMap.set(eventName, []);
        }
 
        this.eventMap.get(eventName).push(handler);
    }
 
    off(eventName: OLEventType, handler: Function) {
        const handlers = this.eventMap.get(eventName);
        if (handlers) {
            const index = handlers.indexOf(handler);
            if (index > -1) {
                handlers.splice(index, 1);
            }
        }
    }
 
    constructor(options: OLMapOptions) {
        const { container, view, sourceType } = defaultsDeep(options, {
            view: {
                center: [13247019.404399557, 4721671.572580107],
                zoom: 8,
            },
            sourceType: GaoDeSourceType.Vector,
        } as OLMapOptions) as OLMapOptions;
        this.source = new XYZ({
            crossOrigin: 'anonymous',
            /** @description 高德地图最大支持18级, 超过会显示空白 */
            maxZoom: 18,
            /** @description 高德地图最小支持3级, 小于3级会显示空白 */
            minZoom: 3,
        });
 
        // this.source = this.getWMTS();
        const layer = new Tile({
            source: this.source,
        });
        this.map = new OpenLayerMap({
            target: container, // 绑定 DOM 容器
            layers: [layer], // 添加图层
            view: new View(view),
            interactions: olDefaults({ doubleClickZoom: false }),
        });
 
        this.activeSourceType.value = sourceType;
        this.applySourceType(this.activeSourceType.value);
        this.listenMapClick();
        this.addBasicControl();
        this.initEvent();
    }
 
    gaodeApiKey = 'eea6302da02576fe3f3dd3ba1fbe0a04';
 
    locationLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
    centerLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
 
    async locationCurrent() {
        const position = await getCurrentPosition();
        if (!position) return;
        const { latitude, longitude } = position;
 
        this.map.getView().setCenter(fromLonLat([longitude, latitude]));
        this.map.getView().setZoom(15);
        // 移除旧图层
        this.map.removeLayer(this.locationLayer);
        this.map.removeLayer(this.centerLayer);
        // 创建定位点图层
        this.locationLayer = new VectorLayer({
            source: new VectorSource({
                features: [
                    new Feature({
                        geometry: new Point(fromLonLat([longitude, latitude])),
                    }),
                ],
            }),
            style: new Style({
                // 外圆
                image: new Circle({
                    radius: 20,
                    fill: new Fill({
                        color: 'rgba(24, 144, 255, 0.1)',
                    }),
                    stroke: new Stroke({
                        color: 'rgba(24, 144, 255, 0.3)',
                        width: 2,
                    }),
                }),
            }),
            minZoom: 12,
        });
 
        // 创建中心点图层
        this.centerLayer = new VectorLayer({
            source: new VectorSource({
                features: [
                    new Feature({
                        geometry: new Point(fromLonLat([longitude, latitude])),
                    }),
                ],
            }),
            style: new Style({
                // 内圆
                image: new Circle({
                    radius: 6,
                    fill: new Fill({
                        color: '#1890ff',
                    }),
                    stroke: new Stroke({
                        color: '#fff',
                        width: 2,
                    }),
                }),
            }),
        });
 
        // 添加新图层
        this.map.addLayer(this.locationLayer);
        this.map.addLayer(this.centerLayer);
        return position;
    }
 
    async gaodeAddressSearch(address, city) {
        this.gaodeApiKey = 'eea6302da02576fe3f3dd3ba1fbe0a04';
        // const url = `https://restapi.amap.com/v3/assistant/inputtips?output=json&city=010&keywords=${address}=${this.gaodeApiKey}`;
        // 搜索 POI
        const url = `https://restapi.amap.com/v3/place/text?keywords=${address}&city=${city}&offset=20&page=1&key=${this.gaodeApiKey}&extensions=all `;
        // 搜索 POI 2.0
        // const url = `https://restapi.amap.com/v5/place/text?keywords=${address}&city=beijing&offset=20&page=1&key=${this.gaodeApiKey}&extensions=all
 
        const response = await axios.get(url);
        return response.data;
    }
 
    readWKT(wktStr) {
        const srid = wktStr.match(/SRID=(\d+);/)?.[1];
        const standardWktStr = wktStr.replace(/SRID=\d+;/, '');
        const feature = new WKT().readFeature(standardWktStr, {
            dataProjection: `EPSG:${srid}`,
        });
        return feature;
    }
    drawLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
    private isDrawStatus = false;
 
    removeDrawLayer() {
        if (!this.drawLayer) return;
        this.map.removeLayer(this.drawLayer);
        this.drawLayer = null;
    }
 
    drawPolygon() {
        if (this.isDrawStatus) return;
        this.isDrawStatus = true;
        return new Promise((resolve) => {
            // 创建绘制交互
            const draw = new Draw({
                type: 'Polygon',
            });
 
            // 添加绘制交互到地图
            this.map.addInteraction(draw);
 
            // 监听绘制完成事件
            draw.on('drawend', (event) => {
                const feature = event.feature;
                const geometry = feature.getGeometry();
                const extent = geometry.getExtent();
                this.drawLayer = new VectorLayer({
                    source: new VectorSource({
                        features: [feature],
                    }),
                    style: new Style({
                        stroke: new Stroke({
                            color: '#1677ff',
                            width: 2,
                        }),
                        fill: new Fill({
                            color: 'rgba(22, 119, 255, 0.1)',
                        }),
                    }),
                });
 
                // 添加多边形图层到地图
                this.map.addLayer(this.drawLayer);
 
                // 移除绘制交互
                this.map.removeInteraction(draw);
                setTimeout(() => {
                    this.isDrawStatus = false;
                }, 300);
 
                // 返回范围
                resolve(extent);
            });
        });
    }
    drawRectangle() {
        if (this.isDrawStatus) return;
        this.isDrawStatus = true;
        return new Promise((resolve) => {
            // 创建绘制交互
            const draw = new Draw({
                type: 'Circle',
                geometryFunction: createBox(),
            });
 
            // 添加绘制交互到地图
            this.map.addInteraction(draw);
 
            // 监听绘制完成事件
            draw.on('drawend', (event) => {
                const feature = event.feature;
                const geometry = feature.getGeometry();
                const extent = geometry.getExtent();
                this.drawLayer = new VectorLayer({
                    source: new VectorSource({
                        features: [feature],
                    }),
                    style: new Style({
                        stroke: new Stroke({
                            color: '#1677ff',
                            width: 2,
                        }),
                        fill: new Fill({
                            color: 'rgba(22, 119, 255, 0.1)',
                        }),
                    }),
                });
                // 添加新的feature
                // this.drawLayer.getSource().addFeature(feature);
 
                // 添加矩形图层到地图
                this.map.addLayer(this.drawLayer);
 
                // 移除绘制交互
                this.map.removeInteraction(draw);
                setTimeout(() => {
                    this.isDrawStatus = false;
                }, 300);
 
                // 返回范围
                resolve(extent);
            });
        });
    }
 
    clearObjectSearch() {
        this.highlightSearch([]);
    }
 
    displaySearchResult(searchItem) {
        if (!searchItem?.WKT) return;
        const feature = this.readWKT(searchItem.WKT);
        this.highlightSearch(feature);
        const geometry = feature.getGeometry();
 
        this.map.getView().fit(geometry.getExtent(), {
            // padding: [100, 100, 100, 100],
            maxZoom: 15,
        });
 
        return feature;
    }
 
    zoomToFeatures(features) {
        if (features.length === 0) return;
        // 获取所有 feature 的最小外接矩形
        const extent = features.reduce((acc, feature) => {
            const featureExtent = feature.getGeometry().getExtent();
            if (!acc) return featureExtent;
            return extend(acc, featureExtent);
        }, null);
        // 调整视图以适应最小外接矩形
        this.map.getView().fit(extent, {
            maxZoom: 15,
            padding: [50, 50, 50, 50], // 添加内边距使视图更美观
        });
    }
 
    updateSize() {
        this.map.updateSize();
    }
 
    initEvent() {
        const that = this;
        this.map.on('moveend', function (e) {
            const zoom = that.map.getView().getZoom(); //获取当前地图的缩放级别
            Logger.info('当前地图缩放级别为:' + zoom);
        });
        this.pointermove();
    }
 
    hightLightColor: '0000FFFF';
    sizeRate: 0;
 
    getPointHighLightStyle(feature) {
        if (!feature) return null;
        let pSize = feature.get('psize') ?? 15;
        pSize += pSize * 2;
 
        const pcolor = '0000FFFF';
        const pstyle = feature.get('pstyle');
        return this.getPointStyles({ color: pcolor, size: pSize, style: pstyle });
    }
 
    getLineHighLightStyle(feature) {
        if (!feature) return null;
 
        const lcolor = this.hightLightColor;
        let lsize = feature.get('lsize') ?? 15;
        lsize += lsize * this.sizeRate;
        const lstyle = feature.get('lstyle');
        return this.getLineStyles({ lsize: lsize, lcolor: lcolor, lstyle: lstyle });
    }
 
    getPolygonHighLightStyle(feature) {
        if (!feature) return null;
 
        const lcolor = this.hightLightColor;
        // return this.getPolygonStyles({ pcolor: lcolor, lstyle: 'default', lsize: 2 });
        return new Style({
            stroke: new Stroke({
                color: lcolor,
                width: 5,
            }),
            // fill: new Fill({
            //     color: lcolor,
            // }),
        });
    }
 
    // 保存点样式缓存
    pointStyeMap: Record<string, Style> = {};
 
    /**
     * 根据点的配置获取样式
     * @param config
     * @returns
     */
    getPointStyles(config: { size; color; style }) {
        const pSize = config.size;
 
        const pcolor = config.color;
        const pstyle = config.style;
 
        const pkey = `${pstyle}_${pSize}_${pcolor}`;
 
        if (!this.pointStyeMap[pkey]) {
            const drawStyle = this.drawStyles.value.find((item) => item.id === pstyle + '');
            const drawStyleType = drawStyle?.type;
            const config = drawStyle?.config;
 
            const drawStyleConfigType = drawStyle?.config?.type;
            if (drawStyleType === 'POINT') {
                if (drawStyleConfigType === 'circle') {
                    this.pointStyeMap[pkey] = new Style({
                        image: new Circle({
                            radius: pSize,
                            fill: new Fill({ color: `#${pcolor}` }),
                        }),
                    });
                } else if (drawStyleConfigType === 'font') {
                    this.pointStyeMap[pkey] = new Style({
                        text: new Text({
                            font: `${pSize}px "ywifont"`,
 
                            text: config?.text ?? '',
                            fill: new Fill({ color: `#${pcolor}` }),
                        }),
                    });
                } else {
                    this.pointStyeMap[pkey] = new Style({
                        image: new Circle({
                            radius: pSize,
                            fill: new Fill({ color: `#${pcolor}` }),
                        }),
                    });
                }
            } else {
                this.pointStyeMap[pkey] = new Style({
                    image: new Circle({
                        radius: pSize,
                        fill: new Fill({ color: `#${pcolor}` }),
                    }),
                });
            }
        }
        return this.pointStyeMap[pkey];
    }
 
    // 保存线样式缓存
    lineStyleMap: Record<string, Style> = {};
 
    /**
     * 根据线的配置获取样式
     * @param config
     */
    getLineStyles(config: { lsize; lcolor; lstyle; psize?; pcolor?; pstyle? }) {
        const lSize = config.lsize;
        if (!lSize) return null;
        const lColor = config.lcolor;
        const lstyle = config.lstyle;
        const styles = [];
        const lKey = `${lstyle}_${lSize}_${lColor}`;
        if (!this.lineStyleMap[lKey]) {
            const drawStyle = this.drawStyles.value.find((item) => item.id === lstyle + '');
            const drawStyleType = drawStyle?.type;
            const config = drawStyle?.config;
            this.lineStyleMap[lKey] = new Style({
                // image: new Circle({
                //     radius: lsize,
                //     fill: new Fill({ color: `#${color}` }),
                // }),
                stroke: new Stroke({
                    color: `#${lColor}`,
                    width: lSize,
                }),
            });
        }
        styles.push(this.lineStyleMap[lKey]);
 
        const hasPoint = Object.keys(config).some((key) => key === 'psize' && !!config[key]);
        if (hasPoint) {
            const psize = config.psize;
            const pcolor = config.pcolor;
            const pstyle = config.pstyle;
            const pointStyle = this.getPointStyles({ size: psize, color: pcolor, style: pstyle });
            styles.push(pointStyle);
        }
        return styles;
    }
    polygonStyleMap: Record<string, Style> = {};
    getPolygonStyles(config: { pcolor; lstyle; lsize; lcolor }) {
        const styles = [];
        const pColor = config.pcolor;
        const key = pColor;
        if (!this.polygonStyleMap[key]) {
            const polygonStyle = new Style({
                fill: new Fill({ color: `#${pColor}` }),
            });
            styles.push(polygonStyle);
        }
 
        const lineStyle = this.getLineStyles({
            lsize: config.lsize,
            lcolor: config.lcolor,
            lstyle: config.lstyle,
        });
        lineStyle && styles.push(...lineStyle);
        return styles;
    }
 
    private maxTextResolution = 1;
    getText(textContent, resolution) {
        let text = `${textContent}`;
        if (resolution > this.maxTextResolution) {
            text = '';
        }
 
        // else if (type == 'hide') {
        //     text = '';
        // } else if (type == 'shorten') {
        //     text = text.trunc(12);
        // } else if (type == 'wrap' && (!dom.placement || dom.placement.value != 'line')) {
        //     text = stringDivider(text, 16, '\n');
        // }
 
        return text;
    }
 
    createTextStyle(textContent, resolution) {
        return new Style({
            text: new Text({
                text: this.getText(textContent, resolution),
                font: '14px Arial',
                fill: new Fill({ color: '#000' }),
                stroke: new Stroke({ color: '#fff', width: 2 }),
                offsetX: 10, // 文字相对于几何中心的水平偏移
                offsetY: 20, // 文字相对于几何中心的垂直偏移
            }),
        });
    }
 
    // 保存标签样式缓存
    labelStyleMap: Record<string, Style> = {};
 
    /**
     * 根据标签的配置获取样式
     * @param config
     */
    getLabelStyles(config: { textContent; resolution }) {
        const textContent = config.textContent;
        if (!textContent) return null;
        const resolution = config.resolution;
        if (!textContent) return null;
        if (!this.labelStyleMap[textContent]) {
            this.labelStyleMap[textContent] = this.createTextStyle(textContent, resolution);
        }
        return this.labelStyleMap[textContent];
    }
 
    setDrawStyles(styles: any[]) {
        this.drawStyles.value = styles;
    }
 
    applySourceType(type: GaoDeSourceType = GaoDeSourceType.Vector) {
        const url = getGaoDeSourceUrl(type);
        this.source.setUrl(url);
    }
 
    setSourceType(type: GaoDeSourceType = GaoDeSourceType.Vector) {
        this.activeSourceType.value = type;
        this.applySourceType(type);
    }
    addMarkerLayer(dataList: any[], options: any) {
        const { markerOpt } = options;
        const markers: Overlay[] = [];
 
        // 创建标记点
        dataList.forEach((item, index) => {
            const marker = this.createMarker(`marker-${index}`, item, markerOpt);
            markers.push(marker);
            this.map.addOverlay(marker);
        });
 
        // 计算并调整视图范围
        this.adjustViewToOverlays(markers);
    }
 
    checkEquipIsShow() {
        for (const item of this.layerInfo.value) {
            if (item.id === 'equip') {
                return item.isVisible;
            }
        }
        return false;
    }
 
    getEquipOverlay() {
        for (const item of this.layerInfo.value) {
            if (item.type === 'equip') {
                return item;
            }
        }
    }
    createEleOverlay(dom: string | HTMLElement, position = [0, 0]) {
        const ele = typeof dom === 'string' ? (document.querySelector(dom) as HTMLElement) : dom;
        if (!ele) return;
        const eleOverlay = new MarkerOverlay({
            element: ele,
            position: position,
            positioning: 'top-left',
            stopEvent: false,
            className: 'z-[999]',
        });
        eleOverlay.setVisible(this.checkEquipIsShow());
 
        return eleOverlay;
    }
 
    private createMarker(id: string, item: any, markerOpt: any): Overlay {
        // 创建图片元素
        const markerImg = document.createElement('img');
        markerImg.src = markerOpt.icon.url;
        markerImg.style.width = `${markerOpt.icon.size}px`;
        markerImg.style.height = `${markerOpt.icon.size}px`;
        markerImg.style.cursor = 'pointer';
        markerImg.style.userSelect = 'none';
 
        const position = fromLonLat(item.position);
 
        // 创建 Overlay
        const overlay = new MarkerOverlay({
            id,
            className: MARKER_OVERLAY_CLASS_NAME,
            element: markerImg,
            position: position,
            positioning: 'center-center',
            stopEvent: false,
        });
 
        overlay.set('extData', item.extData);
        overlay.set('type', OverlayType.Marker);
        // 添加点击事件
        markerImg.addEventListener('click', (event) => {
            if (this.isDrawStatus) return;
            if (markerOpt.icon.selectUrl) {
                markerImg.src = markerOpt.icon.selectUrl;
            }
            markerOpt.click?.(event, overlay, item.extData, position);
        });
 
        return overlay;
    }
 
    getAllMarkerOverlays() {
        const overlays = this.map.getOverlays().getArray();
        return overlays.filter((overlay) => overlay.get('type') === OverlayType.Marker);
    }
 
    adjustViewToMarkers() {
        const overlays = this.getAllMarkerOverlays();
        this.adjustViewToOverlays(overlays);
    }
 
    getAllMarkerOverlaysExtent() {
        const overlays = this.getAllMarkerOverlays();
        const extent = this.getOverlaysExtent(overlays);
        return extent;
    }
 
    getOverlaysExtent(overlays: Overlay[]) {
        const extent = overlays.reduce<number[] | null>((ext, item) => {
            const coord = item.getPosition();
 
            if (!ext) {
                return [coord[0], coord[1], coord[0], coord[1]];
            }
            return [Math.min(ext[0], coord[0]), Math.min(ext[1], coord[1]), Math.max(ext[2], coord[0]), Math.max(ext[3], coord[1])];
        }, null);
        return extent;
    }
 
    adjustViewToOverlays(overlays: Overlay[]) {
        if (overlays.length === 0) return;
        const extent = this.getOverlaysExtent(overlays);
        if (extent) {
            this.fitExtend(extent);
        }
    }
 
    private fitExtend(extent: Extent) {
        this.map.getView().fit(extent, {
            padding: [50, 50, 50, 50], // 设置边距,使标记点不会太靠近地图边缘
            duration: 0, // 动画持续时间(毫秒)
            maxZoom: 15, // 限制最大缩放级别,防止单个设备时缩放过大
        });
    }
    /**
     * 监听地图点击
     */
    listenMapClick() {
        this.map.on('click', (event) => {
            if (this.isDrawStatus) return;
            // const features = this.map.getFeaturesAtPixel(event.pixel);
            const features = [];
            const layers: Layer<Source, LayerRenderer<any>>[] = [];
            this.map.forEachFeatureAtPixel(event.pixel, (feature, layer) => {
                features.push(feature);
                layers.push(layer);
            });
            const feature = features[0];
            feature?.get('click')?.(event);
 
            const layer = layers[0];
            if (layer === this.drawLayer) return;
            this.labelOverlay?.setVisible(false);
 
            if (feature !== this.activeFeature.value) {
                this.emit('featureChange', feature, layer);
            }
            if (feature) {
                const otype = feature.get('otype');
                console.log('🚀 ~ otype:', otype);
                const oname = feature.get('oname');
                console.log('🚀 ~ oname:', oname);
                const geometryType = feature.getGeometry().getType();
                console.log('🚀 ~ geometryType:', geometryType);
                const properties = feature.getProperties();
                console.log('🚀 ~ properties:', properties);
            }
            this.highlightSelect(feature);
            this.activeFeature.value = feature;
        });
    }
 
    setAllThemes(themeInfo) {
        this.themeInfo.value = themeInfo;
    }
 
    getAllLayers() {
        const allLayers = this.layerInfo.value.reduce((preVal, curVal) => {
            if (curVal.children && curVal.children.length > 0) {
                return preVal.concat(curVal.children.map((item) => item));
            } else {
                return preVal;
            }
        }, []);
        return allLayers;
    }
 
    zoomToLayers() {
        let extent = this.getAllMarkerOverlaysExtent();
        const layers = this.getAllLayerModels();
        if (layers.length > 0) {
            // 获取所有图层的范围
            extent = layers.reduce((extent, layer) => {
                const layerExtent = layer.getExtent();
 
                if (!extent) {
                    return layerExtent;
                }
 
                // 合并范围
                return extend(extent, layerExtent);
            }, extent);
        }
 
        // 聚焦到合并后的范围
        this.map.getView().fit(extent, {
            padding: [50, 50, 50, 50],
            maxZoom: 15,
        });
    }
 
    getAllLayerModels() {
        return this.layerInfo.value.reduce((preVal, curVal) => {
            if (curVal.children && curVal.children.length > 0) {
                return preVal.concat(curVal.children.map((item) => item.model));
            } else {
                return preVal;
            }
        }, []);
    }
 
    setLayerVisible(layerId: string, visible: boolean) {
        const layer = this.getAllLayers().find((item) => item.id === layerId);
        if (layer) {
            layer.isVisible = visible;
        }
    }
 
    setThemeById(themeId: string) {
        let group;
        let theme;
        travelTree(this.themeInfo.value, (item, index, array, parent) => {
            if (item.type === 'theme' && item.id === themeId) {
                group = parent;
                theme = item;
                return true;
            }
        });
        if (group) {
            group.activeTheme = themeId;
            this.handleThemeChange(themeId, group);
        }
    }
 
    async changeTheme(ids: string) {
        const loadingInstance = ElLoadingService({
            text: '加载主题中...',
            target: '.layout-parent',
        });
        const res = await switchMapTheme({
            theme_id: ids,
            time: formatDate(new Date()),
        }).finally(() => {
            loadingInstance.close();
        });
 
        // 加入主题之后的样式函数
        const themeLayerStyleFunc = (feature, resolution) => {
            const otype = feature.get('otype');
            const oname = feature.get('oname');
            // oname 映射样式
            const onameStyleMap = res?.[`O_${otype}`] ?? {};
            const themeStyles = res?.styles ?? [];
            const styleIndex = onameStyleMap[oname]?.style_id;
            const themeStyle = styleIndex == null ? null : themeStyles[styleIndex];
            // if(themeStyle){
            // }
            const shape = feature.getGeometry().getType();
            const styles = [];
            switch (shape) {
                case 'Point':
                    const pSize = themeStyle?.PSIZE ?? feature.get('psize');
 
                    const pcolor = themeStyle?.PCOLOR ?? feature.get('pcolor');
 
                    const pStyle = themeStyle?.PSTYLE ?? feature.get('pstyle');
 
                    const pointStyle = this.getPointStyles({
                        size: pSize,
                        color: pcolor,
                        style: pStyle,
                    });
                    pointStyle && styles.push(pointStyle);
                    break;
                case 'LineString':
                    const lSize = themeStyle?.LSIZE ?? feature.get('lsize');
                    const lColor = themeStyle?.LCOLOR ?? feature.get('lcolor');
                    const lStyle = themeStyle?.LSTYLE ?? feature.get('lstyle');
 
                    const pSize1 = themeStyle?.PSIZE ?? feature.get('psize');
                    const pcolor1 = themeStyle?.PCOLOR ?? feature.get('pcolor');
                    const pStyle1 = themeStyle?.PSTYLE ?? feature.get('pstyle');
 
                    const lineStyle = this.getLineStyles({
                        lsize: lSize,
                        lcolor: lColor,
                        lstyle: lStyle,
                        psize: pSize1,
                        pcolor: pcolor1,
                        pstyle: pStyle1,
                    });
                    lineStyle && styles.push(...lineStyle);
 
                    break;
                case 'Polygon':
                    const pColor = themeStyle?.PCOLOR ?? feature.get('pcolor');
                    const lSize1 = themeStyle?.LSIZE ?? feature.get('lsize');
                    const lColor1 = themeStyle?.LCOLOR ?? feature.get('lcolor');
                    const lstyle1 = themeStyle?.LSTYLE ?? feature.get('lstyle');
                    const polygonStyle = this.getPolygonStyles({
                        pcolor: pColor,
                        lsize: lSize1,
                        lcolor: lColor1,
                        lstyle: lstyle1,
                    });
                    polygonStyle && styles.push(...polygonStyle);
 
                    break;
                default:
                    break;
            }
 
            // switch (otype) {
            //     case 'WDM_JUNCTIONS':
            //         const textStyle = createTextStyle(feature, resolution);
            //         styles.push(textStyle);
 
            //     case 'WDM_PIPES':
            //         break;
            // }
            //#region ====================== 添加标注 ======================
            const tString = themeStyle?.TSTRING ?? feature.get('tstring');
            const tStringStyle = this.getLabelStyles({
                textContent: tString,
                resolution,
            });
            tStringStyle && styles.push(tStringStyle);
            //#endregion
 
            return styles;
        };
        const allLayers = this.getAllLayers();
        for (const item of allLayers) {
            if (this.unsupportedLayers.includes(item.id)) {
                continue;
            }
            item.model.setStyle(themeLayerStyleFunc);
        }
        return res?.legends ?? [];
    }
 
    async handleThemeChange(val?, themeGroup?) {
        const allIds = [];
        for (const item of this.themeInfo.value) {
            if (item.activeTheme) {
                allIds.push(item.activeTheme);
            }
        }
        const ids = allIds.join(',');
 
        if (!ids) {
            const allLayers = this.getAllLayerModels();
            for (const item of allLayers) {
                const originStyle = item.get('originStyle');
                originStyle && item.setStyle(originStyle);
            }
            return;
        }
        const legends = await this.changeTheme(ids);
        this.legendList.value = this.parseLegends(legends);
    }
 
    parseLegends(legends) {
        const result = legends.map((item) => {
            const isEqual = item.operate === '=';
            const result = {
                ...item,
                legend: item.legend.map((legendItem, index, array) => {
                    const preItem = array[index - 1];
                    let label = '';
                    if (isEqual) {
                        label = legendItem.value;
                    } else if (preItem) {
                        label = `>${preItem.value}且${item.operate}${legendItem.value}`;
                    } else {
                        label = `${item.operate}${legendItem.value}`;
                    }
                    return {
                        ...legendItem,
                        label: label,
                    };
                }),
            };
 
            result.legend.push({
                style: item.default,
                value: '',
                label: result.legend.length == 0 ? '默认' : `>${item.legend[item.legend.length - 1].value}`,
            });
            return result;
        });
        return result;
    }
 
    /** @description 记录所有图层 */
    setAllLayers(layerModels: Layer[], layers: any[], layerGroup: any[]) {
        this.layerInfo.value = layerGroup.reduce((preVal, curVal) => {
            const group = curVal.group;
            const groupId = `group-${group}`;
            let mapGroupItem = preVal.find((item) => item.id === groupId);
            if (!mapGroupItem) {
                mapGroupItem = { id: groupId, title: group, type: 'layer-group' };
                preVal.push(mapGroupItem);
            }
            if (!mapGroupItem.children) {
                mapGroupItem.children = [];
            }
            const layerId = curVal.layer_id;
            const foundIndex = layers.findIndex((item) => item.id === layerId);
            if (foundIndex === -1) {
                return preVal;
            }
            const layer = layerModels[foundIndex];
            const layerData = layers[foundIndex];
            //#region ====================== 设置缩放级别 ======================
            if (layerData?.max_ratio !== null) {
                layer.setMaxZoom(layerData.max_ratio);
            }
 
            if (layerData?.min_ratio !== null) {
                layer.setMinZoom(layerData.min_ratio);
            }
            //#endregion
 
            const data = {
                id: layerData.id,
                title: layerData.title,
                icon: layerData.icon,
                model: markRaw(layer),
                get isVisible() {
                    return layer.getVisible();
                },
                set isVisible(val) {
                    layer.setVisible(val);
                },
                type: 'layer',
            };
            mapGroupItem.children.push(data);
            return preVal;
        }, []);
        const that = this;
        this.layerInfo.value.push({
            id: 'equip',
            title: '监测设备',
            children: [],
            _isVisible: true,
            get isVisible() {
                return this._isVisible;
            },
            set isVisible(val) {
                this._isVisible = val;
                that.toggleMarkerOverlayVisible(val);
            },
            type: 'equip',
        });
    }
 
    /**
     *
     * 监听地图要素hover
     */
    listenMapFeatureHover() {
        let activeHover: FeatureLike = null;
        this.map.on('pointermove', (event) => {
            const features = this.map.getFeaturesAtPixel(event.pixel);
            const feature = features[0];
            if (feature !== activeHover) {
                this.emit('featureHoverChange', feature);
            }
            activeHover = feature;
        });
    }
 
    toggleMarkerOverlayVisible(visible: boolean) {
        const overlays = this.map.getOverlays();
        overlays.forEach((overlay) => {
            if (overlay instanceof MarkerOverlay) {
                const overlayElement = overlay.getElement();
                if (overlayElement) {
                    overlayElement.style.visibility = visible ? 'visible' : 'hidden';
                }
            }
        });
    }
 
    getConfig(): MapConfig {
        return {
            sourceType: this.activeSourceType.value,
        };
    }
 
    setConfig(config: MapConfig) {
        this.activeSourceType.value = config.sourceType;
        this.applySourceType(this.activeSourceType.value);
    }
 
    private addBasicControl() {
        // this.map.addControl(new ZoomSlider());
        // this.map.addControl(new FullScreen());
        const container = this.map.getViewport();
        if (!container) return;
        const olZoom = container.querySelector('.ol-zoom') as HTMLElement;
        if (!olZoom) return;
        olZoom.style.display = 'none';
    }
 
    /**
     * 放大地图
     */
    zoomIn(offsetLevel = 1) {
        const view = this.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom + offsetLevel);
    }
 
    /**
     * 缩小地图
     */
    zoomOut(offsetLevel = 1) {
        const view = this.map.getView();
        const zoom = view.getZoom();
        view.setZoom(zoom - offsetLevel);
    }
 
    /**
     * 地图左移
     */
    panLeft(offset = 1000) {
        const view = this.map.getView();
        const center = view.getCenter();
        if (!center) return;
        view.setCenter([center[0] - offset, center[1]]);
    }
 
    /**
     * 地图右移
     */
    panRight(offset = 1000) {
        const view = this.map.getView();
        const center = view.getCenter();
        if (!center) return;
        view.setCenter([center[0] + offset, center[1]]);
    }
 
    /**
     * 地图上移
     */
    panUp(offset = 1000) {
        const view = this.map.getView();
        const center = view.getCenter();
        if (!center) return;
        view.setCenter([center[0], center[1] + offset]);
    }
 
    /**
     * 地图下移
     */
    panDown(offset = 1000) {
        const view = this.map.getView();
        const center = view.getCenter();
        if (!center) return;
        view.setCenter([center[0], center[1] - offset]);
    }
 
    private tileUrlFunction(url) {
        return (tileCoord) =>
            url
                .replace('{z}', String(tileCoord[0] * 2 - 1))
                .replace('{x}', String(tileCoord[1]))
                .replace('{y}', String(tileCoord[2]))
                .replace('{a-d}', 'abcd'.substr(((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1));
    }
 
    addCustomLayer(url: string, style?: any) {
        const vectorTileExtent = [13270414.528705932, 2994644.904997596, 13295641.139349712, 3018305.0256410106];
 
        const vectorTileLayer = new VectorTileLayer({
            source: new VectorTileSource({
                format: new MVT(),
                url: url,
                // minZoom:5,
                // maxZoom:2
                // minZoom:12
            }),
            extent: vectorTileExtent,
            style: style,
        });
        this.map.addLayer(vectorTileLayer);
        return vectorTileLayer;
    }
    highlightFeature(feature) {
        const highlightStyle = {
            // Point: new Style({
            //     // image: new Circle({
            //     //     radius: 5,
            //     //     fill: new Fill({ color: `blue` }),
            //     // }),
            //     image: new Circle({
            //         radius: 13,
            //         stroke: new Stroke({
            //             color: `blue`,
            //             width: 3,
            //         }),
            //     }),
            // }),
            // Point:this.getPointHighLightStyle.call(this,feature),
            Point: new Style({
                // image: new Circle({
                //     radius: 5,
                //     fill: new Fill({ color: `blue` }),
                // }),
                image: new Circle({
                    radius: 13,
                    stroke: new Stroke({
                        color: `blue`,
                        width: 3,
                    }),
                }),
            }),
            LineString: new Style({
                stroke: new Stroke({
                    color: `blue`,
                    width: 5,
                }),
            }),
            Polygon: new Style({
                stroke: new Stroke({
                    color: `blue`,
                    width: 5,
                }),
                // fill: new Fill({
                //     color: `rgba(0, 0, 255, 0.1)`,
                // }),
            }),
        };
        // 创建高亮图层
        if (!this.interactLayer) {
            this.interactLayer = new VectorLayer({
                source: new VectorSource(),
                map: this.map,
                style: (feature) => {
                    const type = feature.getGeometry().getType();
                    return highlightStyle[type];
                },
            });
        }
    }
 
    private searchHighlightStyle = {
        // Point: new Style({
        //     // image: new Circle({
        //     //     radius: 5,
        //     //     fill: new Fill({ color: `blue` }),
        //     // }),
        //     image: new Circle({
        //         radius: 13,
        //         stroke: new Stroke({
        //             color: `blue`,
        //             width: 3,
        //         }),
        //     }),
        // }),
        // Point:this.getPointHighLightStyle.call(this,feature),
        Point: new Style({
            // image: new Circle({
            //     radius: 5,
            //     fill: new Fill({ color: `blue` }),
            // }),
            image: new Circle({
                radius: 13,
                stroke: new Stroke({
                    color: `yellow`,
                    width: 3,
                }),
            }),
        }),
        LineString: new Style({
            stroke: new Stroke({
                color: `yellow`,
                width: 5,
            }),
        }),
        Polygon: new Style({
            stroke: new Stroke({
                color: `yellow`,
                width: 5,
            }),
            // fill: new Fill({
            //     color: `rgba(0, 0, 255, 0.1)`,
            // }),
        }),
    };
 
    private selectHighlightStyle = {
        // Point: new Style({
        //     // image: new Circle({
        //     //     radius: 5,
        //     //     fill: new Fill({ color: `blue` }),
        //     // }),
        //     image: new Circle({
        //         radius: 13,
        //         stroke: new Stroke({
        //             color: `blue`,
        //             width: 3,
        //         }),
        //     }),
        // }),
        // Point:this.getPointHighLightStyle.call(this,feature),
        Point: new Style({
            // image: new Circle({
            //     radius: 5,
            //     fill: new Fill({ color: `blue` }),
            // }),
            image: new Circle({
                radius: 13,
                stroke: new Stroke({
                    color: `blue`,
                    width: 3,
                }),
            }),
        }),
        LineString: new Style({
            stroke: new Stroke({
                color: `blue`,
                width: 5,
            }),
        }),
        Polygon: new Style({
            stroke: new Stroke({
                color: `blue`,
                width: 5,
            }),
            // fill: new Fill({
            //     color: `rgba(0, 0, 255, 0.1)`,
            // }),
        }),
    };
 
    highlightSelect(feature) {
        // 创建高亮图层
        if (!this.interactLayer) {
            this.interactLayer = new VectorLayer({
                source: new VectorSource(),
                map: this.map,
                style: (feature) => {
                    const type = feature.getGeometry().getType();
                    return this.selectHighlightStyle[type];
                },
            });
        }
 
        // 设置高亮要素
        if (feature !== this.activeFeature.value) {
            if (this.activeFeature.value) {
                console.log('remove feature:', this.activeFeature.value);
                this.interactLayer.getSource().removeFeature(this.activeFeature.value as any);
            }
            if (feature) {
                this.interactLayer.getSource().addFeature(feature);
            }
            // this.highlightFeature = feature;
        }
    }
 
    private labelOverlay: MarkerOverlay = null;
    private initLabelOverlay() {
        if (this.labelOverlay) return;
        // 创建一个 div 元素用于显示标签
        const labelElement = document.createElement('div');
        labelElement.className = 'ol-label-overlay';
        labelElement.style.position = 'relative';
        labelElement.style.background = 'rgba(0,0,0,0.6)';
        labelElement.style.borderRadius = '4px';
        labelElement.style.color = '#fff';
        labelElement.style.padding = '4px 8px';
        labelElement.style.whiteSpace = 'nowrap';
        labelElement.style.fontSize = '12px';
        labelElement.style.transform = 'translate(-50%, -100%)';
        labelElement.style.marginBottom = '8px';
 
        // 创建 overlay
        this.labelOverlay = new MarkerOverlay({
            element: labelElement,
            offset: [0, 0],
            positioning: 'bottom-center',
        });
 
        // 添加到地图
        this.map.addOverlay(this.labelOverlay);
    }
    private preSearchHighlightFeatures: Feature[] = [];
    highlightSearch(features) {
        if (!Array.isArray(features)) {
            features = [features];
        }
 
        const positionFeatures = features.map((feature, index, array) => {
            const geometry = feature.getGeometry();
            const center = geometry.getExtent ? getCenter(geometry.getExtent()) : geometry.getCoordinates();
 
            // 创建一个新的Feature用于显示字体图标
            const iconFeature = new Feature({
                geometry: new Point(center),
            });
 
            // 设置字体图标样式
            // 添加点击事件监听
            // iconFeature.set('click', (event) => {
            //     // 初始化 labelOverlay
            //     this.initLabelOverlay();
            //     // 获取点击位置的坐标
            //     const coordinate = event.coordinate;
            //     // 设置 labelOverlay 的内容和位置
            //     const element = this.labelOverlay.getElement();
            //     element.innerHTML = `第${index + 1}个位置`;
            //     this.labelOverlay.setPosition(coordinate);
            // });
 
            iconFeature.setStyle([
                new Style({
                    text: new Text({
                        text: '\ue642', // 使用字体图标的unicode编码
                        font: '24px "ywifont"', // 设置字体大小和字体名称
                        fill: new Fill({
                            color: '#1677ff',
                        }),
                        offsetY: -20, // 调整图标位置
                    }),
                }),
                new Style({
                    text: new Text({
                        text: array.length === 1 ? '' : index + 1, // 添加数字
                        font: '14px Arial', // 设置数字字体
                        fill: new Fill({
                            color: '#ffffff', // 数字颜色设为白色
                        }),
                        offsetY: -20, // 与图标保持相同的偏移
                    }),
                }),
            ]);
 
            return iconFeature;
        });
        // 创建高亮图层
        if (!this.searchHighlightLayer) {
            this.searchHighlightLayer = new VectorLayer({
                source: new VectorSource(),
                map: this.map,
                style: (feature) => {
                    const type = feature.getGeometry().getType();
                    return this.searchHighlightStyle[type];
                },
            });
        }
        if (this.preSearchHighlightFeatures && this.preSearchHighlightFeatures.length > 0) {
            this.searchHighlightLayer.getSource().removeFeatures(this.preSearchHighlightFeatures);
        }
 
        // 设置高亮要素
        if (positionFeatures && positionFeatures.length > 0) {
            this.searchHighlightLayer.getSource().addFeatures(positionFeatures);
        }
        this.preSearchHighlightFeatures = positionFeatures;
    }
 
    pointermove() {
        this.map.on('pointermove', (e) => {
            if (this.map.hasFeatureAtPixel(e.pixel)) {
                this.map.getViewport().style.cursor = 'pointer';
            } else {
                this.map.getViewport().style.cursor = 'inherit';
            }
        });
    }
 
    clearMarker() {
        this.clearObjectSearch();
    }
 
    getWMTS = () => {
        const projection = getProjection('EPSG:3857');
        const projectionExtent = projection.getExtent();
        const size = getWidth(projectionExtent) / 256;
        const resolutions = new Array(19);
        const matrixIds = new Array(19);
        for (let z = 0; z < 19; ++z) {
            const pow = Math.pow(2, z);
            resolutions[z] = size / pow;
            matrixIds[z] = z;
        }
        return new WMTS({
            url: 'https://wmts-service.pre-fc.alibaba-inc.com/amap/service/wmts', //WMTS 服务的 url 地址
            layer: 'map:shanghai',
            matrixSet: 'GoogleMapsCompatible',
            format: 'image/png',
            projection: projection,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds,
            }),
            style: 'default',
            wrapX: true,
        });
    };
}