<template>
    <div class="contract-config">
        <div class="header">
            <h2>合同签名区域配置</h2>
            <el-button type="primary" @click="saveSignAreas">保存配置</el-button>
        </div>

        <div class="content">
            <!-- PDF上传区域 -->
            <div class="upload-section">
                <el-upload
                    class="upload-demo"
                    :on-success="handleUploadSuccess"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    :auto-upload="false"
                    accept=".pdf"
                >
                    <template #trigger>
                        <el-button type="primary">上传合同PDF</el-button>
                    </template>
                    <template #tip>
                        <div class="el-upload__tip">请上传PDF格式的合同文件</div>
                    </template>
                </el-upload>
                <div style="margin-top: 15px">
                    <el-button type="success" @click="loadDemoPdf">加载演示PDF</el-button>
                </div>
            </div>

            <!-- PDF预览和坐标设置区域 -->
            <div class="preview-section" v-if="pdfUrl">
                <div class="enhancement-info">
                    <h4>✨ 修复说明</h4>
                    <p>已修复删除签名区域的bug，现在可以正确删除单个签名区域。</p>
                </div>
                <div class="preview-container">
                    <!-- PDF页面列表 -->
                    <div class="page-list">
                        <div
                            v-for="page in pages"
                            :key="page.pageNumber"
                            class="page-item"
                            :class="{ active: currentPage === page.pageNumber }"
                            @click="switchPage(page.pageNumber)"
                        >
                            第{{ page.pageNumber }}页
                        </div>
                    </div>

                    <!-- PDF预览画布 -->
                    <div class="pdf-viewer">
                        <div class="viewer-controls">
                            <el-button @click="zoomOut" :disabled="scale <= 0.5">缩小</el-button>
                            <span class="scale-text">{{ Math.round(scale * 100) }}%</span>
                            <el-button @click="zoomIn" :disabled="scale >= 2">放大</el-button>
                            <el-button type="primary" @click="addSignArea">添加签名区域</el-button>
                            <el-button @click="clearAllAreas">清空所有区域</el-button>
                        </div>

                        <div class="pdf-container" ref="pdfContainer" @click="onCanvasClick">
                            <canvas
                                v-for="page in visiblePages"
                                :key="page.pageNumber"
                                :ref="el => setCanvasRef(el, page.pageNumber)"
                                class="pdf-canvas"
                            ></canvas>

                            <!-- 签名区域标记 -->
                            <div
                                v-for="area in currentPageAreas"
                                :key="area.id"
                                class="sign-area-marker"
                                :class="{
                                    selected: selectedArea?.id === area.id,
                                    dragging: draggingArea?.id === area.id,
                                    resizing: resizingArea?.id === area.id,
                                }"
                                :style="{
                                    left: area.x * scale + 'px',
                                    top: area.y * scale + 'px',
                                    width: area.width * scale + 'px',
                                    height: area.height * scale + 'px',
                                }"
                                @mousedown="startDrag(area, $event)"
                                @click.stop="selectArea(area)"
                            >
                                <div class="area-label">{{ area.roleName }}</div>
                                <div class="area-actions" v-if="selectedArea?.id === area.id">
                                    <el-icon @click.stop="editArea(area)"><Edit /></el-icon>
                                    <el-icon @click.stop="deleteArea(area.id)"><Delete /></el-icon>
                                </div>
                                <div
                                    class="resize-handle"
                                    v-if="selectedArea?.id === area.id"
                                    @mousedown.stop="startResize(area, $event)"
                                ></div>
                            </div>
                        </div>
                    </div>

                    <!-- 签名区域配置表单 -->
                    <div class="config-form">
                        <el-card header="签名区域配置">
                            <el-form :model="areaForm" label-width="80px">
                                <el-form-item label="签署角色">
                                    <el-input
                                        v-model="areaForm.roleName"
                                        placeholder="输入签署角色名称，如：甲方、乙方、见证人等"
                                        maxlength="20"
                                        show-word-limit
                                    />
                                    <div class="role-presets">
                                        <el-tag
                                            v-for="preset in rolePresets"
                                            :key="preset"
                                            class="role-preset-tag"
                                            @click="areaForm.roleName = preset"
                                        >
                                            {{ preset }}
                                        </el-tag>
                                    </div>
                                </el-form-item>

                                <el-form-item label="签署人">
                                    <el-input
                                        v-model="areaForm.signerName"
                                        placeholder="输入签署人姓名"
                                        maxlength="20"
                                        show-word-limit
                                    />
                                </el-form-item>

                                <el-form-item label="区域位置">
                                    <div class="coord-inputs">
                                        <el-input-number
                                            v-model="areaForm.x"
                                            placeholder="X坐标"
                                            :min="0"
                                            @change="updateSelectedArea"
                                        />
                                        <el-input-number
                                            v-model="areaForm.y"
                                            placeholder="Y坐标"
                                            :min="0"
                                            @change="updateSelectedArea"
                                        />
                                    </div>
                                </el-form-item>

                                <el-form-item label="区域大小">
                                    <div class="size-inputs">
                                        <el-input-number
                                            v-model="areaForm.width"
                                            placeholder="宽度"
                                            :min="50"
                                            @change="updateSelectedArea"
                                        />
                                        <el-input-number
                                            v-model="areaForm.height"
                                            placeholder="高度"
                                            :min="30"
                                            @change="updateSelectedArea"
                                        />
                                    </div>
                                </el-form-item>

                                <el-form-item label="页面">
                                    <el-input-number
                                        v-model="areaForm.page"
                                        :min="1"
                                        :max="totalPages"
                                        @change="updateSelectedArea"
                                    />
                                </el-form-item>

                                <el-form-item>
                                    <el-button
                                        type="primary"
                                        @click="saveAreaConfig"
                                        :disabled="!areaForm.roleName"
                                    >
                                        {{ isEditing ? '更新区域' : '添加区域' }}
                                    </el-button>
                                    <el-button @click="cancelEdit" v-if="isEditing">取消</el-button>
                                </el-form-item>
                            </el-form>

                            <!-- 已配置区域列表 -->
                            <div class="areas-list">
                                <h4>已配置的签名区域</h4>
                                <el-table :data="allAreas" style="width: 100%">
                                    <el-table-column prop="roleName" label="角色" />
                                    <el-table-column prop="signerName" label="签署人" />
                                    <el-table-column label="位置">
                                        <template #default="{ row }">
                                            ({{ row.x }}, {{ row.y }})
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="大小">
                                        <template #default="{ row }">
                                            {{ row.width }} × {{ row.height }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="page" label="页面" />
                                    <el-table-column label="操作">
                                        <template #default="{ row }">
                                            <el-button link @click="editArea(row)">编辑</el-button>
                                            <el-button link @click="deleteArea(row.id)">
                                                删除
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>

            <!-- 演示信息 -->
            <div class="demo-info" v-if="!pdfUrl">
                <h3>使用说明</h3>
                <p>这是一个合同签名区域配置工具的演示版本，您可以：</p>
                <ul>
                    <li>点击"加载演示PDF"按钮来体验功能</li>
                    <li>在PDF页面上点击以设置签名区域位置</li>
                    <li><strong>自定义签署角色名称和签署人姓名</strong></li>
                    <li>添加、编辑和删除签名区域</li>
                    <li>在不同页面之间切换</li>
                    <li>放大/缩小PDF视图</li>
                    <li>直接拖拽签名区域来移动位置</li>
                    <li>拖拽右下角调整签名区域大小</li>
                </ul>
                <p style="margin-top: 10px">
                    注意：这是一个前端演示，PDF渲染和签名区域配置仅为模拟功能。
                </p>
            </div>
        </div>
    </div>
</template>

<script setup name="SignatureEdit">
// 响应式数据
const pdfUrl = ref('');
const totalPages = ref(3);
const currentPage = ref(1);
const scale = ref(1.0);
const pages = ref([]);
const canvasRefs = ref({});
const pdfContainer = ref(null);

// 签名区域数据
const signAreas = ref([]);
const selectedArea = ref(null);
const isEditing = ref(false);
const draggingArea = ref(null);
const resizingArea = ref(null);
const dragStartX = ref(0);
const dragStartY = ref(0);
const originalArea = ref(null);

// 角色预设
const rolePresets = ref(['甲方', '乙方', '丙方', '见证方', '法定代表人', '授权代表', '经办人']);

// 表单数据
const areaForm = reactive({
    id: null,
    roleName: '',
    signerName: '',
    x: 0,
    y: 0,
    width: 100,
    height: 50,
    page: 1,
});

// 计算属性
const visiblePages = computed(() => {
    return pages.value.filter(page => page.pageNumber === currentPage.value);
});

const currentPageAreas = computed(() => {
    return signAreas.value.filter(area => area.page === currentPage.value);
});

const allAreas = computed(() => {
    return signAreas.value.map(area => ({
        ...area,
    }));
});

// 方法
const handleUploadSuccess = response => {
    ElMessage.success('文件上传成功');
    pdfUrl.value = 'demo';
    loadPdf();
};

const beforeUpload = file => {
    const isPDF = file.type === 'application/pdf';
    if (!isPDF) {
        ElMessage.error('只能上传PDF文件!');
        return false;
    }
    return true;
};

const loadDemoPdf = () => {
    pdfUrl.value = 'demo';
    loadPdf();
    ElMessage.success('演示PDF已加载');
};

const loadPdf = async () => {
    try {
        // 初始化页面数据
        pages.value = [];
        for (let i = 1; i <= totalPages.value; i++) {
            pages.value.push({
                pageNumber: i,
                rendered: false,
            });
        }

        // 渲染第一页
        await renderPage(1);
    } catch (error) {
        ElMessage.error('PDF加载失败: ' + error.message);
    }
};

const renderPage = async pageNum => {
    try {
        await nextTick();

        const canvas = canvasRefs.value[pageNum];
        if (!canvas) return;

        const context = canvas.getContext('2d');
        const width = 800;
        const height = 1000;

        canvas.width = width * scale.value;
        canvas.height = height * scale.value;

        // 绘制模拟PDF页面
        context.fillStyle = 'white';
        context.fillRect(0, 0, width * scale.value, height * scale.value);

        context.fillStyle = '#333';
        context.font = `${20 * scale.value}px Arial`;
        context.textAlign = 'center';
        context.fillText(
            `合同文档 - 第 ${pageNum} 页`,
            (width * scale.value) / 2,
            50 * scale.value
        );

        context.font = `${14 * scale.value}px Arial`;
        context.textAlign = 'left';

        // 绘制一些模拟内容
        for (let i = 1; i <= 20; i++) {
            context.fillText(
                `这是合同第 ${pageNum} 页的第 ${i} 行内容，用于演示签名区域配置功能。`,
                50 * scale.value,
                (100 + i * 30) * scale.value
            );
        }

        // 绘制页脚
        context.fillStyle = '#666';
        context.font = `${12 * scale.value}px Arial`;
        context.textAlign = 'center';
        context.fillText(
            `第 ${pageNum} 页`,
            (width * scale.value) / 2,
            height * scale.value - 30 * scale.value
        );

        // 更新页面状态
        const pageIndex = pages.value.findIndex(p => p.pageNumber === pageNum);
        if (pageIndex !== -1) {
            pages.value[pageIndex].rendered = true;
            pages.value[pageIndex].width = width;
            pages.value[pageIndex].height = height;
        }
    } catch (error) {
        console.error('渲染页面失败:', error);
    }
};

const switchPage = async pageNum => {
    currentPage.value = pageNum;
    areaForm.page = pageNum;
    await nextTick();

    if (!pages.value.find(p => p.pageNumber === pageNum)?.rendered) {
        await renderPage(pageNum);
    }
};

const setCanvasRef = (el, pageNumber) => {
    if (el) {
        canvasRefs.value[pageNumber] = el;
    }
};

const zoomIn = () => {
    if (scale.value < 2) {
        scale.value += 0.1;
        rerenderCurrentPage();
    }
};

const zoomOut = () => {
    if (scale.value > 0.5) {
        scale.value -= 0.1;
        rerenderCurrentPage();
    }
};

const rerenderCurrentPage = () => {
    renderPage(currentPage.value);
};

const onCanvasClick = event => {
    if (!pdfContainer.value) return;

    const rect = pdfContainer.value.getBoundingClientRect();
    const x = (event.clientX - rect.left) / scale.value;
    const y = (event.clientY - rect.top) / scale.value;

    // 设置点击位置为新的签名区域坐标
    areaForm.x = Math.round(x);
    areaForm.y = Math.round(y);
    areaForm.page = currentPage.value;
};

// 拖拽功能
const startDrag = (area, event) => {
    draggingArea.value = area;
    originalArea.value = { ...area };
    dragStartX.value = event.clientX;
    dragStartY.value = event.clientY;

    document.addEventListener('mousemove', onDragMove);
    document.addEventListener('mouseup', onDragEnd);

    event.preventDefault();
};

const onDragMove = event => {
    if (!draggingArea.value || !pdfContainer.value) return;

    const rect = pdfContainer.value.getBoundingClientRect();
    const deltaX = (event.clientX - dragStartX.value) / scale.value;
    const deltaY = (event.clientY - dragStartY.value) / scale.value;

    // 更新区域位置
    draggingArea.value.x = Math.max(0, originalArea.value.x + deltaX);
    draggingArea.value.y = Math.max(0, originalArea.value.y + deltaY);

    // 如果当前编辑的是这个区域，更新表单
    if (selectedArea.value && selectedArea.value.id === draggingArea.value.id) {
        areaForm.x = draggingArea.value.x;
        areaForm.y = draggingArea.value.y;
    }
};

const onDragEnd = () => {
    draggingArea.value = null;
    originalArea.value = null;

    document.removeEventListener('mousemove', onDragMove);
    document.removeEventListener('mouseup', onDragEnd);
};

// 调整大小功能
const startResize = (area, event) => {
    resizingArea.value = area;
    originalArea.value = { ...area };
    dragStartX.value = event.clientX;
    dragStartY.value = event.clientY;

    document.addEventListener('mousemove', onResizeMove);
    document.addEventListener('mouseup', onResizeEnd);

    event.stopPropagation();
    event.preventDefault();
};

const onResizeMove = event => {
    if (!resizingArea.value || !pdfContainer.value) return;

    const deltaX = (event.clientX - dragStartX.value) / scale.value;
    const deltaY = (event.clientY - dragStartY.value) / scale.value;

    // 更新区域大小
    resizingArea.value.width = Math.max(50, originalArea.value.width + deltaX);
    resizingArea.value.height = Math.max(30, originalArea.value.height + deltaY);

    // 如果当前编辑的是这个区域，更新表单
    if (selectedArea.value && selectedArea.value.id === resizingArea.value.id) {
        areaForm.width = resizingArea.value.width;
        areaForm.height = resizingArea.value.height;
    }
};

const onResizeEnd = () => {
    resizingArea.value = null;
    originalArea.value = null;

    document.removeEventListener('mousemove', onResizeMove);
    document.removeEventListener('mouseup', onResizeEnd);
};

const addSignArea = () => {
    // 重置表单
    Object.assign(areaForm, {
        id: null,
        roleName: '',
        signerName: '',
        x: 0,
        y: 0,
        width: 100,
        height: 50,
        page: currentPage.value,
    });
    isEditing.value = false;
    selectedArea.value = null;
};

const selectArea = area => {
    selectedArea.value = area;
};

const editArea = area => {
    Object.assign(areaForm, { ...area });
    isEditing.value = true;
    selectedArea.value = area;
};

const deleteArea = async areaId => {
    try {
        await ElMessageBox.confirm('确定要删除这个签名区域吗？', '确认删除', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });

        // 修复：正确删除单个区域
        const index = signAreas.value.findIndex(area => area.id === areaId);
        if (index !== -1) {
            signAreas.value.splice(index, 1);
            ElMessage.success('签名区域已删除');

            // 如果删除的是当前选中的区域，清空选中状态
            if (selectedArea.value && selectedArea.value.id === areaId) {
                selectedArea.value = null;
                addSignArea();
            }
        }
    } catch (error) {
        // 用户取消删除
        console.log('用户取消删除');
    }
};

const saveAreaConfig = () => {
    if (!areaForm.roleName) {
        ElMessage.warning('请输入签署角色名称');
        return;
    }

    if (isEditing.value) {
        // 更新现有区域
        const index = signAreas.value.findIndex(area => area.id === areaForm.id);
        if (index !== -1) {
            signAreas.value[index] = { ...areaForm };
        }
        ElMessage.success('签名区域已更新');
    } else {
        // 添加新区域
        const newArea = {
            id: Date.now().toString(),
            ...areaForm,
        };
        signAreas.value.push(newArea);
        ElMessage.success('签名区域已添加');
    }

    // 重置表单
    addSignArea();
};

const updateSelectedArea = () => {
    if (selectedArea.value && isEditing.value) {
        const index = signAreas.value.findIndex(area => area.id === selectedArea.value.id);
        if (index !== -1) {
            signAreas.value[index] = { ...areaForm };
        }
    }
};

const cancelEdit = () => {
    addSignArea();
};

const clearAllAreas = () => {
    ElMessageBox.confirm('确定要清空所有签名区域吗？', '确认清空', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            signAreas.value = [];
            selectedArea.value = null;
            ElMessage.success('已清空所有签名区域');
        })
        .catch(() => {
            // 用户取消操作
        });
};

const saveSignAreas = async () => {
    try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));

        ElMessage.success('签名区域配置保存成功');
        console.log('保存的签名区域:', JSON.stringify(signAreas.value, null, 2));
    } catch (error) {
        ElMessage.error('保存失败: ' + error.message);
    }
};

onMounted(() => {
    // 初始化一些演示数据
    signAreas.value = [
        {
            id: '1',
            roleName: '甲方',
            signerName: '张三',
            x: 200,
            y: 800,
            width: 120,
            height: 60,
            page: 1,
        },
        {
            id: '2',
            roleName: '乙方',
            signerName: '李四',
            x: 500,
            y: 800,
            width: 120,
            height: 60,
            page: 1,
        },
        {
            id: '3',
            roleName: '见证方',
            signerName: '王五',
            x: 350,
            y: 850,
            width: 120,
            height: 60,
            page: 3,
        },
    ];
});
</script>

<style scoped>
.contract-config {
    max-width: 1400px;
    margin: 0 auto;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    color: white;
}

.header h2 {
    margin: 0;
    font-weight: 500;
}

.content {
    padding: 20px;
}

.upload-section {
    margin-bottom: 20px;
    text-align: center;
    padding: 20px;
    border: 2px dashed #dcdfe6;
    border-radius: 6px;
    background-color: #fafafa;
}

.preview-section {
    margin-top: 20px;
}

.preview-container {
    display: grid;
    grid-template-columns: 150px 1fr 350px;
    gap: 20px;
    min-height: 600px;
}

.page-list {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background: white;
    max-height: 600px;
    overflow-y: auto;
}

.page-item {
    padding: 10px 12px;
    margin-bottom: 8px;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
    transition: all 0.3s;
}

.page-item:hover {
    background-color: #f5f7fa;
}

.page-item.active {
    background-color: #409eff;
    color: white;
}

.pdf-viewer {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
    background: white;
    display: flex;
    flex-direction: column;
}

.viewer-controls {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.scale-text {
    margin: 0 10px;
    font-weight: bold;
    min-width: 60px;
    text-align: center;
}

.pdf-container {
    position: relative;
    background: #f8f9fa;
    min-height: 500px;
    display: flex;
    justify-content: center;
    align-items: flex-start;
    padding: 20px;
    overflow: auto;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
}

.pdf-canvas {
    border: 1px solid #ddd;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    background: white;
    max-width: 100%;
}

.sign-area-marker {
    position: absolute;
    border: 2px dashed #409eff;
    background-color: rgba(64, 158, 255, 0.1);
    cursor: move;
    z-index: 10;
    transition: all 0.3s;
    user-select: none;
}

.sign-area-marker:hover {
    background-color: rgba(64, 158, 255, 0.2);
}

.sign-area-marker.selected {
    border: 2px solid #f56c6c;
    background-color: rgba(245, 108, 108, 0.2);
}

.sign-area-marker.dragging {
    opacity: 0.8;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.sign-area-marker.resizing {
    border: 2px solid #67c23a;
}

.area-label {
    position: absolute;
    top: -25px;
    left: 0;
    background: #409eff;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    pointer-events: none;
    max-width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
}

.area-actions {
    position: absolute;
    top: -45px;
    right: 0;
    display: flex;
    gap: 5px;
    background: white;
    padding: 4px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.area-actions .el-icon {
    cursor: pointer;
    padding: 4px;
    border-radius: 3px;
    transition: background-color 0.3s;
}

.area-actions .el-icon:hover {
    background-color: #f5f7fa;
}

.resize-handle {
    position: absolute;
    width: 12px;
    height: 12px;
    background: #409eff;
    border: 1px solid white;
    border-radius: 2px;
    bottom: -6px;
    right: -6px;
    cursor: nwse-resize;
    z-index: 20;
}

.resize-handle:hover {
    background: #67c23a;
    transform: scale(1.2);
}

.config-form {
    height: 100%;
    overflow-y: auto;
}

.config-form .el-card {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.config-form .el-card__body {
    flex: 1;
    overflow-y: auto;
}

.coord-inputs,
.size-inputs {
    display: flex;
    gap: 10px;
}

.areas-list {
    margin-top: 20px;
}

.areas-list h4 {
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
}

.demo-info {
    margin-top: 20px;
    padding: 15px;
    background-color: #f0f9ff;
    border-radius: 4px;
    border-left: 4px solid #409eff;
}

.demo-info h3 {
    margin-bottom: 10px;
    color: #409eff;
}

.demo-info ul {
    padding-left: 20px;
}

.demo-info li {
    margin-bottom: 8px;
}

.enhancement-info {
    margin-top: 15px;
    padding: 12px;
    background-color: #f0f9ff;
    border-radius: 4px;
    border: 1px solid #409eff;
}

.enhancement-info h4 {
    color: #409eff;
    margin-bottom: 8px;
}

.role-presets {
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.role-preset-tag {
    cursor: pointer;
    transition: all 0.3s;
}

.role-preset-tag:hover {
    transform: scale(1.05);
}

@media (max-width: 1200px) {
    .preview-container {
        grid-template-columns: 1fr;
        grid-template-rows: auto 1fr auto;
    }

    .page-list {
        max-height: 150px;
        display: flex;
        overflow-x: auto;
    }

    .page-item {
        min-width: 100px;
    }
}
</style>
