<template>
  <div
    id="container"
    class="mapContainer"
  />
</template>

<script setup lang='ts'>
import AMapLoader from '@amap/amap-jsapi-loader'
import { onMounted, ref } from 'vue'
import useStore from '@/pages/store/index'
import { useNotification } from 'naive-ui'
import img36 from '@/assets/img/36.png'

const store = useStore()
const notification = useNotification()
const props = withDefaults(defineProps<{
  zoom?: number
}>(), {
  zoom: 15
})
let Maps = null as Any
let AMaps = null as Any
window._AMapSecurityConfig = {
  securityJsCode: '184c86be3bbd9a8a941bcaaf6b09c7cd'
}

function getAllRings(feature: { geometry: { coordinates: Any[]; }; }) {
  const coords = feature.geometry.coordinates
  const rings = []
  for (let i = 0, len = coords.length; i < len; i++) {
    rings.push(coords[i][0])
  }
  return rings
}

function getLongestRing(feature: { geometry: { coordinates: Any[]; }; }) {
  const rings = getAllRings(feature)
  rings.sort((a, b) => b.length - a.length)
  return rings[0]
}

function addMark(position:number[], icon:string, size?:{w:number, h:number}) {
  if (!Maps) return
  const mark = new AMaps.Marker({
    position,
    cursor: 'pointer',
    icon: new AMaps.Icon({
      image: icon,
      imageSize: new AMaps.Size(size?.w || 24, size?.h || 24)
    }),
    autoRotation: true,
    offset: new AMaps.Pixel(-5, -20),
    angle: 0,
    anchor: 'center',
    extData: '1'// 设置自定义属性
  })
  Maps.add(mark)
}

onMounted(() => {
  AMapLoader.load({
    key: '0c5c83112cafefa77154769b4433c3df',
    version: '2.0',
    plugins: [ 'AMap.DistrictSearch', 'AMap.Weather', 'AMap.Bounds', 'AMap.Driving' ],
    AMapUI: {
      version: '1.1',
      plugins: [ 'geo/DistrictExplorer' ]
    }
  }).then((AMap) => {
    console.log(123, AMap)
    const map = new AMap.Map('container', { // 设置地图容器id
      zoom: props.zoom, // 设置当前显示级别
      expandZoomRange: true, // 开启显示范围设置
      zooms: [ 9, 20 ], // 最小显示级别为7，最大显示级别为20
      center: [ 103.001033, 29.987722 ], // 设置地图中心点位置
      mapStyle: 'amap://styles/grey'
    })
    // 限制位置 getBounds()
    const bounds = new AMap.Bounds(
      [ 103.395136, 30.936781 ], // 右上角经纬度 northEast
      [ 101.93598, 28.845463 ] // 左下角经纬度 southWest
    )
    map.setLimitBounds(bounds)
    // 天气
    const weather = new AMap.Weather()
    weather.getLive('雅安市', (err: any, data: Any) => {
      console.log('天气', err, data)
      if (err) {
        notification.warning({
          content: '天气获取失败',
          duration: 2000
        })
        return
      }
      store.setWeather(data)
    })
    // 添加mark
    const mark = new AMap.Marker({
      title: 'test',
      position: [ 103.006916, 29.983835 ],
      cursor: 'pointer',
      icon: new AMap.Icon({
        image: img36,
        imageSize: new AMap.Size(36, 36)
      }),
      autoRotation: true,
      offset: new AMap.Pixel(-5, -20),
      angle: 0,
      anchor: 'center',
      extData: '1'// 设置自定义属性
    })
    map.add(mark)
    // 镂空雅安 511800 adcode
    AMapUI.loadUI([ 'geo/DistrictExplorer' ], (DistrictExplorer: any) => {
      const districtExplorer = new DistrictExplorer({ map })
      districtExplorer.loadMultiAreaNodes([ 100000, 511800 ], (error: any, areaNodes: string | any[]) => {
        const countryNode = areaNodes[0]
        const cityNodes = areaNodes.slice(1)
        const path = []
        // 首先放置背景区域，这里是大陆的边界
        path.push(getLongestRing(countryNode.getParentFeature()))

        for (let i = 0, len = cityNodes.length; i < len; i++) {
          // 逐个放置需要镂空的市级区域
          path.push(...getAllRings(cityNodes[i].getParentFeature()))
        }
        // 绘制带环多边形
        const polygon = new AMap.Polygon({
          bubble: true,
          lineJoin: 'round',
          strokeColor: '#030E25', // 线颜色
          strokeOpacity: 1, // 线透明度
          strokeWeight: 1, // 线宽
          fillColor: '#030E25', // 填充色
          fillOpacity: 1, // 填充透明度
          map,
          path
        })
      })
    })
    // 增加路线
    const driving = new AMap.Driving({
      map
    })

    // 根据起终点名称规划驾车导航路线
    driving.search([
      { keyword: '鑫源大厦', city: '雅安市' },
      { keyword: '雅安农业大学', city: '雅安市' }
    ], (status:string, result:Any) => {
      if (status === 'complete') {
        // const { routes } = result
        // const paths = routes[0].steps.map((el: { path: Any }) => (el.path))
        console.log('导航数据获取成功', result)
        // const polyline = new AMap.Polyline({
        //   path: paths,
        //   strokeWeight: 5,
        //   borderWeight: 5, // 线条宽度，默认为 1
        //   strokeColor: 'red', // 线条颜色
        //   lineJoin: 'bevel', // 折线拐点连接处样式
        //   geodesic: true
        // })
        // map.add(polyline)
      } else {
        console.error(`获取驾车数据失败：${result}`)
      }
    })
    Maps = map
    AMaps = AMap
  })
})
</script>

<style lang="scss" scoped>
.mapContainer {
  width: 100%;
  height: 100%;
  mask-image: radial-gradient(circle at center, #030E25 70%, transparent 76%);
}
</style>