<template>
  <div class="content">
    <div class="changeServe">
      <div class="serveTitle">加载服务&nbsp;:&nbsp;</div>
      <select v-model="selected"
              @change="changeServe(selected)">
        <option v-for="item in serveList"
                :value="item.value">{{ item.text }}</option>
      </select>
    </div>
    <div class="transform">
      <div class="transformTitle">坐标转换&nbsp;:&nbsp;</div>
      <input v-model="coordinateBefore"
             type="text"
             placeholder="请输入要转换的坐标">
      <select v-model="transformSelected"
              @change="changeCoordinate(transformSelected)">
        <option v-for="item in transformList"
                :value="item.value">{{ item.text }}</option>
      </select>
      <input v-model="coordinateAfter"
             type="text">
    </div>
    <button class="aggregationGraph"
            @click="changeAggregation()">{{ aggregationGraphBtnText }}</button>
    <div id="map" />
    <div class="fitchLocation">
      <position-matching />
    </div>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import axios from 'axios'
// import * as THREE from 'three'
import { Threebox, THREE } from 'threebox-plugin'
import PositionMatching from '../../components/PositionMatching/index.vue'
import {
  loadWMS,
  removeLayer,
  loadWMTS,
  loadWFSLayer,
  loadTMSLayer,
  removeWFSLayer
} from '@/api/gis/service.js'
import normal_style from '@/assets/js/normal_style.js'
import Transform from '@/api/gis/coordinate-conversion.js'
import LoadAggregationGraph from '@/api/gis/load-aggregation-graph.js'
export default {
  name: 'HomePage',
  components: {
    PositionMatching
  },
  setup (props) {
    const router = useRouter()
    function toSystem () {
      router.push({ path: '/login' })
    }
    return {
      toSystem
    }
  },
  data () {
    return {
      map: null,
      selected: '',
      serveList: [
        { value: 'loadWFS', text: '加载WFS服务' },
        { value: 'removeWFS', text: '移除WFS服务' },
        { value: 'loadWMS', text: '加载WMS服务' },
        { value: 'removeWMS', text: '移除WMS服务' },
        { value: 'loadWMTS', text: '加载WMTS服务' },
        { value: 'removeWMTS', text: '移除WMTS服务' },
        { value: 'loadTMS', text: '加载TMS服务' },
        { value: 'removeTMS', text: '移除TMS服务' }
      ],
      marker: null,
      transformSelected: '',
      transformList: [
        { value: 'bd09togcj02', text: '百度转火星(谷歌,高德)' },
        { value: 'gcj02tobd09', text: '火星转百度' },
        { value: 'wgs84togcj02', text: 'WGS84转GCJ02' },
        { value: 'gcj02towgs84', text: 'GCJ02转WGS84' },
        { value: 'bd09towgs84', text: '百度转WGS84' },
        { value: 'wgs84tobd09', text: 'WGS84转百度' },
        { value: 'LngLatToMercator', text: '经纬度转墨卡托' },
        { value: 'MercatorToLngLat', text: '墨卡托转经纬度' }
      ],
      coordinateBefore: '',
      coordinateAfter: '',

      aggregationGraphBtnText: '加载聚合图',
      popup: null
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {
    initMap () {
      mapboxgl.accessToken = 'pk.eyJ1IjoibHh0aWFudGlhbiIsImEiOiJjaXd2ZjlkYnQwMTZvMnRtYWZnM2lpbHFvIn0.ef3rFZTr9psmLWahrqap2A'

      this.map = new mapboxgl.Map({
        container: 'map',
        center: [120.476913, 31.416667],
        zoom: 5,
        // style: {
        //   version: 8,
        //   name: 'Mapbox Streets',
        //   sources: {
        //     'osm-tiles': {
        //       type: 'raster',
        //       tiles: ['https://t0.tianditu.gov.cn/vec_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82'],

        //       tileSize: 256
        //     }
        //   },
        //   layers: [
        //     {
        //       id: '123',
        //       type: 'raster',
        //       source: 'osm-tiles',
        //       'source-layer': 'osmtiles'
        //     }
        //   ]
        // }
        style: normal_style
      })
      this.addModel()
    },
    addModel () {
      const that = this
      that.map.on('load', function () {
        that.map.addLayer({
          id: 'custom_layer',
          type: 'custom',
          renderingMode: '3d',
          onAdd: function (map, mbxContext) {
            window.tb = new Threebox(
              map,
              mbxContext,
              {
                defaultLights: true
              }
            )
            const yuan = window.tb.sphere({ radius: 5, color: 'green', material: 'MeshStandardMaterial', anchor: 'center' }).setCoords([120.476913, 31.416667, 200])
            window.tb.add(yuan)
          },
          render: function (gl, matrix) {
            window.tb.update()
          }

        })
      })
    },
    changeServe (selected) {
      switch (selected) {
        case 'loadWFS':
          this.loadWFS()
          break
        case 'removeWFS':
          this.removeWFSLayer()
          break
        case 'loadWMS':
          this.loadWMS()
          break
        case 'removeWMS':
          this.removeWMSLayer()
          break
        case 'loadWMTS':
          this.loadWMTS()
          break
        case 'removeWMTS':
          this.removeWMTSLayer()
          break
        case 'loadTMS':
          this.loadTMS()
          break
        case 'removeTMS':
          this.removeTMSLayer()
      }
    },
    changeCoordinate (transformStyle) {
      const arr = this.coordinateBefore.split(',')

      switch (transformStyle) {
        case 'bd09togcj02':

          this.coordinateAfter = Transform.bd09togcj02(arr[0], arr[1])
          break
        case 'gcj02tobd09':
          this.coordinateAfter = Transform.gcj02tobd09(arr[0], arr[1])
          break
        case 'wgs84togcj02':
          this.coordinateAfter = Transform.wgs84togcj02(arr[0], arr[1])
          break
        case 'gcj02towgs84':
          this.coordinateAfter = Transform.gcj02towgs84(arr[0], arr[1])
          break
        case 'bd09towgs84':
          this.coordinateAfter = Transform.bd09towgs84(arr[0], arr[1])
          break
        case 'wgs84tobd09':
          this.coordinateAfter = Transform.wgs84tobd09(arr[0], arr[1])
          break
        case 'LngLatToMercator':
          this.coordinateAfter = Transform.LngLatToMercator(arr[0], arr[1])
          break
        case 'MercatorToLngLat':

          this.coordinateAfter = Transform.MercatorToLngLat(arr[0], arr[1])

          break
      }
    },
    // 点击加载聚合图/移除聚合图层
    changeAggregation () {
      if (this.aggregationGraphBtnText == '加载聚合图') {
        this.aggregationGraphBtnText = '移除聚合图'
        const res = {
          data: [
            {
              gmtCreated: '2022-03-16 15:09:37',
              gmtModified: '2022-03-16 15:12:06',
              id: null,
              indexCode: 'ff8080817b0d9c18017b0ec573560001',
              lat: 33.971199372800456,
              lng: 116.24850619967219,
              name: '宜山余家墨(龙港)'
            }, {
              gmtCreated: '2022-03-16 15:09:37',
              gmtModified: '2022-03-16 15:12:06',
              id: null,
              indexCode: 'ff8080817b0d9c18017b0ec573560001',
              lat: 33.841680980672564,
              lng: 116.19175863704055,
              name: '宜山余家墨(龙港)'
            },
            {
              gmtCreated: '2022-03-16 15:09:37',
              gmtModified: '2022-03-16 15:12:06',
              id: null,
              indexCode: 'ff8080817b0d9c18017b0ec573560001',
              lat: 33.89048373379242,
              lng: 116.26471978899235,
              name: '宜山余家墨(龙港)'
            },
            {
              gmtCreated: '2022-03-16 15:09:37',
              gmtModified: '2022-03-16 15:12:06',
              id: null,
              indexCode: 'ff8080817b0d9c18017b0ec573560001',
              lat: 33.998087580885866,
              lng: 116.52211051948859,
              name: '宜山余家墨(龙港)'
            }
          ]
        }
        const json = {
          type: 'FeatureCollection',
          crs: {
            type: 'name',
            properties: { name: 'urn:ogc:def:crs:OGC:1.3:CRS84' }
          },
          features: []
        }
        res.data.forEach((item) => {
          const params = {
            type: 'Feature',
            properties: item,
            geometry: {
              coordinates: [item.lng * 1, item.lat * 1],
              type: 'Point'
            }
          }
          json.features.push(params)
        })
        this.addCluster(json)
        // const url = 'http://192.168.11.35:8999/geoserver/wfs?service=WFS&version=1.0.0&request=getFeature&typeName=sz_pg:sz_pg_china_mb_china_poi&outputFormat=application/json'
        // const url = '../../src/assets/json/heat.json'
        // const geoData = {}
        // $.getJSON('../../src/assets/json/heat.json', function (data) {
        //   console.log(data, '数据')
        //   geoData.crs = {}
        //   geoData.crs.type = 'name'
        //   geoData.crs.properties = { name: 'urn:ogc:def' }
        //   geoData.type = 'FeatureCollection'
        //   const arr = []
        //   for (let i = 0; i < data.length; i++) {
        //     const obj = {}
        //     obj.geometry = { type: 'Point', coordinates: [Number(data[i].lng), Number(data[i].lat)] }
        //     obj.id = 'china_poi.' + i
        //     obj.properties = {
        //       poi_id: i, 供电单位名称: data[i].供电单位名称, 供电设备总数: data[i].供电设备总数,
        //       农村用户户均配变容量: data[i].农村用户户均配变容量, 接户线总长度: data[i].接户线总长度
        //     }
        //     obj.type = 'Feature'
        //     obj.numberMatched = data.length
        //     obj.numberReturned = data.length
        //     obj.totalFeatures = data.length
        //     arr.push(obj)
        //   }
        //   geoData.features = arr

        //   // console.log(geoData, '数组')
        //   // let geodata={type:"FeatureCollection",features:}
        // })
        // const sourceOption = {
        //   clusterMaxZoom: 14,
        //   clusterRadius: 50
        // }
        // const layerOption = {
        //   filter: ['has', 'poi_id'],
        //   paint: {
        //     // 蓝色,当点数小于100时为20px圆
        //     // 点计数在100到750之间时为黄色,21px圆
        //     // 点计数大于或等于750时为22像素的粉红色圆圈
        //     'circle-color': [
        //       'step',
        //       ['get', 'poi_id'],
        //       'rgba(81,187,214,0.8)',
        //       100,
        //       'rgba(241,240,117,0.8)',
        //       750,
        //       'rgba(242,140,177,0.8)'
        //     ],
        //     'circle-radius': [
        //       'step',
        //       ['get', 'poi_id'],
        //       20, // 蓝色,当点数小于100时为20px圆
        //       100, // 对应上面circle-color数字,意思为100以内
        //       21, // 点计数在100到750之间为黄色,意思为750以内
        //       750, // 对应上面circle-color数字,意思为750以内
        //       22// 点计数大于或等于750时为22像素的粉红色圆圈
        //     ],
        //     // 这个是外边框的颜色 circle-stroke-color这个对应了上面circle-color
        //     'circle-stroke-color': [
        //       'step',
        //       ['get', 'poi_id'],
        //       'rgba(81,187,214,0.2)',
        //       100,
        //       'rgba(241,240,117,0.2)',
        //       750,
        //       'rgba(242,140,177,0.2)'
        //     ],
        //     // 这个是外边框渲染的范围
        //     'circle-stroke-width': [
        //       'step',
        //       ['get', 'poi_id'],
        //       5, // 蓝色晕染长度,当点数小于100时为5px晕染
        //       100, // 对应上面circle-color数字,意思为100以内
        //       6, // 点计数在100到750之间时为黄色,6px晕染
        //       750, // 对应上面circle-color数字,意思为750以内
        //       7// 点计数大于或等于750时为7px像素的粉红色晕染
        //     ]
        //   }
        // }
        // const clusterLayerOption = {
        //   filter: ['has', 'poi_id'], layout: {
        //     'text-field': '{poi_id}', // 文本内容来源字段
        //     'text-font': ['Microsoft YaHei'],
        //     'text-size': 12
        //   }, paint: {
        //     'text-color': 'hsl(0, 0%, 100%)',
        //     'text-halo-color': '#54c081',
        //     'text-halo-width': 100
        //   }
        // }
        // const unclusterLayerOption = {
        //   filter: ['!', ['has', 'poi_id']],
        //   paint: {
        //     'circle-color': '#11b4da',
        //     'circle-radius': 4,
        //     'circle-stroke-width': 1,
        //     'circle-stroke-color': '#fff'
        //   }
        // }
        // LoadAggregationGraph.loadAggregationGraph(this.map, geoData, sourceOption, layerOption, clusterLayerOption, unclusterLayerOption)
      } else {
        this.aggregationGraphBtnText = '加载聚合图'
        LoadAggregationGraph.removeLayer(this.map)
      }
    },
    addCluster (json) {
      const map = this.map
      const that = this
      if (map.getLayer('plantClusters')) {
        map.removeLayer('plantClusters')
      }
      if (map.getLayer('plant-point')) {
        map.removeLayer('plant-point')
      }
      if (map.getLayer('cluster-plant-count')) {
        map.removeLayer('cluster-plant-count')
      }
      if (map.getLayer('localLightIcon-point')) {
        map.removeLayer('localLightIcon-point')
      }
      $.getJSON('../../src/assets/json/aaa.json', function (data) {
        map.addSource('earthquakes', {
          type: 'geojson',
          // data: 'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson',
          data: data,
          cluster: true,
          clusterMaxZoom: 15, // 最大缩放到群集点
          clusterRadius: 80// 每一组点的半径(=50)
        })
        // 外围有数字的圆圈,加晕染
        map.addLayer({
          id: 'plantClusters',
          type: 'circle',
          source: 'earthquakes',
          filter: ['has', 'point_count'],
          paint: {
            // 蓝色,当点数小于100时为20px圆
            // 点计数在100到750之间时为黄色,21px圆
            // 点计数大于或等于750时为22像素的粉红色圆圈
            'circle-color': ['step',
              ['get', 'point_count'],
              '#00B9FF',
              20,
              '#00B9FF'],

            'circle-radius': [
              'step',
              ['get', 'point_count'],
              20, // 蓝色,当点数小于100时为20px圆
              100, // 对应上面circle-color数字,意思为100以内
              21, // 点计数在100到750之间为黄色,21px圆
              750, // 对应上面circle-color数字,意思为750以内
              22// 点计数大于或等于750时为22像素的粉红色圆圈
            ],
            // 这个是外边框的颜色circle-stroke-color这个对应了上面circle-color
            'circle-stroke-color': [
              'step',
              ['get', 'point_count'],
              'rgba(255,255,255,0.3)',
              100,
              'rgba(255,255,255,0.3)',
              750,
              'rgba(255,255,255,0.3)'
            ],
            'circle-stroke-width': [
              'step',
              ['get', 'point_count'],
              5, // 蓝色晕染长度,当点数小于100时为5px晕染
              100, // 对应上面circle-color数字,意思为100以内
              6, // 点计数在100到750之间为黄色,6px晕染
              750, // 对应上面circle-color数字,意思为750以内
              7// 点计数大于或等于750时为7px像素的粉红色晕染
            ]
          }
        })
        // 聚合图圆圈中的数字
        map.addLayer({
          id: 'cluster-plant-count',
          type: 'symbol',
          source: 'earthquakes',
          filter: ['has', 'point_count'],
          layout: {
            'text-field': '{point_count_abbreviated}',
            'text-font': ['Microsoft YaHei'],
            'text-size': 12
          },
          // 添加这个就可以改变圆圈内字样式,这里改变的是颜色
          paint: {
            'text-color': '#fff',
            'text-opacity': 1
          }
        })
        // 加载定位图标
        map.loadImage(
          'data:image/jpeg;base64,[encoded data, 16304 characters]',
          function (error, image) {
            if (error) {
              throw error
            }
            // 加载红旗图标
            if (map.hasImage('redFlg')) {
              map.removeImage('redFlg')
            } else {
              map.addImage('redFlg', image)
            }
            // 添加小点
            map.addLayer({
              id: 'plant-point',
              type: 'circle',
              source: 'earthquakes',
              filter: ['!', ['has', 'point_count']],
              'layout': {

              },
              'paint': {
                'circle-color': '#FC5316'
              }
            })
            // map.on('click', 'plant-point', that.flagClickHandler())
            // 单击时检查群集
            map.on('click', 'plantClusters', function (e) {
              var features = map.queryRenderedFeatures(e.point, {
                layers: ['plantClusters']
              })
              console.log(features, '集群信息')
              var clusterId = features[0].properties.cluster_id
              let prevZoom = map.getZoom()
              map.getSource('earthquakes')
                .getClusterExpansionZoom(clusterId, function (err, zoom) {
                  if (err) {
                    return
                  }
                  if (prevZoom >= 15 && prevZoom < 19.5) {
                    zoom = zoom + 1
                  }
                  map.easeTo({
                    center: features[0].geometry.coordinates,
                    zoom: zoom
                  })
                  prevZoom = zoom
                })
            })
            map.on('mouseenter', 'plantClusters', that.flagClustersHandle)
            map.on('mouseleave', 'plantClusters', function () {
              // map.getCanvas().style.cursor = ''// ?没有效果
              that.popup.remove()
            })
            map.on('mouseenter', 'plant-point', that.flagClickHandler)
            map.on('mouseleave', 'plant-point', function () {
              that.popup.remove()
            })
            // map.on('click', 'plant-point', that.flagClickHandler)
          }
        )
      })
    },
    flagClustersHandle (e) {
      console.log(e.lngLat, '点位信息')
      const position = [e.lngLat.lng, e.lngLat.lat]
      const map = this.map
      const features = map.queryRenderedFeatures(e.point, {
        layers: ['plantClusters']
      })
      console.log(features, '属性信息')

      this.popup = new mapboxgl.Popup({ closeButton: false })
        .setLngLat(position)
        .setHTML('<div><span>集群信息</span></div>')
        .addTo(this.map)
    },
    flagClickHandler (e) {
      const map = this.map
      var features = map.queryRenderedFeatures(e.point, {
        layers: ['plant-point']
      })
      var properties = features[0].properties
      this.drawMarker(properties)
    },
    drawMarker (obj) {
      if (this.marker) {
        this.marker.remove()
      }

      // this.showVideoDialog(obj.name,obj.playUrl)
      const position = [obj.longitude, obj.latitude]
      // add marker to map
      console.log(position, '位置信息')
      // this.marker = new mapboxgl.Marker('plant-point', { offset: [20, -20] })
      //   .setLngLat(position)
      //   .addTo(this.map)
      this.popup = new mapboxgl.Popup({ closeButton: false })
        .setLngLat(position)
        .setHTML('<h1>定位点</h1>')
        .addTo(this.map)
    },

    loadWFS () {
      const url =
        'http://192.168.11.35:8999/geoserver/wfs?service=WFS&version=1.0.0&request=getFeature&typeName=sz_pg:sz_pg_china_mb_china_poi&outputFormat=application/json'
      const option = { id: 'point', type: 'circle', paint: {} }
      loadWFSLayer(this.map, url, option)
    },
    removeWFSLayer () {
      const option = { id: 'point', type: 'circle', paint: {} }

      removeWFSLayer(this.map, option)
    },
    loadWMS () {
      const url =
        'http://192.168.11.35:8999/geoserver/ows?service=WMS&version=1.3.0&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=sz_pg%3Asz_pg_china_mb_china_poi'
      const option = {
        id: 'wms-layer',
        sourceId: 'wms-sourceId',
        type: 'raster',
        source: 'wms-source',
        paint: {}
      }

      loadWMS(this.map, url, option)
    },
    removeWMSLayer () {
      const url =
        'http://192.168.11.35:8999/geoserver/ows?service=WMS&version=1.3.0&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=sz_pg%3Asz_pg_china_mb_china_poi'
      const option = {
        id: 'wms-layer',
        sourceId: 'wms-sourceId',
        type: 'raster',
        source: 'wms-source',
        paint: {}
      }
      removeLayer(this.map, url, option)
    },
    loadWMTS () {
      const url =
        'http://192.168.11.35:8999/geoserver/ows?service=WMS&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=dem_test%3Ajs'
      const option = {
        id: 'wmts-layer',
        type: 'raster',
        source: 'wmts-source',
        paint: { 'raster-opacity': 0.8 }
      }

      loadWMTS(this.map, url, option)
    },
    removeWMTSLayer () {
      const url =
        'http://192.168.11.35:8999/geoserver/ows?service=WMS&request=GetLegendGraphic&format=image%2Fpng&width=20&height=20&layer=dem_test%3Ajs'
      const option = {
        id: 'wmts-layer',
        type: 'raster',
        source: 'wmts-source',
        paint: { 'raster-opacity': 0.8 }
      }
      removeLayer(this.map, url, option)
    },
    loadTMS () {
      const url = 'https://frp.t-aaron.com:28898/geoserver'
      const option = {}
      loadTMSLayer(this.map, url, option)
    },
    removeTMSLayer () {
      let url

      removeLayer(this.map, url)
    },
    transform () {
      const poi = { lng: 114.32894, lat: 30.585748 }
      const poi2 = { x: 12727039.383734727, y: 3579066.6894065156 }
      // Transform.LngLatToMercator(poi)
      // Transform.MercatorToLngLat(poi2)
      const lng_lat_1 = Transform.bd09togcj02(113.912743, 22.497629)
      const lng_lat_2 = Transform.gcj02tobd09(
        113.90624786062033,
        22.49156056685961
      )
      console.log(lng_lat_2, 'gc坐标')
    },
    flyTo (point, id) {
      console.log(point, '传过来的点!')
      this.map.flyTo({
        center: point,
        zoom: 10
      })
      if (this.map.getLayer(id)) {

      } else {
        this.map.loadImage(new URL('../../assets/img/located.png', import.meta.url).href, (error, image) => {
          if (error) throw error
          this.map.addImage(id + 'image', image)
          this.map.addLayer({
            id: id,
            type: 'symbol',
            source: {
              type: 'geojson',
              data: {
                type: 'FeatureCollection',
                features: [{
                  type: 'Feature',
                  geometry: {
                    type: 'Point',
                    coordinates: point
                  }
                }]

              }
            },
            layout: {
              'icon-image': id + 'image',

              'icon-size': 0.3,
              'icon-offset': [0, 0],
              'icon-rotation-alignment': 'map',
              'icon-pitch-alignment': 'map'
              // 'icon-keep-upright': 'map'
            }
          })
        })
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.content {
  width: 100vw;
  height: 100vh;
  position: relative;
  .changeServe {
    position: absolute;
    top: 20px;
    left: 10px;

    z-index: 100;

    .serveTitle {
      float: left;
      background-color: rgba(245, 245, 245, 0.8);
      height: 30px;
      line-height: 30px;
    }
    select {
      float: right;
      padding: 5px;
    }
  }
  .transform {
    position: absolute;
    top: 20px;
    left: 230px;
    z-index: 100;
    .transformTitle {
      background-color: rgba(245, 245, 245, 0.8);
      height: 30px;
      line-height: 30px;
      float: left;
    }
    input {
      height: 30px;
      float: left;
      padding-left: 15px;
      width: 150px;
    }
    select {
      float: left;
      padding: 5px;
    }
  }
  .aggregationGraph {
    position: absolute;
    z-index: 100;
    top: 60px;
    left: 10px;
    border: none;
    background-color: rgba(114, 159, 200, 0.5);
    padding: 5px;
    border-radius: 5px;
  }
  #map {
    width: 100%;
    height: 100%;
  }

  .fitchLocation {
    position: absolute;
    right: 30px;
    top: 20px;
  }
  .mapboxgl-popup-close-button {
    display: none !important;
  }
}
</style>
