<script setup lang="tsx">
import AMapLoader from '@amap/amap-jsapi-loader'
import { onMounted, onUnmounted, computed, ref } from 'vue'
import mapIcon from '../../assets/imgs/location.png'
import { BaseButton } from '../Button'

const map = ref(null)
const myAMap = ref(null)
const carMarker = ref(null)

const props = defineProps({
  points: {
    required: true,
    type: Array
  }
})

const currentCenter = computed(() => {
  return props.points[0]?.longitude ? [props.points[0]?.longitude, props.points[0]?.latitude] : null
})

const lineArr = computed(() => {
  return props.points.map((item) => [Number(item.longitude), Number(item.latitude)])
})

const markers = computed(() => {
  return props.points.map((item) => {
    return {
      position: [item.longitude, item.latitude],
      title: item.place,
      time: item?.happenTime
    }
  })
})

const createPopupContent = (item) => {
  return `
    <div class="infoWindow">
       <div class="time">轨迹发生时间：${item.time}</div>
       <div class="time">轨迹点位：${item.position}</div>
       <div class="title">详细地址：${item.title}</div>

    </div>
 `
}

const initMap = () => {
  console.log('initmap')
  //@ts-ignore
  window._AMapSecurityConfig = {
    // securityJsCode: "2bf102f50b193a7b1e67ad563a98ad76"
    securityJsCode: 'fb811f3c271a305025b0f95fd4817635'
  }

  AMapLoader.load({
    // key: "147364b1245d25e8df44278a4bb1e96a", // 申请好的Web端开发者Key，首次调用 load 时必填
    key: 'c73bccc87d2ae5998db5acf2d183128f', // 申请好的Web端开发者Key，首次调用 load 时必填
    // version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.MoveAnimation'
      // "AMap.Scale",
      // "AMap.PlaceSearch",
      // "AMap.AutoComplete",
      // "AMap.Geocoder"
    ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    AMapUI: {
      // 是否加载 AMapUI，缺省不加载
      // version: "1.1", // AMapUI 版本
      // plugins: ["misc/PathSimplifier"] // 需要加载的 AMapUI ui插件
    }
  })
    .then((AMap) => {
      myAMap.value = AMap
      console.log(currentCenter.value, 'props.points')
      console.log(lineArr.value, 'lineArr')
      map.value = new AMap.Map('OrbitMap', {
        // 设置地图容器id
        resizeEnable: true,
        // viewMode: "3D", // 是否为3D地图模式
        zoom: 17, // 初始化地图级别
        center: currentCenter.value || [116.397428, 39.90923] // 初始化地图中心点位置
      })
      // map.on("moveend", mapMoveend);
      carMarker.value = new AMap.Marker({
        map: map.value,
        position: currentCenter.value,
        icon: 'https://webapi.amap.com/images/car.png',
        offset: new AMap.Pixel(-26, -5),
        autoRotation: true,
        angle: -90
      })

      const polyline = new AMap.Polyline({
        map: map.value,
        path: lineArr.value,
        showDir: true,
        strokeColor: '#28F', //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      })

      const passedPolyline = new AMap.Polyline({
        map: map.value,
        // path: lineArr,
        strokeColor: '#AF5', //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      })

      carMarker.value.on('moving', function (e) {
        passedPolyline.setPath(e.passedPath)
      })

      markers.value.forEach((item, i) => {
        const startIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(38, 38),
          // 图标的取图地址
          image: mapIcon,
          // 图标所用图片大小
          imageSize: new AMap.Size(38, 38),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(0, 0)
        })

        const marker = new AMap.Marker({
          position: item?.position,
          map: map.value,
          icon: startIcon,
          offset: new AMap.Pixel(-20, -20)
        })
        const infoWindow = new AMap.InfoWindow({
          isCustom: true,
          offset: new AMap.Pixel(0, -10),
          content: createPopupContent(item),
          closeWhenClickMap: true
        })
        // marker.content = "我是第" + (i + 1) + "个Marker";
        marker.on('click', function (e) {
          infoWindow.open(map.value, e.target.getPosition())
        })

        // marker.emit("click", { target: marker });
      })
      // function markerClick(e) {
      //   infoWindow.setContent(e.target.content);
      //   infoWindow.open(map, e.target.getPosition());
      // }

      map.value.setFitView()
    })
    .catch((error) => {
      console.log(error, 'map error!!!!!')
    })
}

function start() {
  console.log(carMarker.value.moveAlong)
  carMarker.value.moveAlong(lineArr.value, {
    // 每一段的时长
    duration: 1500, //可根据实际采集时间间隔设置
    // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
    autoRotation: false
  })
}

function pause() {
  carMarker.value.pauseMove()
}

function end() {
  carMarker.value.stopMove()
}

function markerContinue() {
  carMarker.value.resumeMove()
}

onMounted(() => {
  console.log('map onMounted', map)
  if (!map.value) {
    initMap()
  }
})

onUnmounted(() => {
  console.log('map unmounted')
  map?.value.destroy()
  map.value = null
})
</script>

<template>
  <div class="orbitContainer">
    <div id="OrbitMap" ref="mapIdRef"></div>
    <div class="btnArea">
      <BaseButton size="small" type="primary" @click="start">开始 </BaseButton>
      <BaseButton size="small" type="primary" @click="pause">暂停 </BaseButton>
      <BaseButton size="small" type="primary" @click="markerContinue">继续 </BaseButton>
      <BaseButton size="small" type="primary" @click="end">结束</BaseButton>
    </div>
  </div>
</template>

<style scoped lang="less">
#OrbitMap {
  width: 100%;
  height: 100%;
}

:deep(.infoWindow) {
  padding: 10px;
  width: 260px;
  background: #ffffff;
}

.orbitContainer {
  width: 100%;
  height: 100%;
  position: relative;
}

.btnArea {
  position: absolute;
  bottom: 0;
  left: 0;
  background: #ffffff;
  padding: 10px;
  display: flex;
  gap: 10px;
  width: 180px;
  flex-wrap: wrap;
}
</style>
