<template>
  <TempLine
    :data="tData"
    :ref="(v: any) => shape = v?.shape"
    :id="data.id"
    @update:position="updatePosition"
    @update="emit('updateShape', { ...data })"
  />
  <PropertyUpdate
    :describes="describes"
    :data="data"
    :target="shape"
    @change="emit('updateShape', { ...data })"
  />
  <Operate :target="shape" :menus="operateMenus" />
</template>

<script lang="ts" setup>
import { PolygonData, getMouseStyle, defaultStyle } from "./index.ts";
import { useComponentStatus } from "@/core/hook/use-component.ts";
import { PropertyUpdate, Operate } from "../../propertys/index.ts";
import TempLine from "./temp-polygon.vue";
import { useInteractiveDrawShapeAPI } from "@/core/hook/use-draw.ts";
import { useStore } from "@/core/store/index.ts";
import { EditPen } from "@element-plus/icons-vue";
import { Pos } from "@/utils/math.ts";
import { Transform } from "konva/lib/Util";

const props = defineProps<{ data: PolygonData }>();
const emit = defineEmits<{
  (e: "updateShape", value: PolygonData): void;
  (e: "addShape", value: PolygonData): void;
  (e: "delShape"): void;
}>();

const { shape, tData, data, operateMenus, describes } = useComponentStatus({
  emit,
  props,
  getMouseStyle,
  transformType: "line",
  defaultStyle,
  alignment(data, mat) {
    data.points = data.points.map((p) => mat.point(p));
    data.attitude = mat.multiply(new Transform(data.attitude)).m;
  },
  copyHandler(tf, data) {
    data.points = data.points.map((v) => tf.point(v));
    return data;
  },
  propertys: [
    "fill",
    "stroke",
    "strokeWidth",
    "dash",
    "opacity",
    //  "ref", "zIndex"
  ],
});

const updatePosition = ({ ndx, val }: { ndx: number; val: Pos }) => {
  Object.assign(data.value.points[ndx], val);
  shape.value?.getNode().fire("bound-change");
};

const draw = useInteractiveDrawShapeAPI();
const store = useStore();
operateMenus.push({
  label: "钢笔编辑",
  icon: EditPen,
  handler() {
    draw.enterDrawShape("polygon", {
      ...props.data,
      getMessages: () => {
        const line = store.getItemById(props.data.id) as PolygonData;
        return line ? line.points : [];
      },
    });
  },
});
</script>
