import { ImageFillType, LineType } from "../enum";
import { uniqueId } from "lodash-es";

type PropType = {
  fill: {
    fillType: "color" | "gradient" | "image";
    color1: string;
    color2: string;
    gradientType: "linear" | "radial";
    gradientValue: number;
    imageUrl: string;
    objectFit: ImageFillType.Fill;
  };
  size: {
    width: number;
    height: number;
  };
  stroke: {
    type: "solid" | "dashed" | "dotted" | "dashdot";
    color: string;
    width: number;
  };
};
export function useShapeProps(
  fill: PropType["fill"],
  size: PropType["size"],
  stroke: PropType["stroke"]
) {
  const {
    fillType,
    color1,
    color2,
    gradientType,
    gradientValue,
    objectFit,
    imageUrl,
  } = fill || {};
  const { width, height } = size;
  const id = uniqueId("fill_");
  const fillContent = fillType === "color" ? color1 : `url(#${id})`;
  const objectFitMap = {
    [ImageFillType.Fill]: "xMidYMid slice", // 填充
    [ImageFillType.Auto]: "", // 自动
    [ImageFillType.Stretch]: "", // 拉伸
    [ImageFillType.Original]: "xMidYMid meet", // 原始
    [ImageFillType.Tiled]: "", // 平铺
  };

  const defsContent = (
    <>
      {fillType === "color" && gradientType === "linear" && (
        <linearGradient id={id} gradientTransform={`rotate(${gradientValue})`}>
          <stop offset="0%" stopColor={color1} />
          <stop offset="100%" stopColor={color2} />
        </linearGradient>
      )}
      {fillType === "color" && gradientType === "radial" && (
        <radialGradient
          id={id}
          cx="50%"
          cy="50%"
          r={gradientValue + "%"}
          fx="50%"
          fy="50%"
        >
          <stop offset="0%" stopColor={color1} />
          <stop offset="100%" stopColor={color2} />
        </radialGradient>
      )}
      {fillType === "image" && (
        <pattern
          id={id}
          patternUnits="userSpaceOnUse"
          width={width}
          height={height}
        >
          <image
            xlinkHref={imageUrl}
            x="0"
            y="0"
            width="100%"
            height="100%"
            preserveAspectRatio={objectFitMap[objectFit]}
          ></image>
        </pattern>
      )}
    </>
  );

  const strokeDasharray = LineType[stroke.type];

  return {
    strokeColor: stroke.color,
    strokeWidth: stroke.width,
    fillContent,
    defsContent,
    strokeDasharray,
  };
}
