<template>
  <v-arrow
    :ref="(r: any) => arrow[0] = r"
    :config="{
      fill: currentColor,
      stroke: currentColor,
      strokeWidth: 1,
      pointerLength: 10,
      hitStrokeWidth: 10,
      pointerWidth: 10,
      ...currentMat,
    }"
  />
  <v-line
    v-if="!hideLine"
    :ref="(r: any) => arrow[1] = r"
    :config="{
      stroke: currentColor,
      strokeWidth: 2,
      hitStrokeWidth: 4,
      ...currentMat,
    }"
  />
</template>

<script setup lang="ts">
import { computed, ref, watch, watchEffect } from "vue";
import {
  useDrag,
  useGlobalResize,
  useGlobalVar,
  useViewer,
  useViewerInvertTransformConfig,
  useViewerTransform,
} from "../drawing/hook";
import { Transform } from "konva/lib/Util";
import { Arrow } from "konva/lib/shapes/Arrow";
import { DC } from "../drawing/dec";
import { Line } from "konva/lib/shapes/Line";

const props = withDefaults(
  defineProps<{
    currentTime: number;
    follow?: boolean;
    hideLine?: boolean;
    currentColor?: string;
  }>(),
  {
    follow: false,
    currentColor: "#fff",
  }
);

const currentColor = props.currentColor;
const { misPixel } = useGlobalVar();
const emit = defineEmits<{ (e: "update:currentTime", num: number): void }>();

const arrow = ref<DC<Arrow>[]>([]);
const { drag } = useDrag(arrow);
watch(drag, (drag) => {
  if (!drag) return;
  const offsetX = drag.x;

  const currentX = props.currentTime * misPixel + offsetX;
  console.log(offsetX, currentX / misPixel);
  currentX >= 0 && emit("update:currentTime", currentX / misPixel);
});

const invConfig = useViewerInvertTransformConfig();
const currentX = computed(() => props.currentTime * misPixel);
const currentMat = computed(() => {
  return new Transform()
    .translate(currentX.value, 0)
    .scale(invConfig.value.scaleX, 1)
    .translate(-currentX.value, 0)
    .decompose();
});

const { viewer } = useViewer();
const { size } = useGlobalResize();
const viewerMat = useViewerTransform();
watch(
  () => {
    if (!props.follow || !size.value) return;
    return currentX.value;
  },
  (x) => {
    if (typeof x !== "number") return;
    const currentPixel = viewerMat.value.point({ x: currentX.value, y: 0 }).x;
    const offsetX = size.value!.width / 2 - currentPixel;
    viewer.movePixel({ x: offsetX, y: 0 });
  }
);

watch(
  () => ({
    x: currentX.value,
    h: size.value!.height,
    shapes: arrow.value.map((item) => item.getNode()),
  }),
  ({ x, shapes }) => {
    if (shapes[0] && shapes[1]) {
      shapes[0].points([x, 0, x, 10]);
      shapes[1].points([x, size.value!.height, x, 10]);
    }
  }
);
</script>
