<template>
  <view class="container">
    <map
      id="map"
      class="map"
      :latitude="querys.latitude"
      :longitude="querys.longitude"
      :polyline="polyline"
      :markers="markers"
      scale="15"
      show-compass
      show-traffic
      show-locate
    >
    </map>
    <cover-view class="map-info">
      <cover-view class="title">{{ distance }}</cover-view>
      <cover-view class="sub-title">{{ taxi_cost }}</cover-view>
      <cover-view class="go" @click="goSystem">其他导航</cover-view>
    </cover-view>
  </view>
</template>

<script setup lang="ts">
import { showError } from '@/common/composeabe/ErrorDisplay';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import AppCofig from '@/common/config/AppCofig';
import { back } from '@/common/utils/PageAction';
import { ref } from 'vue';
import amapFile from '@/libs/amap-wx.130';
import { toast } from '@/common/utils/DialogAction';

const mapCtx = uni.createMapContext('map');
const polyline = ref();
const markers = ref();
const distance = ref('');
const taxi_cost = ref('');
const { querys } = useLoadQuerys({ 
  latitude: 0,  
  longitude: 0,
}, async (querys) => {
  uni.showLoading({ title: '加载中...' });
  try {
    
    if (querys.latitude == 0 || querys.longitude == 0) {
      throw new Error('传入参数不正确');
    }

    const curretLocation = await new Promise<{ latitude: number, longitude: number }>((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        success: function(res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          resolve({ latitude, longitude });
        }, 
        fail: (err) => {
          let message = err.errMsg
          if (err.errMsg.includes('auth deny')) {
            message = '请允许定位后，才能为您导航哦';
          } else if (err.errMsg.includes('location service off')) {
            message = '请未开启定位服务，才能为您导航哦';
          } 
          reject(message);
        },
      }) 
    })

    markers.value = [
      {
        id: 1,
        latitude: querys.latitude,
        longitude: querys.longitude, 
        iconPath: 'https://mn.wenlvti.net/app_static/minnan/images/icon_marker.png',
        width: 40,
        height: 40,
      },
      {
        id: 2,
        latitude: curretLocation.latitude,
        longitude: curretLocation.longitude, 
        iconPath: 'https://mn.wenlvti.net/app_static/minnan/images/icon_marker2.png',
        width: 50,
        height: 50,
      }
    ];

    function colorTrans(color1: number[], color2: number[], pec: number) {
      return [
        Math.round(color1[0] + (color2[0] - color1[0]) * pec),
        Math.round(color1[1] + (color2[1] - color1[1]) * pec),
        Math.round(color1[2] + (color2[2] - color1[2]) * pec),
      ]
    }

    polyline.value = await new Promise((resolve, reject) => {
      const color1 = [223, 53, 51];
      const color2 = [0, 145, 255];

      const myAmapFun = new amapFile.AMapWX({key:  AppCofig.amapKey});
      myAmapFun.getDrivingRoute({
        origin: `${curretLocation.longitude.toFixed(5)},${curretLocation.latitude.toFixed(5)}`,
        destination: `${querys.longitude.toFixed(5)},${querys.latitude.toFixed(5)}`,
        nosteps: 1,
        success: function(data: any){
          let points = [];
          let colorList : string[] = [];
          if(data.paths && data.paths[0] && data.paths[0].steps){
            var steps = data.paths[0].steps;
            for(var i = 0; i < steps.length; i++){
              var poLen = steps[i].polyline.split(';');
              for(var j = 0;j < poLen.length; j++){
                points.push({
                  longitude: parseFloat(poLen[j].split(',')[0]),
                  latitude: parseFloat(poLen[j].split(',')[1])
                })
              } 
            }
          } 
          for (let j = 0; j < points.length; j++) {
            colorList.push('rgb(' + colorTrans(color1, color2, j / points.length).join(',') + ')');
          }
          distance.value = '距离您约 ' + formatMeter(data.paths[0].distance) + '米'
          taxi_cost.value =  '打车约' + parseInt(data.taxi_cost) + '元'
          resolve([{
            points: points,
            color: "#0091ff",
            colorList: colorList,
            width: 6
          }]);
        },
        fail: function(info: any) {
          reject('路线规划失败：' + info);
        }
      })
    });

    mapCtx.includePoints({
      points: [
        { latitude: querys.latitude, longitude: querys.longitude },
        { latitude: curretLocation.latitude, longitude: curretLocation.longitude }
      ],
      padding: [20, 20, 20, 20],
    });
  } catch (e) {
    showError(e, undefined, () => back());
  } finally {
    uni.hideLoading();
  }
});

function goSystem() {
  uni.openLocation({
    latitude: querys.value.latitude,
    longitude: querys.value.longitude,
    scale: 15,
    name: '目标位置',
    success() {},
    fail(error) {
      toast('导航启动失败');
    },
  });
}

function formatMeter(n: number) {
  if (n > 1000) {
    return (n / 1000).toFixed(1) + '千'; 
  }
  return n + '';
}

</script>

<style lang="scss">
.container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding-bottom: 0;
  
  #map {
    width: 100%;
    height: 100%;
  }
  .map-info {
    position: absolute;
    bottom: 50px;
    left: 40rpx;
    right: 40rpx;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 8px;
    padding: 20rpx;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    .title {
      font-size: 34rpx;
      font-weight: bold;
      color: #333;
    }
    .sub-title {
      font-size: 26rpx;
      margin-top: 10rpx;
      color: #666;
    }
    .go {
      position: absolute;
      padding: 15rpx;
      background-color: #bdbdbd;
      border-radius: 10rpx;
      top: 50%;
      right: 20rpx;
      transform: translateY(-50%);
    }
  }
}
</style>