<template>
  <div class="map h-152">
    <div id="centerMap" class="w-full h-full"></div>
    <div class="legend">
      <p class="legend_title py-0 my-1 cursor-pointer" @click="show = !show">图例</p>
      <table v-if="show">
        <tr>
          <td class="cursor-pointer">
            <div class="my-2" @click="handleClick(1)"><img class="legeng-img" :src="img1" />建设用地土壤污染状况调查地块清单</div>
            <div class="my-2" @click="handleClick(2)"><img class="legeng-img" :src="img2" />移出调查地块清单</div>
            <div class="my-2" @click="handleClick(3)"><img class="legeng-img" :src="img3" />建设用地土壤污染风险评估地块清单</div>
            <div class="my-2" @click="handleClick(4)"><img class="legeng-img" :src="img4" />移出风险评估地块清单</div>
            <div class="my-2" @click="handleClick(5)"><img class="legeng-img" :src="img5" />建设用地风险管控与修复地块清单</div>
            <div class="my-2" @click="handleClick(6)"><img class="legeng-img" :src="img6" />移出风险管控与修复地块清单</div>
            <div class="my-2" @click="handleClick(7)"><img class="legeng-img" :src="img7" />备案地块清单</div>
            <div class="my-2" @click="handleClick(8)"><img class="legeng-img" :src="img8" />预关注地块清单</div>
          </td>
        </tr>
      </table>
    </div>
	<div class="choose">
		缓冲半径
		<a-space direction="vertical">
			<a-radio-group v-model:value="distance" :options="plainOptions" />
		</a-space>
	</div>
  </div>
</template>
<script setup>
  import { ref, onMounted, nextTick, toRaw } from 'vue';
  import 'leaflet/dist/leaflet.css';
  import axios from 'axios';
  import * as L from 'leaflet';
  //   import 'leaflet.fullscreen/Control.FullScreen';
  //   import 'leaflet.fullscreen/Control.FullScreen.css';
  import 'leaflet-measure-path/leaflet-measure-path.css';
  import 'leaflet-measure-path/leaflet-measure-path.js';
  import 'leaflet.markercluster/dist/MarkerCluster.css';
  import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
  import 'leaflet.markercluster';
  import proj4 from 'proj4';
  // 引入jsts
  import WKTReader from 'jsts/org/locationtech/jts/io/WKTReader';
  import RelateOp from 'jsts/org/locationtech/jts/operation/relate/RelateOp';
  import BufferOp from 'jsts/org/locationtech/jts/operation/buffer/BufferOp';
  import WKTWriter from 'jsts/org/locationtech/jts/io/WKTWriter';
  import img1 from '@/assets/images/onePic/dcml_ic@2x.png';
  import img2 from '@/assets/images/onePic/ycdcml_ic@2x.png';
  import img3 from '@/assets/images/onePic/fxpg_ic@2x.png';
  import img4 from '@/assets/images/onePic/ycfxpg_ic@2x.png';
  import img5 from '@/assets/images/onePic/gkjxf_ic@2x.png';
  import img6 from '@/assets/images/onePic/ycfxgk_ic@2x.png';
  import img7 from '@/assets/images/onePic/ba_ic@2x.png';
  import img8 from '@/assets/images/onePic/ygz_ic@2x.png';

  import { gis } from '../../api';

  onMounted(async () => {
    await nextTick();
    initMap();
  });
  const colors = ref(['#FF8F1F', '#00B578', '#07B9B9', '#3662EC', '#8A38F5', '#9FE6B8', '#ED44A0', '#059CED']);
  const map = ref('');
  const content = ref(null);
  const show = ref(false);
  const geojsonLayer = ref(null);
  const layerGroups = ref();
  let markerClusterLayer = '';
  const poiLayer = ref(null);
  const plainOptions = ref(['1km', '3km', '5km']);
  const distance = ref('1km');

  function initMap() {
    // 23.125178, 113.280637
    map.value = L.map('centerMap', {
      center: [23.125178, 113.280637],
      zoom: 8,
      zoomControl: true,
      attributionControl: false,
      crs: L.CRS.EPSG4326, // 默认3857
      fullscreenControl: true,
      maxZoom: 17,
    });

    //定义一个比例尺控件
    let scale = L.control.scale();
    scale.addTo(toRaw(map.value));

    // 这个 比例尺的
    scale.getContainer().childNodes[0].style.cssText =
      'margin-bottom:-4px;color:#FFF;text-shadow:none;border:2px solid #FFF;background:none;border-top:0px;';

    scale.getContainer().childNodes[1].hidden = true;

    // // 经纬度投影
    const IMG_C =
      'https://t1.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=3cf92df1e46b9a576fa8d3f427030886';
    const CIA_C =
      'https://t1.tianditu.gov.cn/cia_c/wmts?layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=3cf92df1e46b9a576fa8d3f427030886';
    // 天地图注记
    const zj =
      'https://t1.tianditu.gov.cn/cia_c/wmts?layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=3cf92df1e46b9a576fa8d3f427030886';

    var myLayer1 = L.tileLayer(IMG_C, {
      zoomOffset: 1, // 经纬度投影打开
      maxZoom: 17,
      tileSize: 256,
    }).addTo(toRaw(map.value));

    var myLayer2 = L.tileLayer(CIA_C, {
      zoomOffset: 1, // 经纬度投影打开
      maxZoom: 17,
      tileSize: 256,
    }).addTo(toRaw(map.value));

    position();
  }

  async function position(v) {
    const res = await gis({ mlbs: v });
    // let arry = res.slice(0, 10);
    const arry = res.slice(0, 100);
    let layers = [];
    let color = colors.value[0];

    markerClusterLayer = L.markerClusterGroup({
      showCoverageOnHover: false,
      zoomToBoundsOnclick: true,
      chunkedLoading: true,
      maxclusterRadius: 30,
    }).addTo(toRaw(map.value));
    let geojson = res;
    let iconUrl = '';
    if (geojson) {
      let markerList = []; // 聚台标记点列表
      if (geojson.length > 0) {
        geojson.forEach((v) => {
          if (v.mlbs == 1) {
            iconUrl = img1;
          } else if (v.mlbs == 2) {
            iconUrl = img2;
          } else if (v.mlbs == 3) {
            iconUrl = img3;
          } else if (v.mlbs == 4) {
            iconUrl = img4;
          } else if (v.mlbs == 5) {
            iconUrl = img5;
          } else if (v.mlbs == 6) {
            iconUrl = img6;
          } else if (v.mlbs == 7) {
            iconUrl = img7;
          } else if (v.mlbs == 8) {
            iconUrl = img8;
          }
          // let htmlstr = `<div class="bg-[${color}] w-20px h-20px rounded-full"></div>`;
          // let iconHtml = L.divIcon({
          //   html: htmlstr,
          //   iconsize: [80, 80],
          //   backgroundColor: 'none',
          //   className: 'maps',
          // });
          let iconHtml = L.icon({
            iconUrl: iconUrl,
            iconSize: [30, 30],
          });
          let markers = L.marker([v.wd, v.jd], { icon: iconHtml });

          markers.bindPopup(
            `<div class="popu text-[#fff] text-sm">
          <div class="text-base">${v.wrdkmc}</div>
          <div class="pt-4"><span class="text-[#00C9D8] mr-2">地块编码:</span> ${v.wrdkbm}</div>
          <div class="pt-4"><span class="text-[#00C9D8] mr-2">所处阶段编码: </span>${v.scjdbm}</div>
          <div class="pt-4"><span class="text-[#00C9D8] mr-2">创建时间: </span>${v.createTsamp}</div>
          <div class="pt-4 pb-2"><span class="text-[#00C9D8] mr-2" >移除时间: </span>${v.ycsj ? v.ycsj : ''}</div>
        </div>`
          );
          markers.on('click', () => {
            within([v.jd, v.wd]);
          });
          layers.push(markers);
        });
      }
      markerClusterLayer.addLayers(layers);
    }
  }
  // 根据经纬度点[113.233, 23.11]，过滤1000m范围内的数据
  async function within(point) {
    if (poiLayer.value) {
      map.value.removeLayer(poiLayer.value);
    }
    if (!point) {
      point = [113.233, 23.11];
    }

    var firstProjection = '+proj=longlat +datum=WGS84 +no_defs +type=crs';
    var secondProjection =
      '+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs';
    let point3857 = proj4(firstProjection, secondProjection, point);
    // console.log(point3857);

    // BufferOp
    const reader = new WKTReader();
    const feature = reader.read('POINT (' + point3857[0] + ' ' + point3857[1] + ')');

	let jl = distance?distance.value:1;
	jl = jl.replace('km', '');
    let circle = BufferOp.bufferOp(feature, jl*1000);

    const writer = new WKTWriter();
    let wkt = writer.write(circle);

    let array = wkt.replace('POLYGON ((', '').replace('))', '').split(',');
    let polygon = 'POLYGON ((';
    array.forEach(function (e, index) {
      let p = proj4(secondProjection, firstProjection, [Number(e.trim().split(' ')[0]), Number(e.trim().split(' ')[1])]);
      polygon = polygon + p[0] + ' ' + p[1];
      if (index < array.length - 1) {
        polygon = polygon + ',';
      }
    });
    polygon = polygon + '))';
    // get请求查询poi点geojson数据
    let url = `http://175.6.146.33:88/geoserver/guangzhou/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=guangzhou:guangzhou-poi&maxFeatures=20000&outputFormat=application/json&${encodeURI(
      `cql_filter=WITHIN(the_geom,${polygon})`
    )}`;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var json = JSON.parse(this.responseText);
        console.log(json);

        var geojsonMarkerOptions = {
          radius: 8,
          fillColor: '#c02c38',
          color: '#000',
          weight: 1,
          opacity: 1,
          fillOpacity: 0.8,
        };
        poiLayer.value = L.geoJSON(json, {
          pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, geojsonMarkerOptions);
          },
        })
          .bindTooltip(function (layer) {
            return layer.feature.properties.name;
          })
          .addTo(toRaw(map.value));
      }
    };
    xmlhttp.open('GET', url, true);
    xmlhttp.send();
  }

  // 点击图例
  function handleClick(v) {
    clearMarker();
    position(v);
  }
  function clearMarker() {
    if (markerClusterLayer) {
      markerClusterLayer.clearLayers();
    }
  }
</script>
<style lang="less" scoped>
  .map {
    // height: 560px;
    position: relative;
  }
  // .centerMap {
  //   height: 560px;
  // }
  .legend {
    position: absolute;
    bottom: 20px;
    right: 0;
    bottom: 5px;
    color: #fff;
    z-index: 999;
    background: linear-gradient(135deg, rgba(1, 16, 45, 0.8), rgba(27, 93, 192, 0.52));
    box-shadow: inset 0px 0px 10px 0px rgba(0, 201, 216, 0.5);
    padding: 15px 20px;
    .legeng-img {
      height: 20px;
      display: inline-block;
      margin-right: 5px;
    }
    .legend_title {
      text-align: center;
      font-weight: bold;
      font-size: 16px;
    }
    .legend_describe {
      font-size: 12px;
    }
    .circle {
      width: 11px;
      height: 11px;
      border-radius: 50%;
      display: inline-block;
      // background-color: yellow;
      margin-right: 5px;
    }
  }
  :deep(.leaflet-popup-content-wrapper) {
    background: linear-gradient(135deg, rgba(3, 32, 41, 0.69), rgba(8, 75, 96, 0.8));
    box-shadow: inset 0px 0px 10px 0px rgba(0, 201, 216, 0.5);
  }
  :deep(.leaflet-popup-tip) {
    background: linear-gradient(135deg, rgba(3, 32, 41, 0.69), rgba(8, 75, 96, 1));
  }
  :deep(.leaflet-popup-close-button) {
    color: #fff !important;
  }
  .popu {
    padding: 10px 0;
  }
  .choose{
    padding: 12px;
	position: absolute;
    top: 20px;
    right: 20px;
    width: 230px;
    height: 80px;
    text-align: center;
    font-size: 16px;
    z-index: 999;
    background: linear-gradient(135deg, rgba(1, 16, 45, 0.8), rgba(27, 93, 192, 0.52));
    box-shadow: inset 0px 0px 10px 0px rgba(0, 201, 216, 0.5);
	line-height: 30px;
  }

</style>
<style lang="less">
  .choose .ant-radio-wrapper{
    color: #fff;
  }
</style>
