<template>
  <!-- 生成参赛证对话框 -->
  <el-dialog v-model="bibDialog.visible" title="生成参赛证" width="1100px" append-to-body @close="handleCloseBibDialog">
    <div class="bib-generator">
      <!-- 预览面板 - 占满宽度 -->
      <div class="preview-container" ref="previewContainer">
        <div class="preview-canvas">
          <!-- 背景图片 -->
          <img v-if="bgImageUrl" :src="bgImageUrl" class="background-image" />
          <!-- Logo元素 -->
          <div
            v-if="logoImageUrl"
            class="draggable-element logo-element"
            :style="{
              left: bibForm.logoX + '%',
              top: bibForm.logoY + '%',
              transform: `translateX(-50%) scale(${bibForm.logoScale * canvasScale})`,
              transformOrigin: 'top left'
            }"
            @mousedown="startDrag($event, 'logo')"
            @click="selectedElement = 'logo'"
            :class="{ selected: selectedElement === 'logo' }"
          >
            <img :src="logoImageUrl" alt="Logo" style="max-width: 80px; max-height: 80px" />
          </div>
          <!-- 示例条形码 -->
          <div
            class="draggable-element barcode-element"
            :style="{
              left: (bibForm.qRCodeX || 11.67) + '%',
              top: (bibForm.qRCodeY || 32.5) + '%',
              transform: `translateX(-50%) translateY(-50%) scale(${bibForm.barcodeScale * canvasScale})`,
              transformOrigin: 'top left',
            }"
            @mousedown="startDrag($event, 'barcode')"
            @click="selectedElement = 'barcode'"
            :class="{ selected: selectedElement === 'barcode' }"
          >
            <svg
              t="1755833734016"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="2399"
              width="32"
              height="32"
            >
              <path
                d="M540.9 866h59v59h-59v-59zM422.8 423.1V98.4H98.1v324.8h59v59h59v-59h206.7z m-265.7-59V157.4h206.7v206.7H157.1z m0 0"
                p-id="2400"
              ></path>
              <path
                d="M216.2 216.4h88.6V305h-88.6v-88.6zM600 98.4v324.8h324.8V98.4H600z m265.7 265.7H659V157.4h206.7v206.7z m0 0"
                p-id="2401"
              ></path>
              <path
                d="M718.1 216.4h88.6V305h-88.6v-88.6zM216.2 718.3h88.6v88.6h-88.6v-88.6zM98.1 482.2h59v59h-59v-59z m118.1 0h59.1v59h-59.1v-59z m0 0"
                p-id="2402"
              ></path>
              <path
                d="M275.2 600.2H98.1V925h324.8V600.2h-88.6v-59h-59v59z m88.6 59.1V866H157.1V659.3h206.7z m118.1-531.4h59v88.6h-59v-88.6z m0 147.6h59v59h-59v-59zM659 482.2H540.9v-88.6h-59v88.6H334.3v59H600v59h59v-118z m0 118h59.1v59H659v-59z m-177.1 0h59v88.6h-59v-88.6z m0 147.7h59V866h-59V747.9zM600 688.8h59V866h-59V688.8z m177.1-88.6h147.6v59H777.1v-59z m88.6-118h59v59h-59v-59z m-147.6 0h118.1v59H718.1v-59z m0 206.6h59v59h-59v-59z m147.6 59.1h-29.5v59h59v-59h29.5v-59h-59v59z m-147.6 59h59V866h-59v-59.1z m59 59.1h147.6v59H777.1v-59z m0 0"
                p-id="2403"
              ></path>
            </svg>
          </div>

          <!-- 赛事名称预览 -->
          <div
            v-if="bibForm.eventName"
            class="event-name-preview draggable-element"
            v-loading="fontPreviewLoading"
            :style="{
              fontSize: Math.min(bibForm.fontSize, 56) + 'px',
              color: bibForm.fontColorHex,
              fontFamily: bibForm.fontName,
              left: (bibForm.eventX || 50) + '%',
              top: (bibForm.eventY || 5) + '%',
              transform: `translateX(-50%) scale(${bibForm.eventScale * canvasScale})`,
              transformOrigin: 'top center'
            }"
            @mousedown="startDrag($event, 'event')"
            @click="selectedElement = 'event'"
            :class="{ selected: selectedElement === 'event' }"
          >
            {{ bibForm.eventName }}
          </div>      

          <!-- 示例数字 12345 -->
          <div
            class="draggable-element number-element"
            v-loading="fontPreviewLoading"
            element-loading-text="加载字体..."
            element-loading-background="rgba(255, 255, 255, 0.7)"
            :style="{
              left: (bibForm.numberX || 50) + '%',
              top: (bibForm.numberY || 50) + '%',
              transform: `translate(-50%, -50%) scale(${bibForm.numberScale * canvasScale})`,
              fontSize: Math.min(bibForm.fontSize, 56) + 'px',
              color: bibForm.fontColorHex,
              fontFamily: bibForm.fontName,
              transformOrigin: 'center'
            }"
            @mousedown="startDrag($event, 'number')"
            @click="selectedElement = 'number'"
            :class="{ selected: selectedElement === 'number' }"
          >
            12345
          </div>
        </div>
      </div>

      <!-- 上传按钮区域 - 显示在预览面板下方 -->
      <div class="upload-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="upload-item">
              <div class="upload-row">
                <el-upload 
                  ref="bgUploadRef" 
                  :limit="1" 
                  :auto-upload="false" 
                  :on-change="handleBgImageChange" 
                  :show-file-list="false"
                  accept="image/*"
                >
                  <el-button type="primary" :icon="bgImageFile ? 'Select' : 'Upload'">
                    {{'上传背景图片' }}
                  </el-button>
                </el-upload>
                <span class="upload-tip">建议尺寸：2948×2079px</span>
              </div>
              <div v-if="bgImageFile" class="file-info">
                <span class="file-name">{{ bgImageFile.name }}</span>
                <el-button type="text" @click="removeBgImage" class="remove-btn">删除</el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="upload-item">
              <div class="upload-row">
                <el-upload 
                  ref="logoUploadRef" 
                  :limit="1" 
                  :auto-upload="false" 
                  :on-change="handleLogoImageChange" 
                  :show-file-list="false"
                  accept="image/*"
                >
                  <el-button type="primary" :icon="logoImageFile ? 'Select' : 'Upload'">
                    {{'上传Logo图片' }}
                  </el-button>
                </el-upload>
                <span class="upload-tip">建议尺寸：80×80px</span>
              </div>
              <div v-if="logoImageFile" class="file-info">
                <span class="file-name">{{ logoImageFile.name }}</span>
                <el-button type="text" @click="removeLogoImage" class="remove-btn">删除</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 配置面板 -->
      <el-form :model="bibForm" label-width="100px" class="config-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字体设置">
              <div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap">
                <el-select v-model="bibForm.fontName" filterable clearable placeholder="字体" style="width: 100px">
                  <el-option label="黑体" value="simhei"></el-option>
                  <el-option label="宋体" value="simsun"></el-option>
                  <el-option label="微软雅黑" value="yahei"></el-option>
                  <el-option v-if="bibForm.isCustomFont" :label="bibForm.customFontName" :value="bibForm.customFontNameValue"></el-option>
                </el-select>
                <el-input-number v-model="bibForm.fontSize" :min="8" :max="198" placeholder="字体大小" style="width: 140px"></el-input-number>
                <el-color-picker v-model="bibForm.fontColor" @change="handleFontColorChange"></el-color-picker>
                <el-upload
                  class="font-upload"
                  :auto-upload="true"
                  :show-file-list="false"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :on-success="handleFontUploadSuccess"
                  accept=".ttf,.otf"
                >
                  <el-button type="primary" link icon="Upload">上传字体</el-button>
                </el-upload>
                <el-button type="primary" link icon="FolderOpened" @click="openCloudFontDialog">云端字体库</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="赛事名称">
              <el-input v-model="bibForm.eventName" placeholder="请输入赛事名称" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="选中元素">
              <div style="display: flex; gap: 10px; align-items: center">
                <el-select v-model="selectedElement" placeholder="选择元素" style="width: 120px">
                  <el-option label="Logo" value="logo"></el-option>
                  <el-option label="二维码" value="barcode"></el-option>
                  <el-option label="号码" value="number"></el-option>
                  <el-option label="赛事名称" value="event"></el-option>
                </el-select>
                <el-button 
                  v-if="selectedElement" 
                  @click="scaleElement(0.9)" 
                  :disabled="!selectedElement"
                  size="small"
                >
                  缩小
                </el-button>
                <el-button 
                  v-if="selectedElement" 
                  @click="scaleElement(1.1)" 
                  :disabled="!selectedElement"
                  size="small"
                >
                  放大
                </el-button>
                <el-button 
                  v-if="selectedElement" 
                  @click="resetElementScale" 
                  size="small"
                >
                  重置
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseBibDialog">取 消</el-button>
        <el-button type="primary" @click="handleCreateTask" :loading="bibDialog.loading">创建任务</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 云端字体选择对话框 -->
  <el-dialog v-model="cloudFontVisible" title="选择云端字体" width="600px" append-to-body>
    <el-table v-loading="fontLoading" :data="fontList" @row-click="handleCloudFontSelect" highlight-current-row>
      <el-table-column label="字体名称" align="center" prop="originalName" />
      <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleCloudFontSelect(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cloudFontVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, getCurrentInstance } from 'vue';
import { createBibTask } from '@/api/system/gameEvent/task';
import { listOss } from '@/api/system/oss';
import { getToken } from '@/utils/auth';
import type { UploadInstance } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';

// 定义组件实例类型
interface ComponentInternalInstance {
  proxy?: {
    $modal: {
      msgError: (msg: string) => void;
      msgWarning: (msg: string) => void;
      msgSuccess: (msg: string) => void;
    };
  };
}

// 获取组件实例
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

// 预览框尺寸常量（与后端保持一致）
// 实际输出尺寸
const ACTUAL_WIDTH = 2948;
const ACTUAL_HEIGHT = 2079;
// 预览缩放比例
const PREVIEW_SCALE = 3;
// 预览尺寸（实际尺寸除以3，四舍五入）
const PREVIEW_WIDTH = Math.round(ACTUAL_WIDTH / PREVIEW_SCALE); // 983
const PREVIEW_HEIGHT = Math.round(ACTUAL_HEIGHT / PREVIEW_SCALE); // 693

// 响应式数据定义
const bibDialog = reactive({
  visible: false,
  loading: false
});

const selectedElement = ref<string>(''); // 当前选中的元素
const canvasScale = ref<number>(1); // 画布缩放比例

const bibForm = reactive({
  // 统一使用百分比坐标系统 (0-100)
  logoX: 4.17,      // 25/600 * 100 = 4.17%
  logoY: 6.25,      // 25/400 * 100 = 6.25%
  qRCodeX: 11.67,   // 70/600 * 100 = 11.67%
  qRCodeY: 32.5,    // 130/400 * 100 = 32.5%
  fontName: 'simhei',
  fontSize: 36,
  fontColor: '#000000',
  fontColorHex: '#000000',
  eventName: '',
  // 位置字段（百分比）
  numberX: 50,      // 百分比位置
  numberY: 50,      // 百分比位置
  eventX: 50,       // 百分比位置
  eventY: 5,        // 百分比位置
  // 添加元素尺寸控制字段
  logoScale: 1,
  barcodeScale: 1,
  numberScale: 1,
  eventScale: 1,
  // 字体相关
  fontOssId: null as number | null,
  isCustomFont: false,
  customFontName: '',
  customFontNameValue: '' // 存储自定义字体的内部标识符，如 CustomFont_123
});

const uploadHeaders = ref({
  Authorization: 'Bearer ' + getToken(),
  clientid: import.meta.env.VITE_APP_CLIENT_ID
});
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');

const cloudFontVisible = ref(false);
const fontLoading = ref(false);
const fontPreviewLoading = ref(false); // 字体预览加载状态
const fontList = ref<any[]>([]);

const bgImageFile = ref<File | null>(null);
const logoImageFile = ref<File | null>(null);
const bgImageUrl = ref<string>('');
const logoImageUrl = ref<string>('');
const previewContainer = ref<HTMLElement>();
const bgImageDimensions = ref<{ width: number; height: number } | null>(null);
const logoImageDimensions = ref<{ width: number; height: number } | null>(null);
const bgUploadRef = ref<UploadInstance>();
const logoUploadRef = ref<UploadInstance>();

// 拖拽相关
const dragState = reactive({
  isDragging: false,
  dragTarget: '',
  startX: 0,
  startY: 0,
  startLeft: 0,
  startTop: 0
});

// 关闭对话框
const handleCloseBibDialog = () => {
  bibDialog.visible = false;
  resetBibForm();

  // 清除上传的文件
  if (bgUploadRef.value) {
    bgUploadRef.value.clearFiles();
  }
  if (logoUploadRef.value) {
    logoUploadRef.value.clearFiles();
  }
};

// 添加元素缩放方法
const scaleElement = (factor: number) => {
  if (!selectedElement.value) return;
  
  switch (selectedElement.value) {
    case 'logo':
      bibForm.logoScale = Math.max(0.1, bibForm.logoScale * factor);
      break;
    case 'barcode':
      bibForm.barcodeScale = Math.max(0.1, bibForm.barcodeScale * factor);
      break;
    case 'number':
      bibForm.numberScale = Math.max(0.1, bibForm.numberScale * factor);
      break;
    case 'event':
      bibForm.eventScale = Math.max(0.1, bibForm.eventScale * factor);
      break;
  }
};

// 重置元素缩放
const resetElementScale = () => {
  if (!selectedElement.value) return;
  
  switch (selectedElement.value) {
    case 'logo':
      bibForm.logoScale = 1;
      break;
    case 'barcode':
      bibForm.barcodeScale = 1;
      break;
    case 'number':
      bibForm.numberScale = 1;
      break;
    case 'event':
      bibForm.eventScale = 1;
      break;
  }
};

// 重置表单
const resetBibForm = () => {
  // 设置默认值（百分比单位）
  bibForm.logoX = 4.17;      // 25/600 * 100 = 4.17%
  bibForm.logoY = 6.25;      // 25/400 * 100 = 6.25%
  bibForm.qRCodeX = 11.67;   // 70/600 * 100 = 11.67%
  bibForm.qRCodeY = 32.5;    // 130/400 * 100 = 32.5%
  bibForm.fontName = 'simhei';
  bibForm.fontSize = 36;
  bibForm.fontColor = '#000000';
  bibForm.fontColorHex = '#000000';
  bibForm.eventName = '';
  
  // 添加位置重置
  bibForm.numberX = 50;
  bibForm.numberY = 50;
  bibForm.eventX = 50;
  bibForm.eventY = 5;
  
  bgImageFile.value = null;
  logoImageFile.value = null;
  bgImageUrl.value = '';
  logoImageUrl.value = '';
  bgImageDimensions.value = null;
  logoImageDimensions.value = null;

  // 重置缩放
  bibForm.logoScale = 1;
  bibForm.barcodeScale = 1;
  bibForm.numberScale = 1;
  bibForm.eventScale = 1;
  // 重置选中元素
  selectedElement.value = '';
  // 重置画布比例
  canvasScale.value = 1;
  
  // 重置自定义字体
  bibForm.fontOssId = null;
  bibForm.isCustomFont = false;
  bibForm.customFontName = '';
  bibForm.customFontNameValue = '';

  // 清除上传的文件
  if (bgUploadRef.value) {
    bgUploadRef.value.clearFiles();
  }
  if (logoUploadRef.value) {
    logoUploadRef.value.clearFiles();
  }
};

// 背景图片改变处理
const handleBgImageChange = async (file: any) => {
  if (file.raw) {
    // 直接使用原始图片，不进行裁剪
    bgImageFile.value = file.raw;

    const reader = new FileReader();
    reader.onload = (e) => {
      bgImageUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(file.raw);

    // 获取原始图片尺寸
    try {
      const dimensions = await getImageDimensions(file.raw);
      bgImageDimensions.value = dimensions;
    } catch (error) {
      console.error('获取图片尺寸失败:', error);
    }

    // 添加成功提示
    proxy?.$modal.msgSuccess('背景图片上传成功');
  }
};

// Logo图片改变处理
const handleLogoImageChange = async (file: any) => {
  if (file.raw) {
    logoImageFile.value = file.raw;
    const reader = new FileReader();
    reader.onload = (e) => {
      logoImageUrl.value = e.target?.result as string;
    };
    reader.readAsDataURL(file.raw);

    // 获取Logo图片尺寸
    try {
      const dimensions = await getImageDimensions(file.raw);
      logoImageDimensions.value = dimensions;
    } catch (error) {
      console.error('获取Logo图片尺寸失败:', error);
    }

    // 添加成功提示
    proxy?.$modal.msgSuccess('Logo图片上传成功');
  }
};

// 删除背景图片
const removeBgImage = () => {
  bgImageFile.value = null;
  bgImageUrl.value = '';
  bgImageDimensions.value = { width: 0, height: 0 };
  if (bgUploadRef.value) {
    bgUploadRef.value.clearFiles();
  }
  proxy?.$modal.msgSuccess('背景图片已删除');
};

// 删除Logo图片
const removeLogoImage = () => {
  logoImageFile.value = null;
  logoImageUrl.value = '';
  logoImageDimensions.value = null;
  if (logoUploadRef.value) {
    logoUploadRef.value.clearFiles();
  }
  proxy?.$modal.msgSuccess('Logo图片已删除');
};

// 字体颜色改变处理
const handleFontColorChange = (color: string) => {
  bibForm.fontColor = color;
  bibForm.fontColorHex = color;
};

// 上传字体成功回调
const handleFontUploadSuccess = (response: any) => {
  if (response.code === 200) {
    const ossData = response.data;
    loadCustomFont(ossData.url, ossData.originalName, ossData.ossId);
    proxy?.$modal.msgSuccess('字体上传成功');
  } else {
    proxy?.$modal.msgError(response.msg || '上传失败');
  }
};

// 打开云端字体对话框
const openCloudFontDialog = async () => {
  cloudFontVisible.value = true;
  fontLoading.value = true;
  try {
    const res = await listOss({ fileSuffix: '.ttf' } as any);
    const resOtf = await listOss({ fileSuffix: '.otf' } as any);
    fontList.value = [...(res.rows || []), ...(resOtf.rows || [])];
  } finally {
    fontLoading.value = false;
  }
};

// 选择云端字体
const handleCloudFontSelect = (row: any) => {
  loadCustomFont(row.url, row.originalName, row.ossId);
  cloudFontVisible.value = false;
};

// 加载并注册自定义字体以供预览
const loadCustomFont = async (url: string, name: string, ossId: number) => {
  // 1. 处理名称：去除后缀
  const cleanName = name.replace(/\.[^/.]+$/, "");
  const fontFamily = `CustomFont_${ossId}`;
  
  // 2. 检查缓存：如果该字体已经加载过，直接应用
  const existingFont = Array.from(document.fonts).find(f => f.family === fontFamily);
  if (existingFont && existingFont.status === 'loaded') {
    bibForm.fontName = fontFamily;
    bibForm.fontOssId = ossId;
    bibForm.isCustomFont = true;
    bibForm.customFontName = cleanName;
    bibForm.customFontNameValue = fontFamily;
    return;
  }

  fontPreviewLoading.value = true;
  try {
    const fontFace = new FontFace(fontFamily, `url(${url})`);
    // 显式添加到集合中
    document.fonts.add(fontFace);
    
    // 3. 等待加载完成
    await fontFace.load();
    
    // 4. 更新状态
    bibForm.fontName = fontFamily;
    bibForm.fontOssId = ossId;
    bibForm.isCustomFont = true;
    bibForm.customFontName = cleanName;
    bibForm.customFontNameValue = fontFamily;
    
    proxy?.$modal.msgSuccess(`成功加载字体: ${cleanName}`);
  } catch (error) {
    console.error('加载字体文件失败:', error);
    proxy?.$modal.msgError('加载预览字体失败');
    
    // 即使加载失败也记录信息
    bibForm.fontName = fontFamily;
    bibForm.fontOssId = ossId;
    bibForm.isCustomFont = true;
    bibForm.customFontName = cleanName;
  } finally {
    fontPreviewLoading.value = false;
  }
};

// 开始拖拽
const startDrag = (event: MouseEvent, target: string) => {
  event.preventDefault();
  dragState.isDragging = true;
  dragState.dragTarget = target;
  dragState.startX = event.clientX;
  dragState.startY = event.clientY;

  selectedElement.value = target;

  if (target === 'logo') {
    dragState.startLeft = bibForm.logoX;
    dragState.startTop = bibForm.logoY;
  } else if (target === 'barcode') {
    dragState.startLeft = bibForm.qRCodeX;
    dragState.startTop = bibForm.qRCodeY;
  } else if (target === 'number') {
    // 修复：使用存储的位置数据
    dragState.startLeft = bibForm.numberX;
    dragState.startTop = bibForm.numberY;
  } else if (target === 'event') {
    // 修复：使用存储的位置数据
    dragState.startLeft = bibForm.eventX;
    dragState.startTop = bibForm.eventY;
  }

  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
};

// 处理拖拽
const handleDrag = (event: MouseEvent) => {
  if (!dragState.isDragging) return;

  const deltaX = event.clientX - dragState.startX;
  const deltaY = event.clientY - dragState.startY;

  const container = previewContainer.value;
  const previewWidth = container?.clientWidth || container?.offsetWidth || PREVIEW_WIDTH;
  const previewHeight = container?.clientHeight || container?.offsetHeight || PREVIEW_HEIGHT;

  // 统一使用百分比坐标系统
  const newX = Math.max(0, Math.min(100, dragState.startLeft + (deltaX / previewWidth) * 100));
  const newY = Math.max(0, Math.min(100, dragState.startTop + (deltaY / previewHeight) * 100));
  
  if (dragState.dragTarget === 'logo') {
    bibForm.logoX = newX;
    bibForm.logoY = newY;
  } else if (dragState.dragTarget === 'barcode') {
    bibForm.qRCodeX = newX;
    bibForm.qRCodeY = newY;
  } else if (dragState.dragTarget === 'number') {
    bibForm.numberX = newX;
    bibForm.numberY = newY;
  } else if (dragState.dragTarget === 'event') {
    bibForm.eventX = newX;
    bibForm.eventY = newY;
  }
};

// 停止拖拽
const stopDrag = () => {
  if (dragState.dragTarget) {
    let finalX = 0, finalY = 0, targetName = '';
    
    if (dragState.dragTarget === 'logo') {
      finalX = bibForm.logoX;
      finalY = bibForm.logoY;
      targetName = 'Logo';
    } else if (dragState.dragTarget === 'barcode') {
      finalX = bibForm.qRCodeX;
      finalY = bibForm.qRCodeY;
      targetName = '二维码';
    } else if (dragState.dragTarget === 'number') {
      finalX = bibForm.numberX;
      finalY = bibForm.numberY;
      targetName = '号码';
    } else if (dragState.dragTarget === 'event') {
      finalX = bibForm.eventX;
      finalY = bibForm.eventY;
      targetName = '赛事名称';
    }
    
  }
  
  dragState.isDragging = false;
  dragState.dragTarget = '';
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);
};

// 获取背景图片实际尺寸的函数
const getImageDimensions = (file: File): Promise<{ width: number; height: number }> => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      resolve({ width: img.width, height: img.height });
    };
    img.src = URL.createObjectURL(file);
  });
};

// 创建参赛证生成任务
const handleCreateTask = async () => {
  // 校验必须上传背景图
  if (!bgImageFile.value) {
    proxy?.$modal.msgError('请上传背景图片');
    return;
  }

  bibDialog.loading = true;
  try {
    let qRCodeX = bibForm.qRCodeX;
    let qRCodeY = bibForm.qRCodeY;

    // 如果值为null或undefined，强制使用默认值
    if (qRCodeX === null || qRCodeX === undefined || isNaN(qRCodeX)) {
      qRCodeX = 70;
      console.warn('qRCodeX值异常，使用默认值70px');
    }

    if (qRCodeY === null || qRCodeY === undefined || isNaN(qRCodeY)) {
      qRCodeY = 130;
      console.warn('qRCodeY值异常，使用默认值130px');
    }

    // 检查背景图片尺寸
    if (!bgImageDimensions.value) {
      proxy?.$modal.msgWarning('正在获取背景图片尺寸，请稍后再试');
      return;
    }

    // 等待一帧确保所有尺寸都已计算完成
    await nextTick();

    // 计算画布的实际尺寸（使用固定的实际输出尺寸）
    const originalWidth = ACTUAL_WIDTH;
    const originalHeight = ACTUAL_HEIGHT;

    // 将百分比坐标转换为像素坐标
    const convertPercentToPixel = (percent: number, dimension: number): number => {
      return Math.round((percent / 100) * dimension);
    };

    // Logo像素坐标和尺寸
    const logoPixelX = convertPercentToPixel(bibForm.logoX || 4.17, originalWidth);
    const logoPixelY = convertPercentToPixel(bibForm.logoY || 6.25, originalHeight);

    // 计算Logo尺寸（需要乘以缩放比例，保证与预览效果一致）
    const logoOriginalWidth = logoImageDimensions.value?.width || 80;
    const logoOriginalHeight = logoImageDimensions.value?.height || 80;
    const logoPreviewSize = 80; // 前端预览时的最大尺寸
    const logoScale = Math.min(1.0, logoPreviewSize / Math.max(logoOriginalWidth, logoOriginalHeight));
    const logoFinalWidth = Math.round(logoOriginalWidth * logoScale * bibForm.logoScale * PREVIEW_SCALE);
    const logoFinalHeight = Math.round(logoOriginalHeight * logoScale * bibForm.logoScale * PREVIEW_SCALE);

    // 二维码像素坐标
    const validQRCodeX = (qRCodeX !== null && qRCodeX !== undefined && !isNaN(qRCodeX)) ? qRCodeX : 11.67;
    const validQRCodeY = (qRCodeY !== null && qRCodeY !== undefined && !isNaN(qRCodeY)) ? qRCodeY : 32.5;
    const qrPixelX = convertPercentToPixel(validQRCodeX, originalWidth);
    const qrPixelY = convertPercentToPixel(validQRCodeY, originalHeight);

    // 计算二维码尺寸（需要乘以缩放比例，保证与预览效果一致）
    const qrInitialSize = 32;
    const qrFinalWidth = Math.round(qrInitialSize * bibForm.barcodeScale * PREVIEW_SCALE);
    const qrFinalHeight = Math.round(qrInitialSize * bibForm.barcodeScale * PREVIEW_SCALE);

    // 号码像素坐标
    const numberPixelX = convertPercentToPixel(bibForm.numberX || 50, originalWidth);
    const numberPixelY = convertPercentToPixel(bibForm.numberY || 50, originalHeight);

    // 计算号码字体大小（需要乘以缩放比例，保证与预览效果一致）
    const numberPixelFontSize = Math.round((bibForm.fontSize || 36) * bibForm.numberScale * PREVIEW_SCALE);

    // 赛事名称像素坐标
    const eventPixelX = convertPercentToPixel(bibForm.eventX || 50, originalWidth);
    const eventPixelY = convertPercentToPixel(bibForm.eventY || 5, originalHeight);

    // 计算赛事名称字体大小（需要乘以缩放比例，保证与预览效果一致）
    const eventPixelFontSize = Math.round((bibForm.fontSize || 36) * bibForm.eventScale * PREVIEW_SCALE);

    const bibParams = {
      // 画布实际尺寸
      width: originalWidth,
      height: originalHeight,
      
      // Logo参数（像素）
      logoX: logoPixelX,
      logoY: logoPixelY,
      logoWidth: logoFinalWidth,
      logoHeight: logoFinalHeight,
      
      // 二维码参数（像素）
      qRCodeX: qrPixelX,
      qRCodeY: qrPixelY,
      qRCodeWidth: qrFinalWidth,
      qRCodeHeight: qrFinalHeight,
      
      // 号码参数（像素）
      numberX: numberPixelX,
      numberY: numberPixelY,
      numberFontSize: numberPixelFontSize,
      
      // 赛事名称参数（像素）
      eventX: eventPixelX,
      eventY: eventPixelY,
      eventFontSize: eventPixelFontSize,
      
      // 其他通用参数
      fontName: bibForm.fontName || 'simhei',
      fontOssId: bibForm.fontOssId,
      fontSize: bibForm.fontSize || 36,
      fontColor: parseInt((bibForm.fontColor || '#000000').replace('#', ''), 16),
      eventName: bibForm.eventName || '',
    };
    
    const taskName = `参赛证生成_${parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')}`;
    
    // 调用创建任务API
    const response = await createBibTask(
      bgImageFile.value, 
      logoImageFile.value, 
      taskName, 
      bibParams
    );
    
    proxy?.$modal.msgSuccess('任务创建成功，请到任务列表查看进度');
    handleCloseBibDialog();
    
    // 跳转到任务列表页面
    router.push('/system/gameEvent/taskList');
    
  } catch (error: any) {
    console.error('创建任务失败:', error);
    proxy?.$modal.msgError('创建任务失败：' + error.message);
  } finally {
    bibDialog.loading = false;
  }
};

// 暴露方法给父组件
defineExpose({
  bibDialog,
  bibForm,
  bgImageFile,
  logoImageFile,
  bgImageUrl,
  logoImageUrl,
  bgImageDimensions,
  logoImageDimensions,
  canvasScale,
  handleCloseBibDialog,
  resetBibForm,
  handleBgImageChange,
  handleLogoImageChange,
  removeBgImage,
  removeLogoImage,
  handleFontColorChange,
  startDrag,
  handleCreateTask
});
</script>

<style scoped lang="scss">
/* 生成参赛证样式 */
.bib-generator {
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;    // 让内容居中
}

/* 预览容器 - 固定尺寸 983x693 */
.preview-container {
  border: 2px dashed #ddd;
  border-radius: 8px;
  width: 983px !important;
  height: 693px !important;
  position: relative;
  overflow: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;        // 居中显示并保留底部间距
  background-color: #f8f9fa;
}

/* 上传按钮区域 */
.upload-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.upload-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-row {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .el-upload {
    display: inline-block;
  }
}

/* 配置表单 */
.config-form {
  margin-top: 10px;
}

.preview-canvas {
  width: 983px;
  height: 693px;
  position: relative;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;
}

.draggable-element {
  position: absolute;
  cursor: move;
  user-select: none;
  z-index: 10;
}

.draggable-element:hover {
  opacity: 0.8;
}

.logo-element {
  border: 2px dashed transparent;
}

.logo-element:hover {
  border-color: #409eff;
}

.barcode-element {
  border: 2px dashed transparent;
  padding: 5px;
}

.barcode-element:hover {
  border-color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  white-space: nowrap;
}

.file-info {
  margin-top: 8px;
  padding: 8px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px;
  color: #606266;
  margin-right: 8px;
}

.remove-btn {
  color: #f56c6c;
  font-size: 12px;
  padding: 0;
  min-height: auto;
}

.remove-btn:hover {
  color: #f56c6c;
  background-color: transparent;
}

.number-element {
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  border: 2px dashed transparent;
  padding: 4px;
  white-space: nowrap;
  user-select: none;
  /* pointer-events: none; */
  text-align: center;
  min-width: 80px;
}

.event-name-preview {
  position: absolute;
  // top: 5%;
  // left: 50%;
  // transform: translateX(-50%);
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
  user-select: none;
  // pointer-events: none;
  z-index: 5;
  text-align: center;
  white-space: nowrap;
  max-width: 80%;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 选中元素样式 */
.draggable-element.selected {
  outline: 2px solid #409eff;
  outline-offset: 2px;
}

/* 坐标系统说明样式 */
.coordinate-info {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.coord-marker {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #f56c6c;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
  z-index: 100;
}

.coord-label {
  position: absolute;
  left: 15px;
  top: -5px;
  background-color: rgba(245, 108, 108, 0.9);
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.coord-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #909399;
  font-size: 14px;
  line-height: 1.8;
  
  p:first-child {
    font-size: 16px;
    font-weight: bold;
    color: #606266;
    margin-bottom: 10px;
  }
  
  p {
    margin: 5px 0;
  }
}
</style>
