<template>
    <div :id="mapContainerName" class="map-container">

    </div>
</template>
<script lang="ts" setup>
import {ref,onMounted,defineExpose,defineEmits} from "vue";
import { generateUUID} from '@/components/MapboxMaps/src/tool'
import { WktToGeojson } from '@/components/MapboxMaps/src/WktGeojsonTransform';
import  mapboxgl,{ Map, Popup } from 'mapbox-gl';
import {MAPBOX_TOKEN,TINADITU_TOKEN,MAP_VIEWER} from './config.ts'
import heatGeoJson from './data.json'
import {getPolygonCenter,getUserOrgs} from '@/api/tiankongdi'
import axios from 'axios'

import { getAppEnvConfig } from '@/utils/env';
const { VITE_GLOB_API_URL } = getAppEnvConfig();
const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL);

const mapContainerName = ref<String>()
mapContainerName.value = "mapContainer-"+generateUUID();
// 

const emits = defineEmits(["onload","handlerGetDetails"])

let map:Map;

// init map
const initMap = () => {
    return new mapboxgl.Map({
        container:mapContainerName.value,
        language: 'zh-cmn',
        projection: 'equirectangular', // wgs84参考系
        style: {
            glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
            version: 8,
            sources: {
                'raster-tiles': {
                type: 'raster',
                tiles: [
                    `https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
                ],
                tileSize: 256,
                },
            },
            layers: [
                {
                id: 'tdt-img-tiles',
                type: 'raster',
                source: 'raster-tiles',
                minzoom: 0,
                maxzoom: 18,
                },
            ],
        },
        maxZoom:18,
        minZoom:1,
        zoom: 10,
        pitch:0,
        center: [117.984425,35.270654],
    });
};

// 获取图斑面数据
const polygonVisibility = ref<String>("visible");

async function handlerCheckUserOrgs(){
    let orgs =await getUserOrgs({});
    let isLevel = orgs.find((item,index)=>{
        return (item.name == "临沂市" || item.parentId == 0 || item.parentName == "根节点");
    })
    if(isLevel){
        handlerLoadPolygon("","","","1")
    }else{
        handlerLoadPolygon()
    }
}

function handlerLoadPolygon(code="",filter="",type="",level=""){
    let sql_filter;
    if(code){
        sql_filter = "&filter=\"countyid\"=\'"+code+"\'";
    }else{
        sql_filter=""
    }
    let map_filter;
    switch(filter){
        case "合法":
            map_filter = ["all",["==", ["get", "is_illegal"], 0],["==", ["get", "handle_status_id"], 5]];
            break;
        case "违法":
            map_filter = ["any",["==", ["get", "is_illegal"], 1],["!=", ["get", "handle_status_id"], 5]];
            break;
        case "其他":
            map_filter = ["all",["==", ["get", "is_illegal"], 2],["==", ["get", "handle_status_id"], 5]];
            break;
        case "补办手续":
            map_filter = ["all",["==", ["get", "measure_name"], 0],["==", ["get", "handle_status_id"], 5]];
            break;
        case "拆除复耕":
            map_filter = ["all",["==", ["get", "measure_name"], 1],["==", ["get", "handle_status_id"], 5]];
            break;
        default:
            map_filter = ["!=", ["get", "gid"], 0];
    }
    let type_filter;
    switch(type){
        case "农用地":
            type_filter = ["==", ["get", "typename"], "农用地"];
            break;
        case "建设用地":
            type_filter = ["==", ["get", "typename"], "建设用地"];
            break;
        case "推堆土":
            type_filter = ["==", ["get", "typename"], "推堆土"];
            break;
    }
    if(filter && type){
        map_filter.push(type_filter);
    }else if(!filter && type){
        map_filter = ["all",["!=", ["get", "gid"], 0],type_filter];
    }
    if(map.getSource("historyLayerLine")){
        polygonVisibility.value = map.getLayoutProperty('historyLayerLine', 'visibility');
        map.removeLayer("historyLayerLine")
        map.removeLayer("historyLayerFill")
        map.removeSource("historyLayerLine")
        map.removeSource("historyLayerFill");
    }

    if(level){

    }else{
        sql_filter = '&filter=streetid in ( select CAST(\"OrgId\" AS VARCHAR) from sys_userorg where \"UserId\" = '+localStorage.getItem('userid')+') or countyid in ( select CAST(\"OrgId\" AS VARCHAR) from sys_userorg where \"UserId\" = '+localStorage.getItem('userid')+')'
    }
    
    map.addLayer(
        {
          'id': 'historyLayerLine',
          'type': 'line',
          'source': {
            type: 'vector',
            tiles: [VITE_GLOB_API_URL_VAR.value+'/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data&'+sql_filter+'&field=\"gid\",\"handle_status_id\",\"is_illegal\",\"measure_name\",\"typename\",\"Id\",'],
            minzoom: 1,
            maxzoom: 20
          },
          "source-layer": "view_drone_shp_data",
          'layout': {
            'line-join': 'round',
            'line-cap': 'round',
            'visibility':polygonVisibility.value,
          },
          'filter':map_filter,
          'paint': {
            'line-color': [
              "case",
              ["all",["==", ["get", "is_illegal"], 0],["==", ["get", "handle_status_id"], 5]],  //合法
              "#FFECB9",
              ["any",["==", ["get", "is_illegal"], 1],["!=", ["get", "handle_status_id"], 5]], //违法
              "#FDA1A1",
              ["all",["==", ["get", "is_illegal"], 2],["==", ["get", "handle_status_id"], 5]], //其他
              "#C7FFBC",
              ["all",["==", ["get", "measure_name"], 0],["==", ["get", "handle_status_id"], 5]], //补办手续
              "#ABFCFF",
              ["all",["==", ["get", "measure_name"], 1],["==", ["get", "handle_status_id"], 5]], //拆除复耕
              "#C2B3FB",
              // 默认
              "#FDA1A1",
            ],
            'line-width': 4
          }
        }
    )
    map.addLayer({
          'id': 'historyLayerFill',
          'type': 'fill',
          'source': {
            type: 'vector',
            tiles: [VITE_GLOB_API_URL_VAR.value+'/api/DroneCaseInfoSingle/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data'+sql_filter+'&field=\"gid\",\"handle_status_id\",\"is_illegal\",\"measure_name\",\"typename\",\"Id\",'],
            // 
            minzoom: 1,
            maxzoom: 20
          },
          "source-layer": "view_drone_shp_data",
          'filter':map_filter,
          'layout':{
            'visibility':polygonVisibility.value,
          },
          'paint': {
            'fill-color': [
                "case",
                ["all",["==", ["get", "is_illegal"], 0],["==", ["get", "handle_status_id"], 5]],  //合法
                "#FFECB9",
                ["any",["==", ["get", "is_illegal"], 1],["!=", ["get", "handle_status_id"], 5]], //违法
                "#FDA1A1",
                ["all",["==", ["get", "is_illegal"], 2],["==", ["get", "handle_status_id"], 5]], //其他
                "#C7FFBC",
                ["all",["==", ["get", "measure_name"], 0],["==", ["get", "handle_status_id"], 5]], //补办手续
                "#ABFCFF",
                ["all",["==", ["get", "measure_name"], 1],["==", ["get", "handle_status_id"], 5]], //拆除复耕
                "#C2B3FB",
                // 默认
                "#FDA1A1",
            ],
            'fill-opacity': 0.3
          }
    })
    emits("onload");

    map.on("click","historyLayerFill",(e)=>{
       emits("handlerGetDetails",e.features[0].properties);
    })
}

// 获取和处理图斑点数据
const currentCode = ref("")
async function handlerDealPoint(code=""){
    let sql_filter;
    if(code){
        sql_filter = "\"countyid\"=\'"+code+"\'";
    }else{
        sql_filter=""
    }
    let points = await getPolygonCenter({tablename:"view_drone_shp_data",filter:sql_filter})
    
    let heatdata = {
        type: "FeatureCollection",
        features:[]
    }
    points?.forEach((item,index)=>{
        let geometry = WktToGeojson(item['centroid_point']);
        let feature = {
            geometry:geometry,
            properties:{
                mag:1
            }
        }
        heatdata.features.push(feature);
    })

    handlerLoadHeatLayer(heatdata);

    if(map.getLayer('clusters')){
        map.moveLayer("clusters","heatLayer");
        map.moveLayer("cluster-count","heatLayer")
        map.moveLayer("unclustered-point","heatLayer")
    }

}

// 加载热力图图斑数据
function handlerLoadHeatLayer(heatdata){
    if(map.getSource("heatSource")){
        map.getSource("heatSource").setData(heatdata);
    }else{
        map.addSource('heatSource', {
            'type': 'geojson',
            'data': heatdata
        });
        map.addLayer(
            {
                'id': 'heatLayer',
                'type': 'heatmap',
                'source': 'heatSource',
                'maxzoom': 13,
                'minzoom':7,
                'layout':{
                    "visibility":"none"
                },
                'paint': {
                    'heatmap-weight': [
                        'interpolate',
                        ['linear'],
                        ['get', 'mag'],
                        0,
                        1,
                        7,
                        0
                    ],
                    'heatmap-intensity': [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        0,
                        1,
                        9,
                        3
                    ],
                    'heatmap-color': [
                        'interpolate',
                        ['linear'],
                        ['heatmap-density'],
                        0,
                        'rgba(33,102,172,0)',
                        0.2,
                        'rgba(103,169,207,0.8)',
                        0.4,
                        'rgba(209,229,240,0.8)',
                        0.6,
                        'rgba(253,219,199,0.8)',
                        0.8,
                        'rgba(239,138,98,0.8)',
                        1,
                        'rgba(178,24,43,0.8)'
                    ],
                    'heatmap-radius': [
                        'interpolate',['linear'],['zoom'],
                        4,
                        7,
                        11,
                        20
                    ],
                    'heatmap-opacity': [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        7,
                        0,
                        8,
                        1
                    ]
                }
            }
        );
    }



    if(map.getLayer('heatLayer')){
        map.moveLayer('heatLayer', 'historyLayerLine');
        map.moveLayer('heatLayer', 'historyLayerFill');
        if(map.getLayer('clusters')){
            map.moveLayer("clusters","heatLayer");
            map.moveLayer("cluster-count","heatLayer")
            map.moveLayer("unclustered-point","heatLayer")
        }
    }

    
}

// 地图定位
function handlerLocation(lngLat,zoom){
    map.flyTo({
    center: lngLat,
        zoom: zoom,
        bearing: 0,
        speed: 1, // 飞行速度
        curve: 2, // 飞行曲线
        essential: true,
        easing(t) {
            // 飞行动画函数
            return t;
        },
    });
};

// 获取县区边界数据
const handlerDealCountry = (countyName:String = "临沂市"):void=>{
    let center = {};
    let zoom;
    let filterName = "";
    if(countyName == '临沂市'){
        center ={lng: 118.72504868812163, lat: 35.180072027132915}
        zoom = 7.848587811931849;
        handlerLocation([center['lng'],center['lat']],zoom);
    }else if(countyName){
        center = MAP_VIEWER[countyName].center;
        zoom = MAP_VIEWER[countyName].zoom;
        handlerLocation([center['lng'],center['lat']],zoom);
        filterName=countyName;
    } 

    axios({
        method:"get",
        url:`http://175.27.168.120:8080/geoserver/linyishi/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=linyishi%3Axianjie&maxFeatures=50&outputFormat=application%2Fjson&cql_filter=xzqmc%20like%20%27%25${filterName}%25%27`,
    }).then(res=>{
        handlerLoadCountyLayer(res.data);
    })

}


// 渲染边界数据
const handlerLoadCountyLayer = (geojson)=>{
    // 绘制线
    if(map.getSource("countySource")){
        map.getSource("countySource").setData(geojson);
      }else{
        map.addSource("countySource",{
          type:"geojson",
          data:geojson
        })
        map.addLayer(
          {
            "id": "countyLayer",
            "type": "line",
            "source": "countySource",
            "paint": {
              'line-color': '#408eff', // 设置线的颜色
              'line-width': 2 // 设置线的宽度
            }
          }
        )
      }
}

// 控制图层显示隐层
/**
 * 热力图：heatLayer
 * 
 * 图斑线：historyLayerLine
 * 
 * 图斑面：historyLayerFill
 * 
 * 行政区划：countyLayer
 * 
 * */ 
function handlerChangeLayerVisible(layerName,checked){
    if (checked) {
        map.setLayoutProperty(layerName, 'visibility', 'visible');
    } else {
        map.setLayoutProperty(layerName, 'visibility', 'none');
    }
}

// 切换县区
function handlerChangeCounty(county,type=""){
    handlerDealCountry(county.name);
    handlerLoadPolygon(county.code,type);
    handlerDealPoint(county.code);
}



// 
onMounted(()=>{
    mapboxgl.accessToken = MAPBOX_TOKEN;
    map = initMap();
    map.on("load",()=>{

        handlerCheckUserOrgs();

        handlerDealCountry();
        map.on("click",(e)=>{
            var center = map.getCenter(); // 获取当前视图中心点
            var zoom = map.getZoom(); // 获取当前视图缩放级别
            console.log(zoom);
            console.log(center);
        })
    })
})


// 抛出函数
defineExpose({
    handlerChangeCounty,   // 切换县区
    handlerChangeLayerVisible, // 控制图层显示隐藏
    handlerLoadPolygon,
});

</script>
<style type="less" scoped>
.map-container{
    width:100%;
    height:100%;
}
::v-deep .mapboxgl-ctrl-logo{
    display: none!important;
}
</style>
