<template>
  <TextDom v-if="editText && $shape" :shape="$shape" @submit="quitHandler" />
  <TempText
    :data="tData"
    :ref="(v: any) => shape = v?.shape"
    :id="data.id"
    @dblclick="dbclickHandler"
  />
  <PropertyUpdate
    v-if="!editText"
    :describes="describes"
    :data="data"
    :target="shape"
    @change="emit('updateShape', { ...data })"
  />
  <Operate :target="shape" :menus="operateMenus" v-if="!editText" />
</template>

<script lang="ts" setup>
import { TextData, getMouseStyle, defaultStyle, textNodeMap } from "./index.ts";
import { PropertyUpdate, Operate } from "../../propertys";
import TempText from "./temp-text.vue";
import TextDom from "./text-dom.vue";
import { useComponentStatus } from "@/core/hook/use-component.ts";
import {
  cloneRepShape,
  useCustomTransformer,
  useTransformer,
} from "@/core/hook/use-transformer.ts";
import { Transform } from "konva/lib/Util";
import { Text } from "konva/lib/shapes/Text";
import { computed, ref, watch } from "vue";
import { setShapeTransform } from "@/utils/shape.ts";
import { zeroEq } from "@/utils/math.ts";
import { MathUtils } from "three";
import { KonvaEventObject } from "konva/lib/Node";

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

const { shape, tData, data, operateMenus, describes } = useComponentStatus<
  Text,
  TextData
>({
  emit,
  props,
  getMouseStyle,
  defaultStyle,
  transformType: "custom",
  customTransform(callback, shape, data) {
    useCustomTransformer(shape, data, {
      openSnap: true,
      getRepShape($shape) {
        const repShape = cloneRepShape($shape).shape;
        return {
          shape: repShape,
          update(data) {
            data.width && repShape.width(data.width);
            data.fontSize && repShape.fontSize(data.fontSize);
            setShapeTransform(repShape, new Transform(data.mat));
          },
        };
      },
      transformerConfig: {
        rotateEnabled: true,
        enabledAnchors: ["middle-left", "middle-right"],
        boundBoxFunc: (oldBox, newBox) => {
          if (newBox.width - minWidth.value < -0.01) {
            return oldBox;
          }
          return newBox;
        },
      },
      beforeHandler(data, mat) {
        return { ...data, ...update(mat, data) };
      },
      handler(data, mat) {
        const setAttrib = update(mat, data);
        Object.assign(data, setAttrib);
        if (setAttrib.width) {
          return true;
        }
      },
      callback,
    });
  },
  copyHandler(tf, data) {
    return {
      ...data,
      mat: tf.multiply(new Transform(data.mat)).m,
    };
  },
  propertys: [
    "fill",
    "stroke",
    "strokeWidth",
    "dash",
    "opacity",
    "fontSize",
    "align",
    "fontStyle",
    // "ref",
    // "zIndex",
  ],
});

const minWidth = computed(() => (data.value.fontSize || 12) * 2);
const getWidth = (data: TextData, scaleX: number) => {
  let width: number;
  if ("width" in data) {
    width = Math.max(data.width! * scaleX, minWidth.value);
  } else {
    width = Math.max(shape.value!.getNode()!.width() * scaleX, minWidth.value);
  }
  return width;
};

const update = (mat: Transform, data: TextData) => {
  const { scaleX, x, y, rotation } = mat.decompose();
  if (!zeroEq(scaleX - 1)) {
    return {
      width: getWidth(data, scaleX),
      mat: new Transform()
        .translate(x, y)
        .rotate(MathUtils.degToRad(rotation))
        .scale(1, 1).m,
    };
  } else {
    return {
      mat: mat.m,
    };
  }
};

// 字体大小变化时，更新width
watch(
  () => data.value.fontSize,
  () => {
    data.value.width = getWidth(data.value, 1);
    const $shape = shape.value?.getNode();
    $shape && $shape.fire("bound-change");
  }
);

const transformer = useTransformer();
const $shape = computed(() => shape.value?.getNode());
const editText = ref(false);
const dbclickHandler = (ev: KonvaEventObject<MouseEvent>) => {
  editText.value = true;
  $shape.value && $shape.value.hide();
  transformer.hide();
};
const quitHandler = (val: string) => {
  console.log("quit");
  editText.value = false;
  transformer.show();
  $shape.value && $shape.value.show();
  if (val !== data.value.content) {
    data.value.content = val;
  }
};
</script>

<style scoped lang="scss"></style>
