<template>
  <div class="koi-flex" v-if="bmInfo">
    <KoiCard>
      <el-row :gutter="20">
        <el-col :span="8">
          <div style="padding: 0px 20px 20px 0px;font-weight: 600">请在图片边框内选定区域</div>
          <el-card :body-style="{ padding: '0' }" style="padding: 0;position:relative;">
            <div @mousedown="startDrag" @mousemove="onDrag" @mouseup="endDrag" @mouseleave="endDrag"
              style="width: 100%">
              <!-- 图片 -->
              <img draggable="false" id="image-selector" :src="bmInfoData.bm_img" ref="image" alt="image"
                @click="handleClick"
                style="cursor: crosshair; position: relative; user-select: none; width: 100%; height: auto;"
                @load="onImageLoad" />
              <!-- 画布用于绘制矩形路径 -->
              <canvas id="myCanvas" ref="canvas" :width="imageWidth" :height="imageHeight"
                style="position: absolute; top: 0; left: 0; pointer-events: none;">
              </canvas>
            </div>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-form :model="form" label-width="auto">
            <el-form-item label="新闻标题" required>
              <el-input v-model="form.new_name" placeholder="请输入新闻标题" size="large" />
            </el-form-item>
            <el-form-item label="新闻副标题">
              <el-input v-model="form.subtitle" placeholder="请输入新闻副标题" size="large" />
            </el-form-item>
            <el-form-item label="新闻记者" required>
              <el-input v-model="form.reporter" placeholder="请输入新闻记者" size="large" />
            </el-form-item>
            <el-form-item label="新闻坐标" required>
              <el-input disabled v-model="coordinate" placeholder="请选择新闻坐标" size="large" />
              <el-button type="danger" class="mt-2" @click="allowClickTrue()">重新选择</el-button>
            </el-form-item>
            <el-form-item label="媒体链接">
              <el-input v-model="form.video" placeholder="请输入媒体链接" size="large"/>
            </el-form-item>
            <el-form-item label="跳转链接">
              <el-input v-model="form.jump_link" placeholder="请输入跳转链接" size="large"/>
            </el-form-item>
            <el-form-item label="新闻详情" required>
              <el-card shadow="hover">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
                <Editor style="height: 300px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
                  @onCreated="handleCreated" />
              </el-card>
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="onSubmit" size="large">保存新闻</el-button>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>
    </KoiCard>
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { getAssets } from "@/utils/index.ts";
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive, nextTick } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { bmInfo, newsAdd } from "@/api/system/post";
import { koiNoticeError, koiNoticeSuccess } from "@/utils/koi.ts";
import { useRoute, useRouter } from 'vue-router';
import useTabsStore from "@/stores/modules/tabs.ts"; // 导入 useRoute
const router = useRouter();
const tabsStore = useTabsStore();
const form = reactive({
  new_name: '',
  coordinate: '',
  subtitle: '',
  reporter: '',
  content: '',
  coordinate_show: '',
  video: '',
  jump_link:'',
});
/*新闻坐标*/
const coordinate = ref();
/*版面详情*/
const bmInfoData = ref({});
const route = useRoute(); // 创建 route 对象
const id = ref();
onMounted(() => {
  id.value = route.params.id;
  getBmInfo();
})
const getBmInfo = async () => {
  try {
    const res: any = await bmInfo({ id: id.value });
    console.log("菜单数据表格数据->", res.data);
    bmInfoData.value = res.data;
    // koiNoticeSuccess("修改成功!");
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
}
/*文章保存*/
const onSubmit = async () => {
  form.coordinate = coordinate.value;

  form.bm_id = id.value;
  console.log(form);

  if (form.new_name == '') {
    koiNoticeError("新闻标题不能为空！");
    return;
  }
  if (form.reporter == '') {
    koiNoticeError("新闻记者不能为空！");
    return;
  }
  if (form.coordinate == '' || typeof (form.coordinate) == 'undefined') {
    koiNoticeError("新闻坐标不能为空！");
    return;
  }
  if (form.content == '') {
    koiNoticeError("新闻内容不能为空！");
    return;
  }
  form.coordinate_show = `${rectCoordinates.value.x1},${rectCoordinates.value.y1},${rectCoordinates.value.x2},${rectCoordinates.value.y2}`;
  try {
    const res: any = await newsAdd(form);
    console.log("菜单数据表格数据->", res.data);
    bmInfoData.value = res.data;
    koiNoticeSuccess("添加成功!");
    tabsStore.removeTab(route.fullPath);
    router.push('/paper/list');
  } catch (error) {
    console.log(error);
    koiNoticeError("数据添加失败，请刷新重试🌻");
  }
}
const toolbarConfig = {
  showLinkImg: false,
  uploadImgShowBase64: true,
  excludeKeys: [
    'insertImage',// 删除网络图片上传
    'insertLink',// 删除链接
    'insertTable',// 删除表格
    'codeBlock',// 删除代码块
  ]
}
const editorConfig = {
  placeholder: '',
  readOnly: false, // 是否只允许阅读，不可编辑
  autoFocus: true,
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 1 * 1024 * 1024,
      server: import.meta.env.VITE_WEB_BASE_API + '/api/common/upload',
      fieldName: 'file',
      meta: {
        association_id: 0,
      },
      customInsert(res, insertFn) {  // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果
        console.log(res);
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.data.fullurl, '', '')
      }, onError: (file, err, res) => {
        if (err.message.indexOf('exceeds maximum allowed size') !== -1) {
          koiNoticeError('图片限制为1M，请调整好再上传！');
        }
      },
    },
    uploadVideo: {
      maxFileSize: 50 * 1024 * 1024,
      server: import.meta.env.VITE_WEB_BASE_API + '/api/common/upload',
      fieldName: 'file',
      meta: {
        association_id: 0,
      },
      customInsert(res, insertFn) {  // TS 语法
        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果
        console.log(res);
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.data.fullurl, '', '')
      }, onError: (file, err, res) => {
        if (err.message.indexOf('exceeds maximum allowed size') !== -1) {
          koiNoticeError('视频限制为50M，请调整好再上传！');
        }
      },
    }
  }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
// 定义响应式变量
const points = ref([]); // 存储点击的点
/*新闻坐标*/
const s = ref();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const showPoints = ref([]); // 展示的点

const rectCoordinates = ref(null); // 矩形坐标
const rect = ref(null); // 用来显示矩形的overlay
const imageWidth = ref(0); // 图片宽度
const imageHeight = ref(0); // 图片高度
const imageLoaded = ref(false); // 确保图片加载完成
const isDragging = ref(false); // 是否正在拖动
const dragStart = ref({ x: 0, y: 0 }); // 拖动开始的坐标
const allowClick = ref(true); // 是否允许点击

const allowClickTrue = () => {
  console.log("allowClickTrue");
  // 清空点，准备下一次点击
  points.value = [];
  allowClick.value = true;
  isDragging.value = false;
  rectCoordinates.value = null;
  const canvas = document.getElementById('myCanvas');
  const context = canvas.getContext("2d");
  // 清空之前的画布
  context.clearRect(0, 0, canvas.width, canvas.height);
}
// 确保图片加载完成后执行操作
const onImageLoad = () => {
  const img = document.getElementById('image-selector');
  imageWidth.value = img.offsetWidth; // 使用自然宽度
  imageHeight.value = img.offsetHeight; // 使用自然高度
  imageLoaded.value = true;
  console.log('Image loaded:', imageWidth.value, imageHeight.value);
};

// 处理用户点击事件
const handleClick = (event) => {
  if (!imageLoaded.value || !allowClick.value) return;
  const img = document.getElementById('image-selector');
  const rect = img.getBoundingClientRect(); // 使用 img 的边界矩形
  const scaleX = img.naturalWidth / img.offsetWidth; // 计算缩放比例
  const scaleY = img.naturalHeight / img.offsetHeight; // 计算缩放比例
  const xx = parseInt((event.clientX - rect.left) * scaleX); // 使用缩放比例计算坐标
  const yy = parseInt((event.clientY - rect.top) * scaleY); // 使用缩放比例计算坐标
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  // 保存点击的坐标
  points.value.push({ x, y });
  showPoints.value.push({ xx, yy });
  console.log(`Clicked at: (${x}, ${y})`); // 调试信息
  console.log(`Clicked at: (${xx}, ${yy})`); // 调试信息
  // 确保 canvas 元素存在后再绘制
  const canvas = document.getElementById('myCanvas');
  console.log('Canvas:', canvas);
  if (canvas) {
    drawCurrentPath(); // 确保调用绘制函数
  } else {
    console.error("Canvas element not found!");
  }

  // 如果点击了四次，计算矩形并显示
  if (points.value.length === 4) {
    calculateRectangle();
    showCalculateRectangle();
  }
};

// 新增函数：绘制当前点击的点和线
const drawCurrentPath = () => {
  const canvas = document.getElementById('myCanvas');
  if (!canvas) {
    console.error("Canvas element not found!");
    return;
  }

  const context = canvas.getContext("2d");
  context.clearRect(0, 0, canvas.width, canvas.height); // 清空画布

  // 绘制已点击的点
  points.value.forEach(point => {
    context.beginPath();
    context.arc(point.x, point.y, 5, 0, Math.PI * 2); // 绘制圆点
    context.fillStyle = "red"; // 红色点
    context.fill();
  });

  // 绘制线条连接已点击的点
  if (points.value.length > 1) {
    context.beginPath();
    context.moveTo(points.value[0].x, points.value[0].y);
    for (let i = 1; i < points.value.length; i++) {
      context.lineTo(points.value[i].x, points.value[i].y);
    }
    context.strokeStyle = "blue"; // 蓝色线条
    context.lineWidth = 2;
    context.stroke();
  }
};
// 计算矩形坐标
const showCalculateRectangle = () => {
  const [p1, p2, p3, p4] = showPoints.value;
  console.log(showPoints.value);
  const x1 = Math.min(p1.xx, p2.xx, p3.xx, p4.xx);
  const y1 = Math.min(p1.yy, p2.yy, p3.yy, p4.yy);
  const x2 = Math.max(p1.xx, p2.xx, p3.xx, p4.xx);
  const y2 = Math.max(p1.yy, p2.yy, p3.yy, p4.yy);
  s.value = { x1, y1, x2, y2 };
  coordinate.value = `${x1},${y1},${x2},${y2}`;
};
// 计算矩形坐标
const calculateRectangle = () => {
  const [p1, p2, p3, p4] = points.value;

  const x1 = Math.min(p1.x, p2.x, p3.x, p4.x);
  const y1 = Math.min(p1.y, p2.y, p3.y, p4.y);
  const x2 = Math.max(p1.x, p2.x, p3.x, p4.x);
  const y2 = Math.max(p1.y, p2.y, p3.y, p4.y);

  rectCoordinates.value = { x1, y1, x2, y2 };

  // 显示矩形（用于视觉反馈）
  rect.value = {
    left: `${x1}px`,
    top: `${y1}px`,
    width: `${x2 - x1}px`,
    height: `${y2 - y1}px`,
  };

  // 使用 nextTick 确保 DOM 更新完成后再访问 canvas
  nextTick(() => {
    drawRectanglePath(x1, y1, x2, y2);
  });

  // 清空点，准备下一次点击
  points.value = [];
};

// 使用 Canvas 绘制矩形路径
const drawRectanglePath = (x1, y1, x2, y2) => {
  const canvas = document.getElementById('myCanvas');
  if (!canvas) {
    console.error("Canvas element not found!");
    return;
  }
  const context = canvas.getContext("2d");
  // 清空之前的画布
  context.clearRect(0, 0, canvas.width, canvas.height);
  // 绘制矩形路径
  context.beginPath();
  context.moveTo(x1, y1);
  context.lineTo(x2, y1);
  context.lineTo(x2, y2);
  context.lineTo(x1, y2);
  context.closePath();
  // 设置绘制样式
  context.lineWidth = 3;
  context.strokeStyle = "green"; // 绿色路径
  context.setLineDash([5, 3]); // 设置虚线样式
  context.stroke();
};

// 新增函数：开始拖动
const startDrag = (event: MouseEvent) => {
  console.log(rectCoordinates.value);
  //event.preventDefault(); // 阻止默认行为
  if (rectCoordinates.value) { // 确保矩形已绘制
    isDragging.value = true;
    allowClick.value = false; // 禁止点击
    dragStart.value = { x: event.clientX, y: event.clientY };
  }
};

// 新增函数：处理拖动
const onDrag = (event) => {
  if (isDragging.value) {
    const dx = event.clientX - dragStart.value.x;
    const dy = event.clientY - dragStart.value.y;
    // 更新矩形坐标
    rectCoordinates.value.x1 += dx;
    rectCoordinates.value.y1 += dy;
    rectCoordinates.value.x2 += dx;
    rectCoordinates.value.y2 += dy;

    // 更新矩形坐标
    s.value.x1 += dx;
    s.value.y1 += dy;
    s.value.x2 += dx;
    s.value.y2 += dy;
    coordinate.value = `${s.value.x1},${s.value.x2},${s.value.y1},${s.value.y2}`;
    // 更新拖动起始点
    dragStart.value = { x: event.clientX, y: event.clientY };
    // 重新绘制矩形
    drawRectanglePath(rectCoordinates.value.x1, rectCoordinates.value.y1, rectCoordinates.value.x2, rectCoordinates.value.y2);
  }
};

// 新增函数：结束拖动
const endDrag = () => {
  isDragging.value = false;
};
</script>

<style scoped lang="scss">
/* 你的样式 */
</style>
