<template>
    <div class="hidden max-w max-h" >
        <div class="max-w" style="height: calc(100% + 35px);" id="distribution_map"></div>
    </div>
    
</template>
<script>
import { defineComponent, reactive, onMounted, toRefs } from "vue";
import xianjiegeojson from "/public/config/临沂市县界.json";
import { postMethodCommon, getMethodCommon } from "../../../api/common";
import axios from 'axios'
import { BASE_API } from "/public/config/server.js";
export default defineComponent({
    components: {
        
    },
    setup(props, context) { 
        const data = reactive({
            mapBox: '',    
        })
        onMounted(() => {           
            methods.mapInit()       
        });
        const methods = {
            mapInit() {
                // mapboxgl.accessToken = 'pk.eyJ1IjoieHVqaW5nbGlhbmciLCJhIjoiY2w3bzFzZnZqMjdieTN1cG92N2I1d2huOSJ9.aQqMz4S-cTziUYizIH_gNg';
                mapboxgl.accessToken = '123'
                var map = new mapboxgl.Map({
                    container: 'distribution_map',
                    style: {
                        glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
                        "version": 8,
                        "sources": {},
                        "layers": []
                    },
                    zoom: 7.7,
                    center: [ 118.33206615680547, 35.280140501608024 ],
                });
                data.mapBox = map
                let bigCount = 0;
                let smallCount = 99999;
                let unit = (bigCount - smallCount) / 12;
                let colorSelect;
                colorSelect = ['interpolate', ['linear'], ['get', 'count'],
                    smallCount, '#43E1F8',
                    smallCount + unit * 2, '#49B0F9',
                    smallCount + unit * 3, '#3EABFA',
                    smallCount + unit * 4, '#27A2FB',
                    smallCount + unit * 5, '#34E6B1',
                    smallCount + unit * 6, '#1099FB',
                    smallCount + unit * 7, '#0695FB',
                    smallCount + unit * 8, '#058DEE',
                    smallCount + unit * 9, '#09C78E',
                    smallCount + unit * 10, '#047DD4',
                    smallCount + unit * 11, '#94D515',
                    smallCount + unit * 12, '#0568B0',
                ]
                map.on('load', function () {
                    methods.getListData()
                    // 镇界图层面
                    map.addSource("townshipSource", {
                        'type': 'geojson',
                        'data': xianjiegeojson
                    });

                   
                    // 镇界图层线
                    map.addLayer({
                        'id': 'townshipLayerLine',
                        'type': 'line',
                        'source': 'townshipSource',
                        'layout': {},
                        'paint': {
                            'line-color': "#216EFA",
                            'line-width': 1,
                            // 'line-pattern':1
                        }
                    });
                    map.addSource("states", {
                        "type": "geojson",
                        "data": xianjiegeojson
                    });
                    map.addLayer({
                        "id": "state-fills",
                        "type": "fill",
                        "source": "states",
                        "layout": {},
                        "paint": {
                            "fill-color": "#62A8FF",
                            "fill-opacity": ["case",
                                ["boolean", ["feature-state", "hover"], false],
                                1,
                                0.6
                            ]
                        }
                    });
                    map.addLayer({
                        id: "china_symbol",
                        type: "symbol",
                        source: "states",
                        paint: {
                            "text-opacity": [
                            "case",
                            ["boolean", ["feature-state", "hover"], false],
                            1,
                            0.8,
                            ],
                        },
                        layout: {
                            "text-field": "{xzqmc}",
                            "text-font": ["Open Sans Semibold"],
                            "text-anchor": "center",
                            // "text-offset": [0, 0.6],
                            // "icon-image": "monument-15",
                            // "icon-anchor": "center",
                            // "icon-allow-overlap": true,
                            // "icon-keep-upright": false,
                            "symbol-placement": "point",
                        },
                    });

                    
                    let hoveredStateId = null;
                    let popup = new mapboxgl.Popup({
                        closeButton: false,
                        closeOnClick: false,

                    }); 
                    setTimeout(()=>{
                        let socketJDArr = []
                        let socketData = JSON.parse(localStorage.getItem("socketJDArr"));
                        console.log('socketData', socketData)
                        socketData.forEach((item,index) =>{
                            let el = document.createElement('div');
                            // el.setAttribute("data-caseIds", index);
                            el.innerHTML = item.value
                            let uavimgCon = document.createElement("div");
                            uavimgCon.className = "jdmarkbox";
                            uavimgCon.appendChild(el);
                            let UAVmarker = new mapboxgl.Marker(uavimgCon).setLngLat(item.latlng);
                            UAVmarker.addTo(data.mapBox)
                        })
                    }, 3000)
                    
                })
            },
            getListData(){
                let param = {
                    // id: "a31215f5-e2eb-4bd7-ad6b-f8fd08bd82c7",
                    // mid: "9c027ef9-cc04-4006-831d-e799982f6435",
                    id: "cf16f568-4bb8-43b9-8e49-b23105e70bda",
                    mid: "9c027ef9-cc04-4006-831d-e799982f6435",
                    paginationInputDto: {
                        page: 1,
                        rows: 10000
                    }
                }
                
                postMethodCommon("/FormScheme/GetFormDataPage?id=" + param.id + "&mid="+param.mid, param).then(res =>{
                    let rel = res.data.result.items
                    let popup = new mapboxgl.Popup({
                        closeButton: false,
                        closeOnClick: false,

                    });
                    let socketIngLatArr = []
                    let socketData = JSON.parse(localStorage.getItem("socketIngLatArr"));
                    if(socketData){
                        socketIngLatArr = socketData
                    }
         
                    if(rel){
                        rel.forEach(item =>{
                            let el = document.createElement('div');
                            el.setAttribute("data-caseId", item.name);
                            let uavimgCon = document.createElement("div");
                            uavimgCon.className = "background2";
                            // if(item.type1=="1"){  
                            //     uavimgCon.className = "2";
                            // }else if(item.type1=="订单服务"){  
                            //     uavimgCon.className = "background2";
                            // }else if(item.type1=="3"){  
                            //     uavimgCon.className = "background3";
                            // }else if(item.type1=="4"){  
                            //     avimgCon.className = "background4";
                            // }
                            uavimgCon.appendChild(el);
                            el.className = "uavmarker";
                            // el.onclick = function(){
                            //     let str = "单位：" + item.name + "<br><br>地址：" + item.address + "<br><br>需求：" + item.type + "<br><br>简介：" + item.descript;
                            //     popup.setLngLat([item.lng, item.lat]).setHTML("<p style='color:#333;font-weight:bold;'>" + str + "</p>").addTo(data.mapBox);
                            
                            // }   

                            if (item.imgsrc) {
                                item.src = BASE_API + item.imgsrc.split(",")[0] || null,
                                item.srcArr = item.imgsrc.split(',')                         
                            } 

                            if (item.imgsrc1) {
                                item.src1 = BASE_API + item.imgsrc1.split(",")[0] || null,
                                item.srcArr1 = item.imgsrc1.split(',')                         
                            }
                            
                            let pointArr = []
                            let keyValue = null
                            if(item.address){
                                keyValue = item.address
                            }else{
                                keyValue = item.town
                            }
                            if(socketData && socketData.length>0){
                                socketData.forEach(val =>{
                                    if(val.name == item.name){
                                        pointArr = val.latlng
                                    }
                                })
                            }else{
                                const myGeo = new BMap.Geocoder();
                                myGeo.getPoint(keyValue, (point) => {
                                    if (point) {
                                        // 地理编码成功，返回经纬度坐标对象
                                        pointArr.push(point.lng,point.lat)
                                        pointArr =  pointArr.filter((item, index) => {  
                                            return pointArr.indexOf(item) === index;  
                                        });  
                                        socketIngLatArr.push({
                                            latlng: pointArr,
                                            name: item.name,
                                            location: keyValue
                                        })
                                    } else {
                                        // 地理编码失败
                                        console.log('地理编码失败');
                                    }
                                }, '全国');
             
                            }
                            
                            
                            setTimeout(()=>{
                                if(pointArr.length == 0){
                                    // const point = methods.getPointByAddress(keyValue);
                                    const myGeo = new BMap.Geocoder();
                                    myGeo.getPoint(keyValue, (point) => {
                                        if (point) {
                                            // 地理编码成功，返回经纬度坐标对象
                                            pointArr.push(point.lng,point.lat)
                                            pointArr =  pointArr.filter((item, index) => {  
                                                return pointArr.indexOf(item) === index;  
                                            });
                                            socketIngLatArr.push({
                                                latlng: pointArr,
                                                name: item.name,
                                                location: keyValue
                                            })
                                        } else {
                                            // 地理编码失败
                                            console.log('地理编码失败');
                                        }
                                    }, '全国');
                                    
                                }
                            },500)
                            
                            el.onmouseover = function(){
                                let str = "单位名称：" + item.name + "<br><br>地址：" + item.address + "<br><br>联系人：" + item.contacts + "<br><br>联系方式：" + item.phone + "<br><br>简介：" + item.descript;
                                popup.setLngLat(pointArr).setHTML("<p style='color:#333;font-weight:bold;'>" + str + "</p>").addTo(data.mapBox);
                            
                            }     
                            el.onmouseleave = function(){                              
                                popup.remove();
                            }     
                            el.onclick = function(){
                                let obj = {
                                    index: '2',
                                    record: item,
                                }
                                context.emit('godetails', obj)
                            }   
                            setTimeout(()=>{
                                if(pointArr){
                                    let coordinate = pointArr;
                        
                                    let UAVmarker = new mapboxgl.Marker(uavimgCon).setLngLat(coordinate);
                                    UAVmarker.addTo(data.mapBox)
                                }
                                
                            },1000)
                            
                        })
                        setTimeout(()=>{
                            const mapa = new Map();
                            const newArr = socketIngLatArr.filter(v => !mapa.has(v.name) && mapa.set(v.name, v));
                            localStorage.setItem("socketIngLatArr", JSON.stringify(newArr));
                        },2000)
                        
                    }
                })
            },
            // 根据地址名称获取经纬度坐标
            getPointByAddress(address) {
                // 创建地理编码实例
                const myGeo = new BMap.Geocoder();
                return new Promise((resolve, reject) => {
                    // 对地址进行地理编码
                    
                });
            },
        };
        return {
            ...data,
            ...methods,
        };
    },
});
</script>
<style>
.uavmarker{
    width: 10px;
    height: 10px;
    border-radius: 10px;
}
.jdmarkbox{
    width: 28px;
    height: 28px;
    border-radius: 28px;
    line-height: 28px;
    font-size: 18px;
    background: #122B87;
    color: #fff;
}
.background1{
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background: #F805F1;
}

.background2{
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background: #fd6040;
}

.background3{
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background: #F5CE06;
}
.background4{
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background: #47C4BB;
}
</style>