<template>
    <div :class="['map', customClass]" ref="map" />
</template>

<script>
export default {
    name: 'MineMap',
    props: {
        // 默认地图加载配置
        defaultOptions: {
            default: () => ({}),
            type: Object,
            required: false,
        },
        // 自定义类名
        customClass: {
            default: '',
            type: String,
            required: false,
        },
        // 自定义点位集合
        markers: {
            default: () => [],
            type: Array,
            required: false,
        },
        // 自定义线集合
        lines: {
            default: () => [],
            type: Array,
            required: false,
        },
        // 自定义面集合
        polygons: {
            default: () => [],
            type: Array,
            required: false,
        },
    },
    data() {
        return {
            mapOptions: {
                // style: 'https://service.minedata.cn/map/solu/style/11001' /* 底图样式 */,
                // style: 'miniMap/service/solu/style/id/16932' /* 底图样式 */,
                style:
                    'https://map.hope.cmet1965.com:58000/service/solu/style/id/16932' /* 底图样式 */,
                center: [105.869855, 28.067095] /*地图中心点*/,
                zoom: 5 /*地图默认缩放等级*/,
                pitch: 0 /*地图俯仰角度*/,
                maxZoom: 20 /*地图最大缩放等级*/,
                minZoom: 3 /*地图最小缩放等级*/,
            },
            mineMap: Object.freeze(minemap), // mineMap插件
            map: null, // 地图实例对象
            mapLoaded: false,
            boundaryLineFace: [
                {
                    // 地图省份边界  layerIdl边界线 layerIdf 边界面
                    code: 'SC',
                    layerIdl: '20187ac7367e14034b8c19a40a33fe30',
                    layerIdf: '4394876460f6c3bd34d0615bf04cff47',
                    center: [102.928995, 30.52487],
                    zoom: 5.8,
                },
                {
                    code: 'YN',
                    layerIdl: '06fc0230dad437e85d24600e06516587',
                    layerIdf: '031e5e61df73778bce2c2d82a4fc0a1c',
                    center: [101.593103, 25.353375],
                    zoom: 6,
                },
                {
                    code: 'GZ',
                    layerIdl: '6c66cdbaddbcf839a529b03bcee23266',
                    layerIdf: 'd960ce4f0fe3eafeebf02a908e25910b',
                    center: [106.641243, 27.10797],
                    zoom: 6.5,
                },
                {
                    code: 'CQ',
                    layerIdl: 'dfc9779a51de79b2eb40790f613964e2',
                    layerIdf: 'b37573d5d73f223aa5cf4293efeda3c0',
                    center: [107.569855, 30.367095],
                    zoom: 6.8,
                },
                {
                    code: 'HN',
                    layerIdl: '4edbe95e3ec8786276bb39ce7c42453f',
                    layerIdf: 'c1c5c040257326352d694528b7e33fac',
                },
                {
                    code: 'AH',
                    layerIdl: 'ef01a0169aaec81e77e9f0048ceb9713',
                    layerIdf: '3dde510c446230cbd4fdd15c5fb85416',
                    center: [117.229929, 32.325398],
                    zoom: 6.5,
                },
                // {
                //     code: 'XJ',
                //     layerIdl: 'b6f8c73b2d314bd6e091012fd7698e94',
                //     layerIdf: '238a5e9de56faa7385873aaadf3ad67d',
                // },
            ],
            eventMarkers: [], // 事件驻点
            taskMarkers: [], // 任务驻点
            xcPlaceMarkers: [], // 巡查驻点
            jyPlaceMarkers: [], // 救援驻点
            xcCarMarkers: [], // 巡查车辆
            jyCarMarkers: [], // 救援车辆
            jyAreaMarkers: [], // 救援区域

            regionLayerIds: [], // 存储图层id
            regionSourceIds: [],  // 存储数据源id
            resucePlaceLayerIds: [], // 存储救援任务处置点位图层id
            resucePlaceSourceIds: [], // 存储救援任务处置点位数据源id
        }
    },
    created() {
        // 配置 key、solution
        this.mineMap.key = '30be7831caf84685b94e78727e4ce25f'
        this.mineMap.solution = 16932
        this.mineMap.domainUrl =
            'https://map.hope.cmet1965.com:58000' /* MineMap根域名地址 */
        /* MineMap矢量数据服务根域名地址 */
        this.mineMap.dataDomainUrl = 'https://map.hope.cmet1965.com:58000'
        /* MineMap矢量数据服务新规范根域名地址 */
        this.mineMap.serverDomainUrl = 'https://map.hope.cmet1965.com:58000'
        /* MineMap底图雪碧图地址 */
        this.mineMap.spriteUrl = [
            'https://map.hope.cmet1965.com:58000/minemapapi/zsxz/zsxz',
        ] // "./mapresource/sprite/sprite",
        /* MineMap后台服务根地址 */
        this.mineMap.serviceUrl = 'https://map.hope.cmet1965.com:58000/service/'

        // 合并覆盖默认配置项
        this.mapOptions = {
            ...this.mapOptions,
            ...this.defaultOptions,
        }
    },
    mounted() {
        this.initMineMap()
    },
    methods: {
        // 加载mineMap2D地图
        initMineMap() {
            // 初始化地图实例
            this.map = new this.mineMap.Map({
                container: this.$refs.map,
                ...this.mapOptions,
            })
                .on('load', (_) => {
                    this.setHinight() // 确保在地图加载完成后调用 setHinight
                    this.mapLoaded = true // 当地图加载完成时，设置标志为 true
                })
                .on('error', (error) => this.$emit('onError', error))
        },
        //设置高亮区域
        setHinight() {
            if (this.map) {
                this.boundaryLineFace.forEach((el) => {
                    this.map.setLayoutProperty(el.layerIdl, 'visibility', 'visible')
                    this.map.setLayoutProperty(el.layerIdf, 'visibility', 'visible')
                })
                this.$emit('onLoad', this.map)
            }
        },
        setProvice(code) {
            if (this.map) {
                let targetProvice
                this.boundaryLineFace.forEach((el) => {
                    if (code) {
                        if (el.code === code) {
                            this.map.setLayoutProperty(el.layerIdl, 'visibility', 'visible')
                            this.map.setLayoutProperty(el.layerIdf, 'visibility', 'visible')
                            targetProvice = el
                        } else {
                            this.map.setLayoutProperty(el.layerIdl, 'visibility', 'none')
                            this.map.setLayoutProperty(el.layerIdf, 'visibility', 'none')
                        }
                    } else {
                        this.map.setLayoutProperty(el.layerIdl, 'visibility', 'visible')
                        this.map.setLayoutProperty(el.layerIdf, 'visibility', 'visible')
                    }
                })
                this.changeMapCenter(targetProvice)
                this.$emit('onLoad', this.map)
            }
        },
        //地图中心点切换
        changeMapCenter(provice) {
            this.$nextTick(() => {
                let { center, zoom } = this.mapOptions
                if (provice) {
                    center = provice.center
                    zoom = provice.zoom
                }
                this.map.flyTo({
                    center,
                    zoom,
                })
            })
        },
        // 重新加载地图
        resetMap(callback) {
            if (this.map && this.mapLoaded) {
                // 移除所有动态添加的标记、线和面
                this.markers.forEach((marker) => marker.remove())
                this.lines.forEach((line) => this.map.removeLayer(line.id))
                this.polygons.forEach((polygon) => this.map.removeLayer(polygon.id))

                // 清空存储的图层引用
                this.markers.length = 0
                this.lines.length = 0
                this.polygons.length = 0

                // 重新应用底图样式
                const { center, zoom } = this.mapOptions
                this.map.setCenter(center)
                this.map.setZoom(zoom)
            }
            callback && callback(this.map)
        },



        //改变地图中心点
        changeCenter(val) {
            if (this.map) {
                // this.map // 同时传入缩放级别和中心点经纬度
                //   .setZoomAndCenter(8, val) //设置地图层级
                this.map.flyTo({
                    center: val,
                    zoom: 6.5,
                })
            }
        },

        /**
         * @description:
         * @param {*} type 类型
         * @return {*}
         */
        removeMarker(type) {
            if (this[`${type}Markers`].length) {
                this[`${type}Markers`].forEach((marker) => marker.remove())
                this[`${type}Markers`] = []
            }
            if (type === 'jyPlace') {
                this.removeAllRegion()
            }
            if (type === 'task') {
                this.removeAllResucePlace()
            }
        },

        removeAllMarker() {
            const types = ['event', 'task', 'xcPlace', 'jyPlace', 'xcCar', 'jyCar', 'jyArea']
            types.forEach((type) => {
                this.removeMarker(type)
            })
            this.removeAllRegion()
            this.removeAllResucePlace()
        },

        /**
         * @description:
         * @param {Array} markers 点位集合
         * @param {String} type 类型
         * @return { void }
         */
        // 地图打点
        minemapMarker(markers, type) {
            markers.forEach((item) => {
                if (item.lng && item.lng !== 'null' && item.lat !== 'null' && item.lat) {
                    item.lnglat = [item.lng, item.lat]
                    // 创建div作为标记点
                    let el = document.createElement('div')
                    el.className = 'map-point'

                    // let p1 = document.createElement('div')
                    // p1.className = 'text-box text-box-bg-' + item.state
                    // p1.innerHTML = item.bridgeName

                    let p2 = document.createElement('div')
                    p2.className = 'icon-box icon-point-' + type + 'Point'

                    // let p3 = document.createElement('div')
                    // p3.className = 'icon-bridge icon-bridge-' + item.type

                    // p2.appendChild(p3)
                    // el.appendChild(p1)
                    el.appendChild(p2)

                    // 标记点位
                    let marker = new minemap.Marker(el, { offset: [-33, -30] })
                        .setLngLat(item.lnglat)
                        .addTo(this.map)
                    this[`${type}Markers`].push(marker)
                    //添加点击事件
                    el.addEventListener('click', () => {
                        this.map.flyTo({
                            center: [item.lng, item.lat],
                            zoom: 8,
                        })
                        setTimeout(() => {
                            this.$emit('markerClick', {
                                data: { ...item },
                                type: type,
                            })
                        }, 500)
                    })
                } else {
                    console.log('该点位无定位数据', item)
                }
            })
        },
        abc() {
            console.log(123, '调用地图方法-----------------------')
        },
        moveToEvent(data) {
            if (!this.eventMarkers.length) {
                this.minemapMarker([data], 'event')
            }
            this.map.flyTo({
                center: [data.lng, data.lat],
                zoom: 8,
            })
        },
        // 绘制救援区域
        resuceRegion(id, data) {
            this.addResion(id, data)
        },
        addResion(id, data) {
            this.addResionSources(id, data)
        },
        addResionSources(id, data) {
            const coordinates = data.map((item) => {
                return [item.lng, item.lat]
            })
            var jsonData = {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "Polygon",
                            "coordinates": [coordinates]
                        }
                    }
                ]
            };
            const sourceId = "fillSource-" + id
            this.map.addSource(sourceId, {
                "type": "geojson",
                "data": jsonData
            });
            this.regionSourceIds.push(sourceId)
            this.addResionLayers(id, sourceId)
            this.map.flyTo({
                center: coordinates[0],
                zoom: 8,
            })
        },
        addResionLayers(id, sourceId) {
            const layerId = "fillLayer-" + id
            this.regionLayerIds.push(layerId)
            this.map.addLayer({
                "id": layerId,
                "type": "fill",
                "source": sourceId,
                "layout": {
                    "visibility": "visible",
                },
                "paint": {
                    "fill-color": "#f6f601",
                    "fill-opacity": 0.7,
                    "fill-outline-color": "#f6f601"
                },
                "minzoom": 7,
                "maxzoom": 17.5
            });
        },
        clearResion(id) {
            if (this.map) {
                if (this.map.getLayer("fillLayer-" + id)) {
                    this.map.removeLayer("fillLayer-" + id);
                }
                if (this.map.getSource("fillSource-" + id)) {
                    this.map.removeSource("fillSource-" + id);
                }
            }
        },
        removeAllRegion() {
            this.regionLayerIds.forEach((layerId) => {
                if (this.map.getLayer(layerId)) {
                    this.map.removeLayer(layerId);
                }
            })
            this.regionSourceIds.forEach((sourceId) => {
                if (this.map.getSource(sourceId)) {
                    this.map.removeSource(sourceId);
                }
            })
            this.regionLayerIds = []
            this.regionSourceIds = []
        },
        // 绘制救援任务处置点位
        resuceHandlePlace(id, data) {
            this.addResucePlaceSource(id, data)
        },
        addResucePlaceSource(id, data) {
            const features = data.map((item) => {
                return {
                    "type": "Feature",
                    "geometry": {
                        "type": "Point",
                        "coordinates": [item.lng, item.lat]
                    },
                    "properties": {
                        "title": item.name,
                        "kind": "hospital"
                    },

                }
            })
            var jsonData = {
                "type": "FeatureCollection",
                "features": features
            }
            const sourceId = "resucePlaceSource-" + id
            this.map.addSource(sourceId, {
                "type": "geojson",
                "data": jsonData
            });
            this.resucePlaceSourceIds.push(sourceId)
            this.addResucePlaceLayers(id, sourceId)
            this.map.flyTo({
                center: [data[0].lng, data[0].lat],
                zoom: 8,
            })
        },
        addResucePlaceLayers(id, sourceId) {
            const layerId = "resucePlaceLayer-" + id
            this.resucePlaceLayerIds.push(layerId)
            this.map.addLayer({
                "id": layerId,
                "type": "symbol",
                "source": sourceId,
                "layout": {
                    "visibility": "visible",
                    "text-field": "{title}",
                    "text-offset": [0, 0.6],
                    "text-anchor": "top",
                    "text-size": 20,
                    "icon-allow-overlap": true,  //图标允许压盖
                    "text-allow-overlap": true,   //图标覆盖文字允许压盖
                },
                "paint": {
                    "text-color": "#f6f601",
                    "text-halo-color": "#fff",
                    "text-halo-width": 0.5,
                },
                "minzoom": 7,
                "maxzoom": 17.5
            });
        },
        clearResucePlace(id) {
            if (this.map) {
                if (this.map.getLayer("resucePlaceLayer-" + id)) {
                    this.map.removeLayer("resucePlaceLayer-" + id);
                }
                if (this.map.getSource("resucePlaceSource-" + id)) {
                    this.map.removeSource("resucePlaceSource-" + id);
                }
            }
        },
        removeAllResucePlace() {
            this.resucePlaceLayerIds.forEach((layerId) => {
                if (this.map.getLayer(layerId)) {
                    this.map.removeLayer(layerId);
                }
            })
            this.resucePlaceSourceIds.forEach((sourceId) => {
                if (this.map.getSource(sourceId)) {
                    this.map.removeSource(sourceId);
                }
            })
            this.resucePlaceLayerIds = []
            this.resucePlaceSourceIds = []
        },
    },
    beforeDestroy() {
        // 注销地图实例,移除地图
        if (this.map) {
            this.map.remove()
        }
    },
}
</script>

<style scoped lang="scss">
.map {
    width: 100%;
    height: 100%;

    /* 通过 CSS 隐藏 logo */
    ::v-deep .minemap-ctrl-bottom-left {
        display: none !important;
    }
}

::v-deep .content {
    display: flex;
    width: 100%;

    a {
        text-decoration: none;
        color: inherit;
    }
}

::v-deep .content-left {
    width: 40%;
    border-right: 2px solid white;
}

::v-deep .content-right {
    margin-left: 20px;
}

::v-deep .minemap-popup-content {
    width: 200px;
    background: #3a66dd; // 示例样式
    color: white; // 示例样式
}

::v-deep .minemap-popup-tip {
    border-bottom-color: #3290d7; // 设置箭头颜色
    display: none;
}

::v-deep .minemap-popup-anchor-bottom .minemap-popup-tip {
    border-top-color: #3290d7; // 如果箭头在底部，则设置顶部边框颜色
    display: none;
}
</style>


<style lang="scss">
/* 地图点位样式 */
.map-point {
    // width: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .text-box {
        line-height: 20px;
        height: 20px;
        padding: 3px 5px;
    }

    .icon-box {
        height: 55px;
        width: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-size: cover;
        // background-position-x: -6.5px;
        // background-position-y: -7px;
        position: relative;
        // margin-top: -5px;
    }

    .icon-point-eventPoint {
        background-image: url('@/assets/images/patrolAndRescue/map/eventPoint.png');
    }

    .icon-point-taskPoint {
        background-image: url('@/assets/images/patrolAndRescue/map/taskPoint.png');
    }

    .icon-point-jyPlacePoint {
        background-image: url('@/assets/images/patrolAndRescue/map/jyPlacePoint.png');
    }

    .icon-point-xcPlacePoint {
        background-image: url('@/assets/images/patrolAndRescue/map/xcPlacePoint.png');
    }

    .icon-point-xcCarPoint {
        background-image: url('@/assets/images/patrolAndRescue/map/xcCar.png');
    }

    .icon-point-jyCarPoint {
        background-image: url('@/assets/images/patrolAndRescue/map/sosCar.png');
    }


    .text-box-bg-1 {
        background: #004a59;
        box-shadow: inset 0px 0px 4px 0px #1affd9;
        border: 1px solid #1affd9;
    }

    .text-box-bg-2 {
        background: #59522d;
        box-shadow: inset 0px 0px 4px 0px #ffea80;
        border: 1px solid #ffea80;
    }

    .text-box-bg-3 {
        background: #59301b;
        box-shadow: inset 0px 0px 4px 0px #ff884d;
        border: 1px solid #ff884d;
    }

    .text-box-bg-4 {
        background: #59202b;
        box-shadow: inset 0px 0px 4px 0px #f35675;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #f35675;
    }
}
</style>