<template>
  <div class="map-container">
    <div id="mapContainer" class="map-box"></div>
    <!-- <div class="map-control">
        <img
          v-for="(item, index) in nextMapControl"
          :key="index"
          :src="item.icon"
          :title="item.title"
          @click="handlerMapControlClick(item.handler)"
        />
        <img v-show="nextMapControl.length > 0" @click="handlerUnDraw" src="/del.png" title="清除" />
      </div> -->

      <!-- layer list -->
      <div class="layer-workspace" :style="{'left':showLayerList?'0px':'-356px'}">
        <LayerComponent
            @changeOpenModal="changeOpenModal"
            @changeOpenInsertShpModal="changeOpenInsertShpModal"
            :layerList="layerList"
            @clearLayerList="handlerClearLayerList"
            @handlerLayerShowChange="handlerLayerControler"
            @handlerGetTableList="handlerGetTableList"
          />
          <div class="close-layer-workspace" @click="changeLayerList">
            <MenuFoldOutlined v-if="showLayerList" />
            <MenuUnfoldOutlined v-else />
          </div>
      </div>


    <LayerControl @draw="handlerDrawPolygon" :style="{'left':showLayerList?'386px':'20px'}" />
    <UseModal v-model:openModal="openModal" @changeOpenModal="changeOpenModal" @handlerAddToLayerList="handlerAddToLayerList" />
    <InsertShp v-model:openModal="insertShpModal" />
    <!-- <AddLayer v-model:openModal="insertShpModal" /> -->

    <!--  table data list -->
    <DataListComponent v-if="DataTableList" />

    <!-- attribute  -->
    <RightShowInfo :openModal="openRightInfo" />

    
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, onUnmounted, defineProps, reactive, ref, defineExpose } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import  { Map, Popup } from 'mapbox-gl';
  import heatGeoJson from './lib/data.json'

  // 图形绘制工具类
  import MapboxDraw from '@mapbox/mapbox-gl-draw';
  
  import U from 'mapbox-gl-utils';
  import 'mapbox-gl/dist/mapbox-gl.css';
  import './src/index.less';
  import { MapboxConfig, MapboxDefaultStyle, MapControlConfig } from './src/config';
  import { MP } from './src/MP';
  import { DrawingType } from '@/enums/mapEnum';
  import {MenuFoldOutlined,MenuUnfoldOutlined} from '@ant-design/icons-vue'
  import {
    SnapPolygonMode,
    SnapPointMode,
    SnapLineMode,
    SnapModeDrawStyles,
    SnapDirectSelect,
  } from 'mapbox-gl-draw-snap-mode';
  import LayerComponent from './LayerComponent/index.vue';
  import LayerControl from './LayerControl/index.vue';
  import UseModal from './Modal/index.vue';
  import InsertShp from './InsertShp/index.vue';
  import AddLayer from './AddLayer/index.vue';
  import DataListComponent from './DataListComponent/index.vue';
  import RightShowInfo from './RightShowInfo/index.vue';
  
  import proj4 from 'proj4';
  // let fromProjection = "+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs";
  let fromProjection = "+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=39500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs"
  // let toProjection = "+proj=longlat +ellps=GRS80 +no_defs +type=crs"
  let toProjection = "+proj=longlat +datum=WGS84 +no_defs +type=crs";

  // let coordinates = [39591762.54875996,3908085.3169043385];
  let coordinates = [39592654.90645946,3909001.5344353705]
  const converted = proj4(fromProjection, toProjection, coordinates);
  // alert(converted)

  const openModal = ref(false);
  const insertShpModal = ref(false);
  const openRightInfo = ref(false);
  const changeOpenModal = (value) => {
    openModal.value = value;
  };
  const changeOpenInsertShpModal = (value) => {
    insertShpModal.value = value;
  };

  // layer list 
  const showLayerList = ref<boolean>(false);
  const changeLayerList = ()=>{
    showLayerList.value = !showLayerList.value;
  }

  const layerList = ref<[]>([]);
  const handlerAddToLayerList = (value) => {
    layerList.value.push(value);
    console.log("layerList.value",layerList.value);
  }

  const handlerClearLayerList = () => {
    layerList.value = [];
  }

  // map参数类型
  interface MapboxOptionsInterface {
    mapOptions: mapboxgl.MapboxOptions;
    control: DrawingType[];
  }
  const props = defineProps<MapboxOptionsInterface>();

  let nextMapControl: Array<any> = reactive([]);
  nextMapControl = props.control
    ? props.control.map((item) => {
        console.log('item::: ', item);
        return MapControlConfig[item];
      })
    : [];

  console.log('nextMapControl::: ', nextMapControl);

  // 定义地图容器
  let map: Map;
  let popup: Popup;
  let clickPoisition: Array<number> = [];
  let selectFeature: Object = {};
  let mp: any = null;

  const { createConfirm, createMessage } = useMessage();

  // 定义地图回调emit
  // 地图加载完成回调
  const emit = defineEmits(['mapOnLoad', 'mapDraw']);

  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;

    map = initMap();
    map.on('load', () => {



      // map.addLayer({
      //   'id': 'wms-test-layer',
      //   'type': 'raster',
      //   'source': {
      //     'type': 'raster',
      //     'tiles': [
      //       // "http://175.27.168.120:8080/geoserver/feixian/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&TRANSPARENT=true&LAYERS=feixian%3Ayingxiang_17&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4548&STYLES=&WIDTH=728&HEIGHT=768&BBOX=586801.5388788335%2C3908183.1422136417%2C590270.7583843566%2C3911848.0123377703",
      //       // "http://175.27.168.120:8080/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian:yingxiang_17&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE"
      //       "http://60.213.14.14:8060/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian:yingxiang&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE"
      //     ],
      //     'tileSize': 256
      //   },
      //   'paint': {}
      // });

      map.addSource('radar', {
          'type': 'image',
          // 'url': 'http://175.27.168.120:8080/geoserver/feixian/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&TRANSPARENT=true&LAYERS=feixian%3Ayingxiang_17&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4548&STYLES=&WIDTH=728&HEIGHT=768&BBOX=586801.5388788335%2C3908183.1422136417%2C590270.7583843566%2C3911848.0123377703',
          // 'url':"http://175.27.168.120:8080/geoserver/feixian/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&TRANSPARENT=true&LAYERS=feixian%3Ayingxiang_17&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4548&STYLES=&WIDTH=727&HEIGHT=768&BBOX=591035.9133569683%2C3908525.08342436%2C591469.2675472646%2C3908982.893941982",
          'url':"http://60.213.14.14:8060/geoserver/feixian/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fjpeg&TRANSPARENT=true&LAYERS=feixian%3Ayingxiang&exceptions=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A4527&STYLES=&WIDTH=1024&HEIGHT=1024&BBOX=39591762.54875996%2C3908085.3169043385%2C39592654.90645946%2C3909001.5344353705",
          'coordinates': [


              // EPSG:4548
              // [118.00090749819051,35.30579563806707],
              // [118.0057224793592,35.30579563806707],
              // [118.0057224793592,35.30170937770571],
              // [118.00090749819051,35.30170937770571],

              // EPSG:4527
              // [118.00884630303432,35.3058545162185],
              // [118.01875909202998,35.3058545162185],
              // [118.01875909202998,35.29767983003392],
              // [118.00884630303432,35.29767983003392],

              [118.00884630303432,35.30585451621851],
              [118.01875909202998,35.30585451621851],
              [118.01875909202998,35.297679830033914],
              [118.00884630303432,35.297679830033914],

              // [39591762.54875996,3909001.5344353705],
              // [39592654.90645946,3909001.5344353705],
              // [39592654.90645946,3908085.3169043385],
              // [39591762.54875996,3908085.3169043385],
          ]
      });
      map.addLayer({
          id: 'radar-layer',
          'type': 'raster',
          'source': 'radar',
          'paint': {
              'raster-fade-duration': 0
          }
      });

      map.addSource('earthquakes', {
          'type': 'geojson',
          'data': heatGeoJson
      });

      map.addLayer(
          {
              'id': 'earthquakes-heat',
              'type': 'heatmap',
              'source': 'earthquakes',
              // 'maxzoom': 18,
              'minzoom':11,
              'paint': {
                  // Increase the heatmap weight based on frequency and property magnitude
                  'heatmap-weight': [
                      'interpolate',
                      ['linear'],
                      ['get', 'mag'],
                      0,
                      1,
                      1,
                      0
                  ],
                  // Increase the heatmap color weight weight by zoom level
                  // heatmap-intensity is a multiplier on top of heatmap-weight
                  'heatmap-intensity': [
                      'interpolate',
                      ['linear'],
                      ['zoom'],
                      0,
                      1,
                      9,
                      3
                  ],
                  // Color ramp for heatmap.  Domain is 0 (low) to 1 (high).
                  // Begin color ramp at 0-stop with a 0-transparancy color
                  // to create a blur-like effect.
                  'heatmap-color': [
                      'interpolate',
                      ['linear'],
                      ['heatmap-density'],
                      0,
                      'rgba(33,102,172,0)',
                      0.2,
                      'rgb(103,169,207)',
                      0.4,
                      'rgb(209,229,240)',
                      0.6,
                      'rgb(253,219,199)',
                      0.8,
                      'rgb(239,138,98)',
                      1,
                      'rgb(178,24,43)'
                  ],
                  // Adjust the heatmap radius by zoom level
                  'heatmap-radius': [
                      'interpolate',['linear'],['zoom'],
                      3,
                      6,
                      9,
                      20
                  ],
                  // Transition from heatmap to circle layer by zoom level
                  'heatmap-opacity': [
                      'interpolate',
                      ['linear'],
                      ['zoom'],
                      7,
                      1,
                      8,
                      1
                  ]
              }
          }
      );



      //挂载mapbox-gl-utils
      // U.init(map);
      mp = new MP(map);
      emit('mapOnLoad', map);

      // 初始化绘图空间
      handlerInitDrawTool();

      map.on('click', (e) => {
        clickPoisition = e.lngLat;
      });

      map.on('draw.selectionchange', (e) => {
        handlerCopyToTargetLayer(e);
      });

      window.handlerCopyFeature = handlerCopyFeature;
    });
  });
  // 销毁地图
  // 移除地图实例
  onUnmounted(() => {
    map ? map.remove() : null;
  });
  // 初始化地图
  // 返回地图实例
  const initMap = () => {
    return new mapboxgl.Map({
      container: 'mapContainer',
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: MapboxDefaultStyle,
      maxZoom: 22,
      minZoom: 1,
      zoom:10,
      // ...props.mapOptions,
      center:[117.984425,35.270654],
    });
  };

  const handlerMapControlClick = (handler: string) => {
    handler === 'handlerDrawPoint' && handlerDrawPoint();
    handler === 'handlerDrawLineString' && handlerDrawLineString();
    handler === 'handlerDrawPolygon' && handlerDrawPolygon();
  };
  //绘制点
  const handlerDrawPoint = () => {
    mp.draw('Point');
    mp.on('Point', function (e) {
      emit('mapDraw', 'Point', e);
    });
  };
  //绘制线
  const handlerDrawLineString = () => {
    mp.draw('LineString');
    mp.on('LineString', function (e) {
      emit('mapDraw', 'LineString', e);
    });
  };
  //绘制面
  const handlerDrawPolygon = () => {
    mp.draw('Polygon');
    mp.on('Polygon', function (e) {
      emit('mapDraw', 'Polygon', e);
    });
  };
  //删除标记
  const handlerUnDraw = () => {
    mp.deleteDraw();
    emit('mapDraw', 'cancel');
  };

  // 初始化绘图空间
  const handlerInitDrawTool = () => {
    let drawTool = new MapboxDraw({
      modes: {
        ...MapboxDraw.modes,
        draw_point: SnapPointMode,
        draw_polygon: SnapPolygonMode,
        draw_line_string: SnapLineMode,
        direct_select: SnapDirectSelect,
      },
      // Styling guides
      styles: SnapModeDrawStyles,
      userProperties: true,
      // Config snapping features
      snap: true,
      snapOptions: {
        snapPx: 15, // defaults to 15
        snapToMidPoints: true, // defaults to false
        snapVertexPriorityDistance: 0.0025, // defaults to 1.25
      },
      guides: true,
    });

    // map.addControl(drawTool, 'top-right');
  };

  // 将图斑复制到指定图层
  const handlerCopyToTargetLayer = (e) => {
    if (e.features.length > 0) {
      if (popup) {
        popup.remove();
        popup = null;
      }

      selectFeature = e.features[0];

      popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false,
      });

      // 设置 popup 的位置和内容
      popup
        .setLngLat(clickPoisition)
        .setHTML(
          `
                  <div style="color:#333;padding:3px 12px;cursor:pointer;" type="primary" icon="el-icon-search" onclick="handlerCopyFeature();">复制当前图斑</div>`,
        )
        .addTo(map);
    } else {
      popup.remove();
    }
  };

  const handlerCopyFeature = () => {
    console.log(selectFeature);
    popup.remove();
    createMessage.success('复制成功！');
  };

  const handlerRenderLayer = (layer) => {
    console.log('layerInfo', layer);
  };

  defineExpose({
    handlerRenderLayer,
  });


  const handlerLayerControler = (layerInfo) => {

    layerInfo.layer = layerInfo.layer? layerInfo.layer : JSON.parse(layerInfo.style);

    if (map.getSource(layerInfo.layer.id)) {
      if (layerInfo.checked) {
        map.setLayoutProperty(layerInfo.layer.id, 'visibility', 'visible');
      } else {
        map.setLayoutProperty(layerInfo.layer.id, 'visibility', 'none');
      }
    } else {
      map.addLayer(layerInfo.layer);
      map.on('click', layerInfo.layer.id, function (e) {
        handlerPreviewFeatureInfo(e);
      });
    }
  };

  // 图斑属性查看
  const handlerPreviewFeatureInfo = (e) => {
    if (e.features) {
      openRightInfo.value = true;
    }
  };


  const DataTableList = ref<Boolean>(false);
  const handlerGetTableList = ()=>{
    DataTableList.value = true;
  }

</script>

<style scoped>
  .layer-control-center p {
    margin: 0px;
  }

  .draw-control-center {
    position: absolute;
    padding: 7px;
    top: 15px;
    right: 15px;
    background: #ffffff;
    border-radius: 12px;
  }

  .draw-control-center .draw-btn {
    float: left;
    margin: 0px 6px;
    padding: 5px;
    border-radius: 5px;
  }

  .draw-control-center .draw-btn:hover {
    background-color: rgb(0 0 0/5%);
    cursor: pointer;
  }

  .mapboxgl-ctrl-group:not(:empty) {
    box-shadow: none;
  }

  .mapboxgl-ctrl-group {
    padding: 10px;
    border-radius: 12px;
    position: relative;
    right: 140px;
    top: 5px;
  }
  .mapbox-gl-draw_ctrl-draw-btn {
    width: 20px !important;
    height: 20px !important;
    float: left;
  }

  .mapboxgl-ctrl-top-right {
  }

  .mapboxgl-ctrl-group button + button {
    border: 0px;
    margin: 0px 6px;
  }

  .mapbox-gl-draw_ctrl-draw-btn:hover {
    transform: scale(1.2);
  }

  .mapbox-gl-draw_polygon {
    background-image: url(/polygon.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
  }
  .mapbox-gl-draw_point {
    background-image: url(/point.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
  }
  .mapbox-gl-draw_line {
    background-image: url(/line.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
    margin: 0px 6px;
  }

  .mapbox-gl-draw_trash {
    background-image: url(/del.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
  }

  .mapbox-gl-draw_combine {
    background-image: url(/combine.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
  }

  .mapbox-gl-draw_uncombine {
    background-image: url(/uncombine.png);
    background-size: 100% 100%;
    width: 100px;
    height: 100px;
  }
  .layer-workspace{
    position:absolute;
    top:0px;
    left:0px;
    height:100%;
  }
  .close-layer-workspace{
    position: absolute;
    bottom:20px;
    left:355px;
    width:30px;
    height:30px;
    background:#e0e5ed;
    z-index:9999;
    line-height: 30px;
    text-align: center;
    border-top-right-radius:4px;
    border-bottom-right-radius:4px;
    cursor:pointer;
  }
</style>
