<template>
  <div :style="{ ...layout, backgroundImage: `url(jsvtexturestore://${sourceId})` }" />
</template>

<script setup>
import { JsvTextureStoreApi } from "jsview";
import { onBeforeUnmount, computed } from "vue";

const props = defineProps({
  // 点数组，每个点包含 x 和 y 坐标
  points: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every(point => 'x' in point && 'y' in point);
    }
  },
  // 虚线配置，例如 [10, 5] 表示10px实线，5px空白
  dash: {
    type: Array,
    default: () => [10, 10]
  },
  // 虚线起始位置偏移
  phase: {
    type: Number,
    default: 0
  },
  // 线条颜色
  color: {
    type: String,
    default: "#FFFFFF"
  },
  // 线条宽度
  lineWidth: {
    type: Number,
    default: 2
  },
  // 布局样式
  layout: {
    type: Object,
    required: true
  }
});

// 计算坐标系调整值和画布尺寸
const canvasInfo = computed(() => {
  const xValues = props.points.map(p => p.x);
  const yValues = props.points.map(p => p.y);
  
  // 找出最小坐标值
  const minX = Math.min(...xValues);
  const minY = Math.min(...yValues);
  
  // 计算偏移量（考虑线宽）
  const offsetX = minX < 0 ? Math.abs(minX) : 0;
  const offsetY = minY < 0 ? Math.abs(minY) : 0;
  const lineOffset = Math.ceil(props.lineWidth / 2);
  
  // 计算画布尺寸（考虑线宽）
  const width = Math.max(...xValues) - minX + props.lineWidth * 2;
  const height = Math.max(...yValues) - minY + props.lineWidth * 2;
  
  return {
    offsetX: offsetX + lineOffset,
    offsetY: offsetY + lineOffset,
    width,
    height
  };
});

// 创建画布纹理
let sourceId = '';
const canvasRef = JsvTextureStoreApi.canvasTexture(
  canvasInfo.value.width,
  canvasInfo.value.height
);

// 绘制透明背景
canvasRef.drawColor("rgba(0,0,0,0)");

// 创建自定义路径
const path = canvasRef.customPath();

// 移动到第一个调整后的点
if (props.points.length > 0) {
  const firstPoint = props.points[0];
  path.moveTo(
    firstPoint.x + canvasInfo.value.offsetX,
    firstPoint.y + canvasInfo.value.offsetY
  );
  
  // 连接后续的调整后的点
  for (let i = 1; i < props.points.length; i++) {
    const point = props.points[i];
    path.lineTo(
      point.x + canvasInfo.value.offsetX,
      point.y + canvasInfo.value.offsetY
    );
  }
  path.close();
}

// 使用虚线样式绘制路径
path.strokeWithSetting({
  lineWidth: props.lineWidth,
  color: props.color,
  dash: props.dash,
  phase: props.phase
});

// 提交纹理并获取sourceId
sourceId = canvasRef.commit();

// 组件卸载时清理纹理
onBeforeUnmount(() => {
  JsvTextureStoreApi.deleteTexture(sourceId);
});
</script> 