<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 { Transform } from "konva/lib/Util";
import { MathUtils } from "three";
import { cloneRepShape, useCustomTransformer } from "@/core/hook/use-transformer.ts";
import { setShapeTransform } from "@/utils/shape.ts";
import { Ellipse } from "konva/lib/shapes/Ellipse";
import { Pos } from "@/utils/math.ts";

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

const matToData = (data: CircleData, mat: Transform, initRadius?: Pos) => {
  // data.mat = mat.m;
  // return data;
  if (!initRadius) {
    initRadius = {
      x: data.radiusX,
      y: data.radiusY,
    };
  }
  const dec = mat.decompose();
  data.radiusY = dec.scaleY * initRadius.y;
  data.radiusX = dec.scaleX * initRadius.x;
  data.mat = new Transform()
    .translate(dec.x, dec.y)
    .rotate(MathUtils.degToRad(dec.rotation)).m;
  return data;
};

const { shape, tData, data, operateMenus, describes } = useComponentStatus<
  Ellipse,
  CircleData
>({
  emit,
  props,
  getMouseStyle,
  defaultStyle,
  alignment: (data, mat) => {
    const tf = shape.value!.getNode().getTransform();
    mat.multiply(tf);
    return matToData(data, mat);
  },
  // transformType: "mat",
  transformType: "custom",
  customTransform(callback, shape, data) {
    let initRadius: Pos;
    useCustomTransformer(shape, data, {
      openSnap: true,
      getRepShape($shape) {
        const repShape = cloneRepShape($shape).shape;
        initRadius = { x: repShape.radiusX(), y: repShape.radiusY() };
        return {
          shape: repShape,
        };
      },
      handler(data, mat) {
        matToData(data, mat, initRadius);
        return true;
      },
      callback,
    });
  },
  copyHandler(mat, data) {
    const tf = shape.value!.getNode().getTransform();
    mat.multiply(tf);
    return matToData({ ...data }, mat);
  },
  propertys: [
    "fill",
    "stroke",
    "strokeWidth",
    "dash",
    // "ref",
    "opacity",
    //  "zIndex"
  ],
});
</script>
