<template>
  <MapMap ref="mapMap" @ready="handleMapReady" />
</template>
    
<script setup>
import MapMap from "@/components/Map/map";
import Fill from "ol/style/Fill";
import Text from "ol/style/Text";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Feature } from "ol";
import { Point, LineString } from "ol/geom";
import { Style, Icon, Stroke } from "ol/style";
import markerIcon from "@/assets/images/ship3.png";
import { duToGpsDM } from "@/utils/gpsToDu";
import { getCurrencyConfigByMid } from "@/utils/index";

const { proxy } = getCurrentInstance();

const props = defineProps({
  coordinates: {
    type: Array,
    default: () => [
      {
        lat: null,
        lng: null,
        time: null,
        x0a9: null,
        x0aA: null,
      },
    ],
  },
  routeIndex: {
    //跳跃位置，默认从头开始
    type: Number,
    default: 0,
  },
  timerDuration: {
    // 位置更新间隔
    type: Number,
    default: 500,
  },
});

const { coordinates, routeIndex, timerDuration } = toRefs(props);

const map = ref(null);
const zoom = 12;
let timer;
let carPoints = [];
let routeLayer = new VectorLayer({
  source: new VectorSource({
    features: [],
  }),
});
let featureMove;

const curAnalog = computed(
  () =>
    proxy.$store.state.data.analogList.find(
      (item) => item.sn == proxy.$store.state.data.curAnalogSn
    ) || {}
);

watch(
  () => routeIndex.value,
  (newValue) => {
    //// console.log(newValue);
    //// console.log(carPoints);
    // let rotation = Math.tan(this.carPoints[newValue].x0aA);
    let rotation = Number(carPoints[newValue].x0aA) * (Math.PI / 180);
    //// //// console.log(carPoints[routeIndex]);
    //// console.log(rotation);
    rotation = isNaN(rotation) ? 0 : rotation;
    //// //// console.log(rotation);
    featureMove
      .getGeometry()
      .setCoordinates([carPoints[newValue].lat, carPoints[newValue].lng]);
    featureMove.getStyle()[0].getImage().setRotation(rotation);
    featureMove
      .getStyle()[0]
      .getText()
      // .setText(getFeatureMoveText(carPoints[newValue]));
  }
);

watch(
  () => coordinates.value,
  (newValue) => {
    //// console.log(newValue);
    nextTick(() => {
      if (map != null) {
        let lat = (newValue[0].lat + newValue[newValue.length - 1].lat) / 2;
        let lng = (newValue[0].lng + newValue[newValue.length - 1].lng) / 2;
        proxy.$refs["mapMap"].moveTo([lat, lng], zoom, 0);
        // map.value.getView().setCenter([lat, lng]);
        // map.value.getView().setZoom(zoom);
        // map.value.getView().adjustZoom();

        deleteFeatures();
        // 画轨迹线
        iniDrawLine();
        drawLine();
        // 开始动
        moveStart();
      }
    });
  }
);

watch(
  () => timerDuration.value,
  () => {
    // console.log(`timerDuration`);
    timePause();
    timeStart();
  }
);

const handleMapReady = () => {
  map.value = proxy.$refs["mapMap"].map;
  map.value.addLayer(routeLayer);
};

const iniDrawLine = () => {
  // routeLayer = new VectorLayer({
  //   source: new VectorSource({
  //     features: [],
  //   }),
  // });
  // map.value.addLayer(routeLayer);
};

//轨迹线  把每个点连起来
const drawLine = () => {
  let comDots = [];
  let wireFeature = {};
  coordinates.value.map((item) => {
    comDots.push([item.lat, item.lng]);
    wireFeature = new Feature({
      geometry: new LineString(comDots),
    });
    wireFeature.setStyle(
      new Style({
        stroke: new Stroke({
          // 设置边的样式
          color: "#5470c6",
          width: 4,
        }),
      })
    );

    let iconFeature = new Feature({
      geometry: new Point([item.lat, item.lng]), //绘制图形（点）
    });
    let rotation = (Number(item.x0aA) - 90) * (Math.PI / 180);
    rotation = isNaN(rotation) ? 0 : rotation;
    // //// console.log(rotation);

    iconFeature.setStyle(
      new Style({
        image: new Icon({
          scale: 0.5,
          rotation: rotation,
          snapToPixel: true,
          src: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAnElEQVQ4T63TsQ0CMQyF4f/NgMQQ0CBR0FIx190cFIiWhhFoKdgEiRUeSoF0gO8cjkub+Evs2OLPpc9422dgBRwlNZn/BtjeApdOUJsh0QuuwKYWiYAFcAKWHaSR1EbpfAHlkO0ICdMJgV+QXmAAmUu6v9IZA8wkPVKgtg7TF7H25t4UbN+A9ahGmqqVD8AO2GdzUF45+I3ZJJb9JxbwRhEhB66xAAAAAElFTkSuQmCC",
        }),
        text: new Text({
          // 字体与大小
          font: "10px",
          // 文字填充色
          fill: new Fill({
            color: "#000",
          }),
          textAlign: "center",
          // 显示文本，数字需要转换为文本string类型！
          //   {m}-{d}
          text: `${proxy.parseTime(item.time, "{y}/{m}/{d} {h}:{i}:{s}")} `,
          offsetX: 0,
          offsetY: 15,
          // rotation: 30 * (Math.PI / 180),
        }),
      })
    );
    routeLayer.getSource().addFeatures([iconFeature]);
  });
  routeLayer.getSource().addFeatures([wireFeature]);
};

//创建小车这个要素
const moveStart = () => {
  //坐标转换
  let dotsData = JSON.parse(JSON.stringify(coordinates.value));
  //深复制车的位置，不在原数组改变，方便重新播放
  carPoints = JSON.parse(JSON.stringify(dotsData));
  //// console.log(carPoints);

  //小车最初位置在第一个坐标点
  featureMove = new Feature({
    geometry: new Point([carPoints[0].lat, carPoints[0].lng]),
  });
  let rotation = Number(carPoints[0].x0aA) * (Math.PI / 180);
  rotation = isNaN(rotation) ? 0 : rotation;
  //// //// console.log(rotation)
  featureMove.setStyle([
    new Style({
      image: new Icon({
        src: markerIcon,
        scale: 0.85,
        anchor: [0.5, 0.5],
        rotation: rotation,
      }),
      // text: new Text({
      //   // 字体与大小
      //   font: "13px Microsoft YaHei",
      //   // 文字填充色
      //   fill: new Fill({
      //     color: "#666",
      //   }),
      //   backgroundFill: new Fill({
      //     color: "#fff",
      //   }),
      //   //文字边界宽度与颜色
      //   stroke: new Stroke({
      //     color: "#fff",
      //     width: 3,
      //   }),
      //   textAlign: "left",
      //   // 显示文本，数字需要转换为文本string类型！
      //   text: getFeatureMoveText(carPoints[0]),
      //   offsetX: 35,
      //   offsetY: 15,
      // }),
    }),
  ]);
  //添加车辆元素到图层
  routeLayer.getSource().addFeature(featureMove);
  timeStart();
};

// 计时器开始
const timeStart = () => {
  timePause();
  timer = setInterval(() => {
    //// console.log(routeIndex.value);
    if (routeIndex.value + 1 >= carPoints.length) {
      //重头开始
      proxy.$emit("update:routeIndex", 0);
      //   routeIndex.value = 0;
      return;
    }
    proxy.$emit("update:routeIndex", routeIndex.value + 1);
    // routeIndex.value++;
  }, 1100 - timerDuration.value);
};

// 计时器暂停
const timePause = () => {
  clearInterval(timer);
  timer = null;
};

// 删除轨迹
const deleteFeatures = () => {
  if (routeLayer) {
    routeLayer.getSource().clear();
  }
};

const getFeatureMoveText = (coordinate) =>
  `  经度：${duToGpsDM(coordinate.lat, "E")}  \n  纬度：${duToGpsDM(
    coordinate.lng,
    "N"
  )} \n  航向：${coordinate.x0aA}°  \n  航速：${coordinate.x0a9}kn \n  时间：${
    coordinate.time
  } `;

defineExpose({
  timeStart,
  timePause,
});
</script>
    