<template>
    <div class="template-management">
        <el-card>
            <template #header>
                <span>合同模板管理</span>
                <el-button type="primary" @click="showUploadDialog" style="float: right">
                    上传模板
                </el-button>
            </template>

            <!-- 模板列表 -->
            <el-table :data="templateList" style="width: 100%">
                <el-table-column prop="name" label="模板名称" />
                <el-table-column prop="fileType" label="文件类型" />
                <el-table-column prop="createdAt" label="上传时间" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link @click="previewTemplate(scope.row)">预览</el-button>
                        <el-button link @click="editSignaturePositions(scope.row)">
                            设置签名位置
                        </el-button>
                        <el-button link @click="deleteTemplate(scope.row)" type="danger">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 上传模板对话框 -->
        <el-dialog v-model="uploadDialogVisible" title="上传合同模板" width="500px">
            <el-upload
                class="upload-demo"
                drag
                :action="uploadUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :limit="1"
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将合同模板拖到此处，或
                    <em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">支持 PDF、Word、Excel 格式文件，且不超过 10MB</div>
                </template>
            </el-upload>

            <template #footer>
                <el-button @click="uploadDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="uploadDialogVisible = false">确定</el-button>
            </template>
        </el-dialog>

        <!-- 设置签名位置对话框 -->
        <el-dialog v-model="positionDialogVisible" title="设置签名位置" width="90%" top="5vh">
            <div class="position-editor">
                <div class="preview-area">
                    <!-- PDF预览 -->
                    <div v-if="currentTemplate.fileType === 'PDF'" class="pdf-preview">
                        <canvas
                            v-for="page in pdfPages"
                            :key="page.pageNum"
                            :ref="
                                el => {
                                    if (el) canvasRefs[page.pageNum] = el;
                                }
                            "
                            class="pdf-page"
                            @click="addSignaturePosition($event, page.pageNum)"
                        ></canvas>
                    </div>

                    <!-- 图片预览 -->
                    <div v-else class="image-preview">
                        <img
                            :src="currentTemplate.previewUrl"
                            alt="模板预览"
                            @click="addSignaturePosition($event, 1)"
                        />
                    </div>
                </div>

                <div class="position-list">
                    <h3>签名位置列表</h3>
                    <el-table :data="signaturePositions" style="width: 100%">
                        <el-table-column prop="name" label="位置名称" />
                        <el-table-column prop="page" label="页码" />
                        <el-table-column label="坐标">
                            <template #default="scope">
                                ({{ scope.row.x }}, {{ scope.row.y }})
                            </template>
                        </el-table-column>
                        <el-table-column label="尺寸">
                            <template #default="scope">
                                {{ scope.row.width }} × {{ scope.row.height }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button link @click="editPosition(scope.row)">编辑</el-button>
                                <el-button link @click="removePosition(scope.row)" type="danger">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="position-actions">
                        <el-button @click="savePositions" type="primary">保存位置</el-button>
                        <el-button @click="positionDialogVisible = false">取消</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 编辑位置对话框 -->
        <el-dialog v-model="editPositionDialogVisible" title="编辑签名位置" width="400px">
            <el-form :model="editingPosition" label-width="80px">
                <el-form-item label="位置名称">
                    <el-input v-model="editingPosition.name" />
                </el-form-item>
                <el-form-item label="X坐标">
                    <el-input-number v-model="editingPosition.x" :min="0" />
                </el-form-item>
                <el-form-item label="Y坐标">
                    <el-input-number v-model="editingPosition.y" :min="0" />
                </el-form-item>
                <el-form-item label="宽度">
                    <el-input-number v-model="editingPosition.width" :min="10" />
                </el-form-item>
                <el-form-item label="高度">
                    <el-input-number v-model="editingPosition.height" :min="10" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="editPositionDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEditedPosition">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="SignaturePoi">
// PDF.js 用于预览PDF
import * as pdfjsLib from 'pdfjs-dist';
pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;

// 模板列表
const templateList = ref([]);
const uploadDialogVisible = ref(false);
const positionDialogVisible = ref(false);
const editPositionDialogVisible = ref(false);
const currentTemplate = ref({});
const pdfPages = ref([]);
const canvasRefs = ref({});
const signaturePositions = ref([]);
const editingPosition = ref({});

// 上传配置
const uploadUrl = 'http://your-server.com/api/template/upload';
const headers = {
    Authorization: 'Bearer ' + localStorage.getItem('token'),
};

onMounted(() => {
    loadTemplates();
});

// 加载模板列表
const loadTemplates = async () => {
    try {
        // 调用API获取模板列表
        // const response = await templateApi.getList()
        // templateList.value = response.data

        // 模拟数据
        templateList.value = [
            {
                id: 1,
                name: '劳动合同模板',
                fileType: 'PDF',
                fileUrl: 'http://example.com/template1.pdf',
                previewUrl: 'http://example.com/template1-preview.jpg',
                createdAt: '2023-06-01',
            },
            {
                id: 2,
                name: '合作协议模板',
                fileType: 'DOCX',
                fileUrl: 'http://example.com/template2.docx',
                previewUrl: 'http://example.com/template2-preview.jpg',
                createdAt: '2023-06-02',
            },
        ];
    } catch (error) {
        ElMessage.error('加载模板列表失败');
    }
};

// 显示上传对话框
const showUploadDialog = () => {
    uploadDialogVisible.value = true;
};

// 上传前验证
const beforeUpload = file => {
    const isPDF = file.type === 'application/pdf';
    const isWord =
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    const isLt10M = file.size / 1024 / 1024 < 10;

    if (!isPDF && !isWord && !isExcel) {
        ElMessage.error('只能上传PDF、Word或Excel文件!');
        return false;
    }
    if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB!');
        return false;
    }
    return true;
};

// 上传成功处理
const handleUploadSuccess = response => {
    ElMessage.success('模板上传成功');
    loadTemplates();
};

// 预览模板
const previewTemplate = template => {
    window.open(template.fileUrl, '_blank');
};

// 设置签名位置
const editSignaturePositions = async template => {
    currentTemplate.value = template;
    signaturePositions.value = template.signaturePositions || [];

    if (template.fileType === 'PDF') {
        await loadPDFForPositioning(template.fileUrl);
    }

    positionDialogVisible.value = true;
};

// 加载PDF用于设置位置
const loadPDFForPositioning = async pdfUrl => {
    try {
        const loadingTask = pdfjsLib.getDocument(pdfUrl);
        const pdf = await loadingTask.promise;
        pdfPages.value = [];

        for (let i = 1; i <= pdf.numPages; i++) {
            pdfPages.value.push({
                pageNum: i,
                pdf: pdf,
                scale: 1.5,
            });
        }

        // 等待DOM更新后渲染PDF
        await nextTick();
        renderPDFPages();
    } catch (error) {
        ElMessage.error('PDF加载失败: ' + error.message);
    }
};

// 渲染PDF页面
const renderPDFPages = async () => {
    for (const pageInfo of pdfPages.value) {
        const page = await pageInfo.pdf.getPage(pageInfo.pageNum);
        const canvas = canvasRefs.value[pageInfo.pageNum];
        const context = canvas.getContext('2d');

        const viewport = page.getViewport({ scale: pageInfo.scale });
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {
            canvasContext: context,
            viewport: viewport,
        };

        await page.render(renderContext).promise;
    }
};

// 添加签名位置
const addSignaturePosition = (event, pageNum) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const x = event.offsetX;
    const y = event.offsetY;

    // 默认签名区域大小
    const width = 120;
    const height = 60;

    const newPosition = {
        id: Date.now(),
        name: `签名位置${signaturePositions.value.length + 1}`,
        page: pageNum,
        x: x,
        y: y,
        width: width,
        height: height,
    };

    signaturePositions.value.push(newPosition);

    // 在画布上绘制矩形框标记位置
    drawPositionMarker(event.currentTarget, newPosition);
};

// 在画布上绘制位置标记
const drawPositionMarker = (canvas, position) => {
    const ctx = canvas.getContext('2d');
    ctx.strokeStyle = '#ff0000';
    ctx.lineWidth = 2;
    ctx.strokeRect(position.x, position.y, position.width, position.height);

    ctx.fillStyle = 'rgba(255, 0, 0, 0.1)';
    ctx.fillRect(position.x, position.y, position.width, position.height);

    ctx.fillStyle = '#ff0000';
    ctx.font = '12px Arial';
    ctx.fillText(position.name, position.x, position.y - 5);
};

// 编辑位置
const editPosition = position => {
    editingPosition.value = { ...position };
    editPositionDialogVisible.value = true;
};

// 保存编辑后的位置
const saveEditedPosition = () => {
    const index = signaturePositions.value.findIndex(p => p.id === editingPosition.value.id);
    if (index !== -1) {
        signaturePositions.value[index] = { ...editingPosition.value };
    }
    editPositionDialogVisible.value = false;
    ElMessage.success('位置更新成功');
};

// 删除位置
const removePosition = position => {
    const index = signaturePositions.value.findIndex(p => p.id === position.id);
    if (index !== -1) {
        signaturePositions.value.splice(index, 1);
        ElMessage.success('位置删除成功');
    }
};

// 保存所有位置到服务器
const savePositions = async () => {
    try {
        // 调用API保存签名位置
        // await templateApi.saveSignaturePositions(currentTemplate.value.id, signaturePositions.value)

        ElMessage.success('签名位置保存成功');
        positionDialogVisible.value = false;
    } catch (error) {
        ElMessage.error('保存失败: ' + error.message);
    }
};

// 删除模板
const deleteTemplate = async template => {
    try {
        await ElMessageBox.confirm(`确定要删除模板"${template.name}"吗？此操作不可恢复。`, '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });

        // 调用API删除模板
        // await templateApi.delete(template.id)

        ElMessage.success('模板删除成功');
        loadTemplates();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + error.message);
        }
    }
};
</script>

<style scoped>
.position-editor {
    display: flex;
    gap: 20px;
    height: 70vh;
}

.preview-area {
    flex: 1;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    padding: 10px;
    overflow: auto;
}

.pdf-preview {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.pdf-page {
    border: 1px solid #e0e0e0;
    cursor: crosshair;
}

.image-preview img {
    max-width: 100%;
    cursor: crosshair;
}

.position-list {
    width: 400px;
    display: flex;
    flex-direction: column;
}

.position-actions {
    margin-top: auto;
    padding-top: 20px;
    text-align: right;
}
</style>
