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

<script lang="ts" setup>
import { CircleData, getMouseStyle, defaultStyle } from "./index.ts";
import { PropertyUpdate, Operate } from "../../propertys";
import TempCircle from "./temp-circle.vue";
import { useComponentStatus } from "@/core/hook/use-component.ts";
import { cloneRepShape, useCustomTransformer } from "@/core/hook/use-transformer.ts";
import { Transform } from "konva/lib/Util";
import { Circle } from "konva/lib/shapes/Circle";

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

const { shape, tData, data, operateMenus, describes } = useComponentStatus<
  Circle,
  CircleData
>({
  emit,
  props,
  getMouseStyle,
  defaultStyle,
  transformType: "custom",
  customTransform(callback, shape, data) {
    const update = (mat: Transform, data: CircleData) => {
      const { x, y, scaleX } = mat.decompose();
      if (scaleX !== 1) {
        return { radius: data.radius * scaleX, x, y };
      } else {
        return { x, y };
      }
    };

    useCustomTransformer(shape, data, {
      openSnap: true,
      getRepShape($shape) {
        const repShape = cloneRepShape($shape).shape;
        return {
          shape: repShape,
          update(data) {
            repShape.x(data.x).y(data.y).radius(data.radius);
          },
        };
      },
      transformerConfig: {
        rotateEnabled: false,
        keepRatio: true,
        enabledAnchors: ["top-left", "top-right", "bottom-left", "bottom-right"],
      },
      beforeHandler(data, mat) {
        return { ...data, ...update(mat, data) };
      },
      handler(data, mat) {
        const setAttrib = update(mat, data);
        Object.assign(data, setAttrib);
        if (setAttrib.radius) {
          return true;
        }
      },
      callback,
    });
  },
  copyHandler(tf, data) {
    const decTf = tf.decompose();
    console.log(data, decTf);
    return {
      ...data,
      x: data.x + decTf.x,
      y: data.y + decTf.y,
    };
  },
  propertys: ["fill", "stroke", "strokeWidth", "dash", "ref", "opacity", "zIndex"],
});
</script>
