<template>
  <div :id="mapContainerName" class="map-container">
    <div class="search-container-box">
      <SearchComponent
        @flyToLocation="flyToLocation"
        @toPosition="toPosition"
        @handlerFilter="handlerFilter"
        :layerSettings="layerSettings"
      ></SearchComponent>
    </div>
    <div class="home-button" @click="handlerInitialize"></div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, defineExpose, defineEmits, defineProps, watch } 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.js';
  import axios from 'axios';
  import SearchComponent from './SearchComponent.vue';
  import { getAppEnvConfig } from '@/utils/env';
  const { VITE_GLOB_API_URL,VITE_GLOB_LAN_API_URL } = getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL);
  const mapContainerName = ref<String>();
  mapContainerName.value = 'mapContainer-' + generateUUID();
  const { VITE_GLOB_YINGXIANG_SERVER, VITE_GLOB_YAOGANYINGXIANG_SERVER } = getAppEnvConfig();
  import { getUserOrgs } from '@/api/tiankongdi';
""
  const networkType = ref("WAN");

  
  //
  import { TableOutlined, GlobalOutlined, HomeOutlined } from '@ant-design/icons-vue';

  // 图层控制 历史影像
  import { message, Modal } from 'ant-design-vue';
  import U from 'mapbox-gl-utils';
  import { MP } from './src/MP.js';
  import { GeojsonToWkt } from './src/WktGeojsonTransform.js';
  // import { layers } from '@/views/sys/exception/util'
  let layers = {}

  const emits = defineEmits([
    'onload',
    'handlerGetDetails',
    'showMonitor',
    'handlerQueryIntersectTif',
    'changeLoading'
  ]);

  let isZoomVisible: any = false;
  let map: Map;
  let mp: any = null;
  const props = defineProps({
    layer: Object,
    defaultColor: String,
  });
  const layerSettings = ref<any>({});
  const layerDefaultColor = ref<String>();
  watch(
    () => props.layer,
    (val) => {
      layerSettings.value = val;
      layerDefaultColor.value = props.defaultColor;
    },
  );
  const initMap = () => {
    return new mapboxgl.Map({
      container: mapContainerName.value,
      language: 'zh-cmn',
      projection: 'globe', // wgs84参考系
      style: {
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        version: 8,
        sources: {
          'raster-tiles': {
            type: 'raster',
            tiles: [
              `http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
            minzoom: 1,
            maxzoom: 17,
          },
          'raster-tiles-font': {
            type: 'raster',
            tiles: [
              `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`,
            ],
            tileSize: 256,
          }
        },
        layers: [
          {
            id: 'tdt-vec-tiles',
            type: 'raster',
            source: 'raster-tiles-font',
            maxZoom: 32,
          },
          {
            id: 'tdt-img-tiles',
            type: 'raster',
            source: 'raster-tiles',
            maxZoom: 32,
          }
          // {
          //     id: 'tdt-wms-tiles',
          //     type: 'raster',
          //     source: 'raster-tiles-geo',
          // },
        ],
      },
      maxZoom: 22,
      minZoom: 8,
      zoom: 8,
      pitch: 0,
      center: [118.30207505530701, 35.30123435040745],
    });
  };

  function loadMapInfo(){

    map = initMap();

    map.on('load', () => {
      //挂载mapbox-gl-utils
      U.init(map);
      mp = new MP(map);
      // 设置2D地图
      map.easeTo({ pitch: 0, bearing: 0, duration: 1000 });
      map.dragRotate.disable(); // 禁用拖动旋转
      map.pitchWithRotate = false; // 禁用旋转时俯仰变化
      handlerDealStreet()
      handlerDealCountry();
      handlerCheckUserOrgs()
      getMaskData()
      const sources = map.getStyle().sources;
      let loadedSources = 0;
      Object.keys(sources).forEach(sourceId => {
        map.on('sourcedata', (e) => {
          if (e.sourceId === sourceId && e.isSourceLoaded) {
            loadedSources++;
            if (loadedSources === Object.keys(sources).length) {
              console.log('所有图层关联的数据源已加载完成');
              emits('changeLoading',false)
            }
          }
        });
      });
    });
  }
  onMounted(() => {
    mapboxgl.accessToken = MAPBOX_TOKEN;

    // 获取网络环境后加载地图

    loadMapInfo();

  })
    // 回到初始视角
  const handlerInitialize = () => {
    map.flyTo({
      center: [118.30207505530701, 35.30123435040745], // 设置中心点坐标
      zoom: 8, // 设置缩放等级
      pitch: 0,
      bearing: 0,
      duration: 1000,
    });
  };

  function toPosition(item) {
    handlerLocation(item, 17.2);
  }
  function handlerFilter(item) {
  }
  async function handlerCheckUserOrgs() {
    handlerLoadPolygon();
  }
  function getMaskData() {
    map.addLayer({
      id: "linyishizhezhao",
      type: "raster",
      source: {
        type: "raster",
        tiles: [
          "http://175.27.168.120:8080/geoserver/gwc/service/wms?service=WMS&version=1.1.0&request=GetMap&layers=linyishi%3Alinyishizhezhao&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE",
        ],
        tileSize: 256,
      },
      layout: {
        visibility: "visible",
      }
    });
  }
  const handlerGetDetails = (e) => {
    emits('handlerGetDetails', e.features[0].properties, [e.lngLat.lng, e.lngLat.lat]);
  }
  const handlerNongjiGetDetails = (e) => {
    emits('handlerGetDetails', e.features[0].properties, e.features[0].geometry.coordinates);
  }
  function handlerLoadPolygon(code = '', filter = '', type = '', level = '') {
    let field_filter = '&field="SerialNumber","Type","Id",';
    map.addSource('tianditu-label', {
      type: 'raster',
      tiles: [
        `https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=${TINADITU_TOKEN}`
      ],
      tileSize: 256
    });
    map.addLayer({
      id: 'tianditu-label-layer',
      type: 'raster',
      source: 'tianditu-label',
      layout: {
        visibility: 'none',
      }
    });
    map.loadImage('/homepage/nong.png', (error, image) => {
      if (error) throw error;
      if (!map.hasImage('nongji-marker')) {
        map.addImage('nongji-marker', image);
      }
    });
    layers.forEach(layerItem => {
      const sourceId = `${layerItem.id}Source`
      map.addSource(sourceId, {
        type: 'vector',
        tiles: [
          VITE_GLOB_API_URL_VAR.value +
            '/api/IdleLand/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=' +
            layerItem.tableName +
            field_filter
        ],
        minzoom: 1,
        maxzoom: 20,
      });
      if(layerItem.id == 'nongji'){
        const layerId = `${layerItem.id}SourceLayer`
        map.addLayer({
          id: layerId,
          type: 'symbol',
          source: sourceId,
          'source-layer': layerItem.tableName, 
          layout: {
            'icon-image': 'nongji-marker', 
            'icon-size': 0.8,
            'icon-allow-overlap': true,
            'icon-anchor': 'bottom',
            visibility: 'none'
          },
        });
        map.on('click', layerId, handlerNongjiGetDetails);
      }else{
        const lineLayerId = `${layerItem.id}SourceLineLayer`
        const fillLayerId = `${layerItem.id}SourceFillLayer`
        map.addLayer({
          id: lineLayerId,
          type: 'line',
          source: sourceId,
          'source-layer': layerItem.tableName, 
          layout: {
            'line-join': 'round',
            'line-cap': 'round',
            visibility: 'none',
          },
          paint: {
            'line-color': layerItem.color,
            'line-width': 5,
          },
        });
        map.addLayer({
          id: fillLayerId,
          type: 'fill',
          source: sourceId,
          'source-layer': layerItem.tableName, 
          layout: {
            visibility: 'none',
          },
          paint: {
            'fill-color': layerItem.color,
            'fill-opacity': 0.5,
          },
        });
        map.on('click', fillLayerId, handlerGetDetails);
      }
    })
  }
    // 获取乡镇数据
  const handlerDealStreet = (countyName: String = '临沂市'): void => {
    map.addSource("zhenjie", {
      "type": "vector",
      "scheme": "tms",
      tiles: [
      "http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/linyishi%3Azhenjie@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf",
      ],
      tileSize: 512
    })
    map.addLayer({
      id: "zhenjie",
      type: "line",
      source: "zhenjie",
      'source-layer': 'zhenjie',
      layout: {
        visibility: "visible",
      },
      paint: {
        'line-color': '#42befb', // 设置线的颜色
        'line-width': 1, // 设置线的宽度
      },
      minzoom: 10,
      maxzoom: 24,
    })
    map.addSource("zhenjiepoint", {
      "type": "vector",
      "scheme": "tms",
      tiles: [
      "http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/linyishi%3Azhenjiepoint@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf",
      ],
      tileSize: 512,
    })
    map.addLayer({
      id: "zhenjiepoint",
      type: "symbol",
      source: "zhenjiepoint",
      'source-layer': 'zhenjiepoint',
      layout: {
        visibility: "visible",
          "text-field": "{xzqmc}",
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
      minzoom: 10,
      maxzoom: 24,
    });
  };
  // 获取县区边界数据
  const handlerDealCountry = (countyName: String = '临沂市'): void => {
    map.addSource("wmsSource", {
      "type": "vector",
      "scheme": "tms",
      tiles: [
      "http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/linyishi%3Axianjie@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf"
      ],
      tileSize: 512
    })
    map.addLayer({
      id: "xianjie",
      type: "line",
      source: "wmsSource",
      'source-layer': 'xianjie',
      layout: {
        visibility: "visible",
      },
      paint: {
        "line-color": "#6f7ff4",
        "line-width": 4,
      }
    })
    map.addSource("xianjiepoint", {
      "type": "vector",
      "scheme": "tms",
      tiles: [
      "http://175.27.168.120:8080/geoserver/gwc/service/tms/1.0.0/linyishi%3Alinyishixianjie_point@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf",
      ],
      tileSize: 512,
    })
    map.addLayer({
      id: "xianjiepoint",
      type: "symbol",
      source: "xianjiepoint",
      'source-layer': 'linyishixianjie_point',
      layout: {
        visibility: "visible",
          "text-field": "{xzqmc}",
          "text-size": 18
      },
      paint: {
        'text-color': '#041B36',
        'text-halo-color': '#fff',
        'text-halo-width': 2,
      },
      minzoom: 8,
      maxzoom: 10,
    });
  };
  // 地图定位
  function handlerLocation(lngLat, zoom) {
    map.flyTo({
      center: lngLat,
      zoom: zoom,
      bearing: 0,
      speed: 1, // 飞行速度
      curve: 2, // 飞行曲线
      essential: true,
      easing(t) {
        // 飞行动画函数
        return t;
      },
    });
  }
  function flyToLocation(e){
    map.flyTo({
      center: e,
      zoom: 12,
      bearing: 0,
      speed: 1, // 飞行速度
      curve: 2, // 飞行曲线
      essential: true,
      easing(t) {
        // 飞行动画函数
        return t;
      },
    });
  }
  const handlerChangeLayer = (list) => {
    const layerIds = layers.map(item => item.id);
    layerIds.forEach(id => {
      const visibility = list.includes(id) ? 'visible' : 'none';
      if(id == 'nongji'){
        const layerId = `${id}SourceLayer`
        map.setLayoutProperty(layerId, 'visibility', visibility);
      }else{
        const lineLayerId = `${id}SourceLineLayer`
        const fillLayerId = `${id}SourceFillLayer`
        map.setLayoutProperty(lineLayerId, 'visibility', visibility);
        map.setLayoutProperty(fillLayerId, 'visibility', visibility);
      }
    })
  }
  const changeTiandituLabelOpen = (type) => {
    map.setLayoutProperty('tianditu-label-layer', 'visibility', type ? 'visible' : 'none');
  }
  // 抛出函数
  defineExpose({
      handlerChangeLayer,
      changeTiandituLabelOpen
  });
</script>
<style type="less" scoped>
  .map-container {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .search-container-box {
    position: absolute;
    width: 330px;
    height: 40px;
    top: 72px;
    left: 73px;
    z-index: 9999;
  }

  .map-type-switch-container {
    width: 208px;
    height: 40px;
    position: absolute;
    top: 72px;
    right: 23px;
    z-index: 9999;
    font-size: 22px;
    color: #fff;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
  }
  .map-type-switch-container .switch-button {
    line-height: 40px;
    width: 150px;
    height: 40px;
    float: left;
    background: url(/map/change-view-btn.png);
    background-size: 100% 100%;
  }

  .map-type-switch-container .switch-button span {
    font-size: 14px;
  }

  .home-button {
    width:40px;
    height:40px;
    background: url(/map/home-btn.png);
    background-size: 100% 100%;
    float: right;
    position: relative;
    text-align: center;
    z-index: 10;
    top: 72px;
    right: 23px;
  }
  ::v-deep .mapboxgl-ctrl-logo {
    display: none !important;
  }
</style>
