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

<script lang="ts" setup>
  import {
    onMounted,
    onUnmounted,
    defineProps,
    defineEmits,
    reactive,
    ref,
    defineExpose,
    watch,
    inject,
  } from 'vue';
  import mapboxgl, { Map, Popup } from 'mapbox-gl';
  // 图形绘制工具类
  import MapboxDraw from '@mapbox/mapbox-gl-draw';
  import { generateUUID, getGeometryCenter } from './src/tool';
  import 'mapbox-extensions/dist/index.css';
  import U from 'mapbox-gl-utils';
  import 'mapbox-gl/dist/mapbox-gl.css';
  import * as turf from '@turf/turf';
  import './src/index.less';
  import { MapboxConfig, MapboxDefaultStyle, MapControlConfig } from './src/config';
  import { MP } from './src/MP';
  import {
    SnapPolygonMode,
    SnapPointMode,
    SnapLineMode,
    SnapModeDrawStyles,
    SnapDirectSelect,
  } from 'mapbox-gl-draw-snap-mode';
  import { customDrawStyles } from './Styles/Styles';
  import { WktToGeojson, GeojsonToWkt } from './src/WktGeojsonTransform';
  import { getPolygonCenter } from '@/api/tiankongdi/index'
import { message } from 'ant-design-vue';
  const mapContainerName = ref<String>();
  mapContainerName.value = 'mapContainer-' + generateUUID();
  const props = defineProps(['geoms','id','isRead']);
  const emit = defineEmits(['handlerDrawComplete'])
  

  // 定义地图容器
  let map: Map;
  let drawTool: any;
  let clickPoisition: Array<number> = [];
  let mp: any = null;
  let geojson = reactive({
    geojson: {},
  });
  let drawing = ref(false);
  let geoms = ref<any>([])
  let hasPolygon = false;
  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    map = initMap();
    map.on('load', () => {
      //挂载mapbox-gl-utils
      U.init(map);
      mp = new MP(map)
      // 初始化绘图空间
      handlerInitDrawTool();
      map.on('click', (e) => {
        console.log('click',e)
        clickPoisition = e.lngLat;
      });
      // 设置绘图监听事件
      map.on('draw.create', function (e) {
        if (hasPolygon) {
          drawTool.delete(e.features[0].id);
          message.warning("只能绘制一个图斑，请先删除已有的！");
          return;
        }
        hasPolygon = true;
        handlerDealFeature(e.features[0]);
      });
      map.on('draw.update', function (e) {
        handlerDealFeature(e.features[0]);
      });
      map.on('draw.delete', function (e) {
        hasPolygon = false;
        handlerDeleteFeature(e.features[0]);
      });
      map.on("draw.selectionchange", (e) => {
        e.features.forEach(feature => {
          if (feature.properties.user_static) {
            drawTool.changeMode("simple_select", { featureIds: [] }); // 取消选中
          }
        });
      });
      let filter = '"RelationId"=\'' + props.id + "'";
      getPolygonCenter({ tablename: 'idle_shp', filter: filter }).then(res => {
        if(res.length > 0){
          try {
            let geojson = WktToGeojson(res[0].centroid_point);
            map.flyTo({
              center: geojson.coordinates,
              zoom: 17.2,
              bearing: 0,
              speed: 1, // 飞行速度
              curve: 2, // 飞行曲线
              essential: true,
              easing(t) {
                // 飞行动画函数
                return t;
              },
            });
          } catch (e) {
            console.log(e)
          }
        }
      });
    });
  });
  // 移除地图实例
  onUnmounted(() => {
    map ? map.remove() : null;
  });
  // 初始化地图 返回地图实例
  const initMap = () => {
    return new mapboxgl.Map({
      container: mapContainerName.value,
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: MapboxDefaultStyle,
      minZoom: 1,
      maxZoom: 24,
      zoom: 10,
      pitch: 0,
      center: [118.340253, 35.092481],
    });
  };
    // 初始化绘图空间
    const handlerInitDrawTool = (feature, bool) => {
    geojson.geojson = feature;

    if (drawTool) {
      drawTool.deleteAll();
      if (feature.features) {
        drawTool.set(geojson.geojson);
      }
    } else {
      drawTool = new MapboxDraw({
        displayControlsDefault: false,
        controls: {
          polygon: props.isRead? false: true, // 仅显示“绘制多边形”按钮
          trash: props.isRead? false: true // 仅显示“删除”按钮
        },
        modes: {
          ...MapboxDraw.modes,
          draw_point: SnapPointMode,
          draw_polygon: SnapPolygonMode,
          draw_line_string: SnapLineMode,
          direct_select: SnapDirectSelect,
        },
        styles: customDrawStyles,
        userProperties: true,
        snap: true,
        snapOptions: {
          snapPx: 12, // defaults to 15
          snapToMidPoints: true, // defaults to false
          snapVertexPriorityDistance: 0.0025, // defaults to 1.25
        },
        guides: false,
      });
      map.addControl(drawTool, 'top-right');
      setTimeout(() => {
        document.querySelector(".mapbox-gl-draw_polygon")?.setAttribute("title", "绘制图斑");
        document.querySelector(".mapbox-gl-draw_trash")?.setAttribute("title", "删除图斑");
      }, 500);
      // let featureList:any = []
      props.geoms.forEach(item => {
        const geojsonPolygon = WktToGeojson(item.geom)
        console.log('geojsonPolygon',geojsonPolygon)
        const featureId = `polygon-${generateUUID()}`;
        let properties = {}
        if(props.isRead){
          properties = { user_static: true}
        }
        const feature = {
          id: featureId,
          type: "Feature",
          properties,
          geometry: geojsonPolygon
        };
        geoms.value.push(feature)
        // featureList.push(feature)
        hasPolygon = true
        drawTool.add(feature);
      })
      // console.log('featureList',featureList)
      // drawTool.add(featureList);
    }
    drawing.value = true;
  };
  
  // 数据绘制完成判断
  const handlerDealFeature = (feature) => {
    if(map.getLayer('area-label')){
      map.removeLayer('area-label');
      map.removeSource('area-label');
    }
    let area = turf.area(feature);
    const centroid = turf.centroid(feature);
    let labelText = `${area.toFixed(2)} m²`;
    map.addLayer({
      id: `area-label`, // 确保 ID 唯一
      type: "symbol",
      source: {
        type: "geojson",
        data: centroid
      },
      layout: {
        "text-field": labelText, // 显示面积
        "text-size": 14,
        "text-anchor": "center"
      },
      paint: {
        "text-color": "#ff0000"
      }
    });
    let existFeature = geoms.value.find((item, index) => {
      return item.id == feature.id;
    });
    if (existFeature) {
      // 如果查找到了 则替换数据
      for (let i = 0; i < geoms.value.length; i++) {
        if (geoms.value[i].id == feature.id) {
          geoms.value[i] = feature;
        }
      }
    } else {
      // 如果没找到数据则添加到数组
      geoms.value.push(feature);
    }
    // 自动将数据返回给父组件
    handlerDrawComplete();
  };
    // 删除数据
  const handlerDeleteFeature = (feature) => {
    if(map.getLayer('area-label')){
      map.removeLayer('area-label');
      map.removeSource('area-label');
    }
    for (let i = 0; i < geoms.value.length; i++) {
      if (geoms.value[i].id == feature.id) {
        geoms.value.splice(i, 1);
      }
    }
    handlerDrawComplete();
  };
  const handlerDrawComplete = () => {
    let arr = [];
    geoms.value.forEach((item, index) => {
      let wktStr = GeojsonToWkt(item.geometry);
      let area = turf.area(item).toFixed(2)
      let obj = {
        area: area,
        geom: wktStr,
      };
      arr.push(obj);
    });
    emit('handlerDrawComplete', arr);
  };
</script>

<style scoped>
  .cloud-query-div {
    position: absolute;
    top: 50px;
    left: 10px;
    width: 66px;
    height: 66px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 5px;
    border-radius: 5px;
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
    user-select: none;
    cursor: pointer;
  }
  .cloud-query-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
  }
  .map-container {
    width: 100%;
    height: 100%;
  }

  .map-box {
    width: 100%;
    height: 100%;
  }

  .layer-control-center {
    position: absolute;
    top: 15px;
    left: 15px;
    background: #fff;
    border-radius: 8px;
  }

  .layer-control-center p {
    margin: 0px;
  }

  .layer-control-center .ant-checkbox-wrapper {
  }

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

  .draw-control-center .draw-btn {
    float: left;
    margin: 0px 7px;
    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: 6px;
    border-radius: 12px;
    top: 5px;
    right: 0px;
  }
  .mapbox-gl-draw_ctrl-draw-btn {
    width: 20px !important;
    height: 20px !important;
    float: left;
  }

  .mapboxgl-ctrl-top-right {
    width: 360px;
  }

  .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;
  }

  .jas-ctrl-measure {
    position: relative;
    top: 6px;
    right: 10px;
  }

  .jas-ctrl-measure-item {
    height: 22px;
    color: rgb(255, 255, 255);
  }

  .layer-item {
    padding: 8px 16px;
  }

  .layer-item:hover {
    background: #c7dcf580;
  }

  ::v-deep .ant-collapse-content-box {
    padding: 0px !important;
  }

  ::v-deep .jas-ctrl-extend-desktop-container {
    width: 320px !important;
  }

  .position-by-lnglat {
    height: 29px;
    background: #fff;
    position: absolute;
    top: 10px;
    right: 131px;
    border-radius: 3px;
    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.1);
    .to-location {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/location.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }

    .picture-azimuth {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/is_show_picture.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }

    .picture-azimuth-active {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/not_show_picture.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }

    .draw-polygon {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/draw_polygon.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }

    .split-line {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/split_polygon.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }

    .split-polygon {
      width: 29px;
      height: 29px;
      float: left;
      background: url(/map/split_polygon_polygon.png);
      background-size: 20px 20px;
      background-repeat: no-repeat;
      background-position: 4px 5px;
      &:hover {
        cursor: pointer;
      }
    }
  }

  .to-location-input {
    padding: 16px;
    padding-right: 4px;
    width: 418px;
    min-height: 60px;
    background: #fff;
    position: absolute;
    top: 48px;
    right: 10px;
    z-index: 999999;
    border-radius: 5px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    .location-operation {
      width: 100%;
      height: 40px;
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 12px;
    }
    .location-item-list-coantienr {
      width: 100%;
      max-height: 400px;
      overflow-y: auto;
      .location-item {
        line-height: 20px;
        margin-bottom: 6px;
      }
    }
  }

  .split-panel-item:hover {
    cursor: pointer;
    color: #999;
  }

  .cloudqueryNotice {
    background: rgba(0, 0, 0, 0.53);
    padding: 0px 14px;
    border-radius: 6px;
    position: fixed;
    top: 20px;
    right: 5vw;
    width: 700px;
    color: #fff;
    z-index: 10;
    .cloudquery-title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
    }
    .cloudquery-left {
      display: flex;
      align-items: center;
    }
    .cloudquery-right {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 130px;
    }
    img {
      width: 34px;
      height: 29px;
    }
    .cloudquery-btn {
      display: flex;
      justify-content: flex-end;
    }
    .line {
      background: #ededed;
      width: 1px;
      height: 20px;
    }
    .anticon.anticon-close {
      height: 30px;
    }
    button {
      width: 70px;
      height: 26px;
      background: linear-gradient(-74deg, #086dec, #0b4bdd);
      box-shadow: 3px 4px 5px 1px rgba(13, 13, 13, 0.05);
      border-radius: 16px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .title-box {
      margin-left: 10px;
      font-size: 14px;
    }
  }
</style>
