<template>
  <div>

    <el-form ref="queryRef" :inline="true" :label-width=" locale ? '90px':'140px'" :model="queryParams"
             style="margin-top: 24px">
      <el-form-item label="车牌号" prop="carLicense">
        <el-input
            v-model="queryParams.carLicense"
            :placeholder=" t('common.pleaseEnter') + '车牌号'"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="dateRange">
        <el-date-picker
            v-model="dateRange"
            end-placeholder="结束日期"
            range-separator="-"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label=" ">
        <el-button icon="Search" type="primary" @click="handleQuery">{{ t('option.search') }}</el-button>
        <el-button icon="Refresh" @click="resetQuery">{{ t('option.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <div id="container3"></div>
  </div>
</template>
<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import {getTrack} from "@/api/realTimeMonitoring/historicalRoute";
import {useI18n} from 'vue-i18n';
import Cookies from "js-cookie";

const {t} = useI18n();

const locale = (Cookies.get('language') || 'zhCn') === 'zhCn'
const {proxy} = getCurrentInstance();
const queryParams = ref({})
const dateRange = ref([])
let map = null
let polyline = null
let polylinePath = ref([])
let distance = null
let text = null


let mouseTool = null

AMapLoader.load({
  key: "ba8fb8d8bae1b280b93406d5959d492f",             // 申请好的Web端开发者Key，首次调用 load 时必填
  // version: "1.4.15",      //
  version: "2.0",      //
  plugins: ['AMap.MouseTool', 'AMap.PolygonEditor', 'AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Marker', 'AMap.GraspRoad'],

  AMapUI: {
    version: '1.1',
    plugins: []
  }
}).then((AMap) => {
  map = new AMap.Map("container3", {  //设置地图容器id
    viewMode: "3D",    //是否为3D地图模式
    zoom: 16,           //初始化地图级别
    center: [116.397428, 39.90923], //初始化地图中心点位置
  });

  // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
  map.addControl(new AMap.ToolBar({position: 'LT'}));

  // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
  map.addControl(new AMap.Scale());

  // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
  map.addControl(new AMap.HawkEye({isOpen: true}));

  // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
  map.addControl(new AMap.MapType());


}).catch(e => {
  console.log(e);
})
const  convertFrom = (LngLatArray, success) =>{
  var LngLatArray2 = [];
  var size = 40;
  var pageNum = parseInt((LngLatArray.length + size - 1) / size);
  var convertNum = 0;
  for (var i = 0; i < pageNum; i++) {
    var LngLatArraySlice = LngLatArray.slice(i * size, (i + 1) * size);
    convert(LngLatArraySlice, i);
  }
  function convert(LngLatArray, n) {
    AMap.convertFrom(LngLatArray, 'gps', function (status, result) {
      if (status == 'complete') {
        LngLatArray2[n] = (result.locations);
        convertNum++;
        if (convertNum >= pageNum) {
          typeof success == "function" ? success([].concat.apply([], LngLatArray2)) : null;
        }
      }
    });
  };
}

const handleQuery = () => {
  polyline ? map.remove([polyline]) : ''
  getTrack(proxy.addDateRange(queryParams.value, dateRange.value)).then(e => {
    text&&text.remove()
    let pathRow = e.data.map(val => [val.longitude, val.latitude])
    convertFrom(pathRow,(result)=>{
      let lnglats = result.map(e => [e.lng, e.lat]);
      console.log(lnglats)
      polyline = new AMap.Polyline({
        strokeColor: '#00BBFF', // 线颜色-深蓝色
        path: lnglats,
        strokeWeight: 6 // 线宽
      })
      map.add(polyline);
      distance = Math.round(AMap.GeometryUtil.distanceOfLine(lnglats));
      text = new AMap.Text({
        position: lnglats.at(-1),
        text: '行驶路径' + distance + '米',
        offset: new AMap.Pixel(-20, -20)
      })
      map.add(text);
      map.setFitView()
    })
    let grasp = new AMap.GraspRoad();
    // AMap.convertFrom(pathRow, 'gps', function (status, result) {
    //   if (result.info === 'ok') {
    //     let lnglats = result.locations.map(e => [e.lng, e.lat]);
    //     polyline = new AMap.Polyline({
    //       strokeColor: '#00BBFF', // 线颜色-深蓝色
    //       path: lnglats,
    //       strokeWeight: 6 // 线宽
    //     })
    //     map.add(polyline);
    //     let distance = Math.round(AMap.GeometryUtil.distanceOfLine(lnglats));
    //     let text = new AMap.Text({
    //       position: lnglats.at(-1),
    //       text: '行驶路径' + distance + '米',
    //       offset: new AMap.Pixel(-20, -20)
    //     })
    //     map.add(text);
    //     map.setFitView()
    //   }
    // })
    // }
    // });
    polylinePath.value = pathRow
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = []
  proxy.resetForm("queryRef");
  handleQuery();
}
</script>
<style>
#container3 {
  padding: 0px;
  margin: 20px 0 0 0;
  width: 100%;
  height: calc(100vh - 190px);
}
</style>
