<template>
    <div class="full-width " style="height: 60vh;" id="mapgl_box"></div>
</template>

<script lang="ts" setup>
import MapService from '@/services/MapService';
import MapboxLanguage from '@mapbox/mapbox-gl-language';
import mapboxgl from 'mapbox-gl';
import { onMounted, ref } from 'vue';

const props = withDefaults(defineProps<{
  scrollwheelZoom?: boolean
  doubleClickZoom?: boolean
}>(), {
  scrollwheelZoom: true,
  doubleClickZoom: true
})

mapboxgl.accessToken = 'pk.eyJ1IjoiYWxleDkwMTIiLCJhIjoiY2xtOGw4NHdkMGFndTNjcnFkeWZncGc2dyJ9.lVrAdPHE0Dg5zoWFidfj4Q'
const map = ref<mapboxgl.Map>()


const initMapHandle = ()=>{
    map.value = new mapboxgl.Map({
      container: 'mapgl_box',
      style: 'mapbox://styles/alex9012/cm1en7ee8000901prhbv5auuw',
      center: [-74.5, 40],
      zoom: 10,
      maxZoom:11,
      minZoom:3,
      scrollZoom:props.scrollwheelZoom,
      doubleClickZoom:props.doubleClickZoom
    });

    map.value.addControl(new MapboxLanguage({
      defaultLanguage:'zh-Hans'
    }))
    
    setTimeout(() => {
      map.value?.resize()
    }, 500);
    // 使用 Mapbox Directions API 计算导航信息
    // const directionsClient = map.get
    // directionsClient.setOrigin(start);
    // directionsClient.setDestination(end);

    // directionsClient.on('response', (response) => {
    //   if (response.routes.length > 0) {
    //     const route = response.routes[0];
    //     console.log('导航信息：', route);
    //     // 可以根据导航信息进行路线绘制等操作
    //   } else {
    //     console.error('未找到导航路线。');
    //   }
    // });

    // directionsClient.send();
}

const directionsInfoHandle = async ()=>{
  // 定义起点和终点坐标
  const start = [11.59838875578771,48.1498484882143];
  const end = [11.646071564986642,48.157168731123306];
  const result = await MapService.queryDirectionsInfoAsync('driving-traffic',start,end)

  // 提取导航距离（单位：米）
  const distance = result.routes[0].distance;
  // 提取用时（单位：秒）
  const duration = result.routes[0].duration;
  const steps = formatStepsHandle(result.routes[0].legs[0].steps);
  console.log(`距离：${formatDistanceHandle(distance)}，用时：${formatSecondsAsHHMMSSHandle(duration)}`)
  console.log(`步骤如下：`,steps)
}

const formatDistanceHandle=(source:any)=>{
  if(isNaN(source)) return '0公里'
  source = Math.floor(source)
  if(source<1000) return `${source}米`
  else return `${(source/1000).toFixed(1)}公里`
}

const formatSecondsAsHHMMSSHandle = (seconds: number): string => {
  seconds = Math.floor(seconds)
  let hours = Math.floor(seconds / 3600);
  let minutes = Math.floor((seconds % 3600) / 60);
  let secs = seconds % 60;

  hours = hours < 10 ? 0+ hours : hours;
  minutes = minutes < 10 ? 0 + minutes : minutes;
  secs = secs < 10 ? 0 + secs : secs;

  let result = ``
  if(hours>0) result = `${hours}小时`
  if(minutes>0) result += `${minutes}分钟`
  if(secs>0 && result=='') result = `${secs}秒`
  return result;
}

const formatStepsHandle = (steps:any[])=>{
  let newStep:Array<{durat:string,dist:string,remark:string}> = []
  newStep = steps.map((x:any)=>{
    return {
      dist:formatDistanceHandle(x.distance),
      durat:formatSecondsAsHHMMSSHandle(x.duration),
      remark:x.maneuver.instruction
    }
  })
  return newStep
}

onMounted(()=>{
  initMapHandle()
  directionsInfoHandle()
})
</script>

<style>
.mapboxgl-control-container{
  display: none!important;
}

</style>