<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    :width="800"
    :confirmLoading="confirmLoading"
  >
    <template #footer>
      <div>
        <a-button type="default" @click="handleCancle">取消</a-button>
        <a-button type="primary" @click="handleSubmit">{{ okText }}</a-button>
        <a-button :disabled="!imgUrl" type="primary" @click="handleCreateArea"
          >生成区域</a-button
        >
        <a-button type="primary" @click="reset">刪除标记</a-button>
        <a-button type="primary">保存区域</a-button>
      </div>
    </template>
    <canvas
      ref="canvas"
      width="770"
      height="600"
      @click="onCanvasClick"
      style="border: 1px solid #000"
    ></canvas>
    <p>点击顺时针或逆时针选择4到10个点。</p>
    <!-- <button @click="connectLines">连接线段</button> -->
    <!-- <button @click="startNewShape">开始新图形</button> -->
    <!-- <button @click="reset">重置</button> -->
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { computed, ref, unref, reactive, onMounted, nextTick } from "vue";
import url from "../../../assets/images/logo.png";
import { message, Alert } from "ant-design-vue";
const [messageApi, contextHolder] = message.useMessage();

const postList = ref<Post[]>([]);
defineOptions({ name: "VidiconInfoModal" });

const emit = defineEmits(["register", "reload"]);
const confirmLoading = ref<boolean>(false);
const imgUrl = ref("");
const okText = ref<string>("拍照");
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return "拍照";
});

// 定义点的类型
interface Point {
  x: number;
  y: number;
}

// 存储多个图形的点集合
const shapes = reactive<Point[][]>([]);
const currentPoints = ref<Point[]>([]); // 当前图形的点集合

const canvas = ref<HTMLCanvasElement | null>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);

// 初始化 Canvas 上下文
onMounted(() => {});

// 处理 Canvas 点击事件
const onCanvasClick = (event: MouseEvent) => {
  // 如果点数达到10个，禁止再添加新点
  if (currentPoints.value.length >= 10) {
    alert("已经达到最大点数，无法再添加新点。");
    return;
  }

  if (ctx.value) {
    const rect = canvas.value!.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    // 添加点到当前图形的数组
    currentPoints.value.push({ x, y });

    // 绘制当前点击的点
    drawPoint(x, y);
  }
};

// 绘制单个锚点
const drawPoint = (x: number, y: number) => {
  if (ctx.value) {
    ctx.value.beginPath();
    ctx.value.arc(x, y, 5, 0, Math.PI * 2);
    ctx.value.fillStyle = "red";
    ctx.value.fill();
  }
};

// 连接当前图形的线段
const connectLines = () => {
  if (ctx.value && currentPoints.value.length >= 4) {
    ctx.value.beginPath();
    ctx.value.strokeStyle = "blue";
    ctx.value.lineWidth = 2;

    // 连接所有点
    currentPoints.value.forEach((point, index) => {
      if (index === 0) {
        ctx.value.moveTo(point.x, point.y);
      } else {
        ctx.value.lineTo(point.x, point.y);
      }
    });

    // 闭合路径
    ctx.value.lineTo(currentPoints.value[0].x, currentPoints.value[0].y);

    ctx.value.stroke();

    // 保存当前图形
    shapes.push([...currentPoints.value]);
    currentPoints.value.length = 0; // 清空当前图形的点数据
  } else {
    alert("请点击4到10个点以连接线段。");
  }
};

// 开始绘制新图形
const startNewShape = () => {
  if (currentPoints.value.length > 0) {
    alert("请先完成当前图形或点击“连接线段”完成当前图形。");
    return;
  }
  // 可以选择清空画布或保留之前绘制的图形
};

// 重置画布和所有图形
const reset = () => {
  shapes.length = 0;
  if (ctx.value && canvas.value) {
    ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
  }
};
const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;

    modalLoading(false);
  }
);

async function handleSubmit() {
  confirmLoading.value = true;
  okText.value = "正在请求摄像头,进行照片拍摄";
  imgUrl.value = "";
  setTimeout(() => {
    confirmLoading.value = false;
    okText.value = "拍照";
    // imgUrl.value = url;
    setTimeout(async () => {
      await nextTick(); // 确保 DOM 完全更新后再获取 canvas 元素
      if (canvas.value) {
        const context = canvas.value.getContext("2d");
        if (context) {
          ctx.value = context;
          // 加载并绘制背景图像
          const backgroundImage = new Image();
          backgroundImage.src = url; // 修改为你的背景图像路径
          backgroundImage.onload = () => {
            if (ctx.value) {
              ctx.value.drawImage(
                backgroundImage,
                0,
                0,
                canvas.value.width,
                canvas.value.height
              );
            }
            imgUrl.value = url;
          };
        } else {
          console.error("无法获取2D上下文");
        }
      } else {
        console.error("Canvas元素未挂载");
      }
    }, 200);
  }, 500);
}
function handleCreateArea() {
  // alert("请按顺时针或逆时针选择4至10个锚点");
  connectLines();
}
function handleCancle() {
  closeModal();
  imgUrl.value = "";
}
</script>

<style scoped>
canvas {
  cursor: crosshair;
}
</style>
