<template>
    <el-dialog v-model="dialogVisible" :title="title" width="900px" append-to-body>
        <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="120px">
            <!-- 文件预览区域 -->
            <el-form-item v-if="document?.ossId && canPreview" label="文档预览">
                <div class="document-preview">
                    <!-- 切换编辑器按钮和高级选项 -->
                    <div v-if="fileType !== 'pdf'" class="editor-switch">
                        <el-switch
                            v-model="useWpsEditor"
                            active-text="WPS 在线编辑"
                            inactive-text="预览模式"
                        />
                        
                        <!-- WPS 高级选项 -->
                        <el-popover
                            v-if="useWpsEditor"
                            placement="bottom"
                            :width="300"
                            trigger="click"
                        >
                            <template #reference>
                                <el-button size="small" type="primary" link>
                                    <el-icon><Setting /></el-icon>
                                    高级选项
                                </el-button>
                            </template>
                            <div class="wps-options">
                                <el-form label-width="100px" size="small">
                                    <el-form-item label="编辑模式">
                                        <el-radio-group v-model="wpsMode">
                                            <el-radio label="normal">完整模式</el-radio>
                                            <el-radio label="simple">简洁模式</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item label="功能开关">
                                        <el-checkbox v-model="wpsOptions.enableComment">批注</el-checkbox>
                                        <el-checkbox v-model="wpsOptions.enableRevision">修订</el-checkbox>
                                        <el-checkbox v-model="wpsOptions.enableWatermark">水印</el-checkbox>
                                    </el-form-item>
                                    <el-form-item label="权限控制">
                                        <el-checkbox v-model="wpsOptions.enableDownload">下载</el-checkbox>
                                        <el-checkbox v-model="wpsOptions.enablePrint">打印</el-checkbox>
                                        <el-checkbox v-model="wpsOptions.enableCopy">复制</el-checkbox>
                                    </el-form-item>
                                    <el-form-item label="水印文字" v-if="wpsOptions.enableWatermark">
                                        <el-input v-model="wpsOptions.watermarkText" placeholder="输入水印文字" />
                                    </el-form-item>
                                    <el-form-item label="只读模式">
                                        <el-switch v-model="wpsOptions.readOnly" />
                                    </el-form-item>
                                </el-form>
                            </div>
                        </el-popover>
                    </div>

                    <!-- WPS 编辑器（Word/Excel/PPT） -->
                    <WpsEditor
                        v-if="useWpsEditor && fileUrl && fileType !== 'pdf'"
                        :file-url="fileUrl"
                        :file-name="document?.fileName"
                        :file-type="fileType"
                        :mode="wpsMode"
                        :user-id="userStore.userId?.toString()"
                        :user-name="userStore.userName"
                        :enable-comment="wpsOptions.enableComment"
                        :enable-revision="wpsOptions.enableRevision"
                        :enable-watermark="wpsOptions.enableWatermark"
                        :watermark-text="wpsOptions.watermarkText"
                        :enable-download="wpsOptions.enableDownload"
                        :enable-print="wpsOptions.enablePrint"
                        :enable-copy="wpsOptions.enableCopy"
                        :enable-save="wpsOptions.enableSave"
                        :enable-share="wpsOptions.enableShare"
                        :enable-history="wpsOptions.enableHistory"
                        :read-only="wpsOptions.readOnly"
                        @ready="handleWpsReady"
                        @error="handleWpsError"
                        @save="handleWpsSave"
                        @file-change="handleWpsFileChange"
                        style="height: 600px;"
                        ref="wpsEditorRef"
                    />

                    <!-- Word 文档预览 -->
                    <VueOfficeDocx 
                        v-else-if="fileType === 'docx' && fileBlob && !useWpsEditor" 
                        :src="fileBlob" 
                        @rendered="handleRendered"
                        @error="handlePreviewError"
                        style="height: 500px; overflow: auto;"
                    />
                    
                    <!-- Excel 文档预览 -->
                    <VueOfficeExcel 
                        v-else-if="fileType === 'xlsx' && fileBlob && !useWpsEditor" 
                        :src="fileBlob"
                        @rendered="handleRendered"
                        @error="handlePreviewError"
                        style="height: 500px; overflow: auto;"
                    />
                    
                    <!-- PDF 文档预览（支持签名和批注） -->
                    <div v-else-if="fileType === 'pdf' && fileBlob" class="pdf-container" ref="pdfContainerRef">
                        <!-- 工具栏 -->
                        <div class="pdf-toolbar">
                            <el-radio-group v-model="annotationMode" size="small">
                                <el-radio-button label="signature">
                                    <el-icon><Edit /></el-icon>
                                    签名
                                </el-radio-button>
                                <el-radio-button label="text">
                                    <el-icon><ChatLineSquare /></el-icon>
                                    批注
                                </el-radio-button>
                            </el-radio-group>
                            <span class="toolbar-tip">
                                {{ annotationMode === 'signature' ? '点击 PDF 添加签名' : '点击 PDF 添加文字批注' }}
                            </span>
                        </div>
                        
                        <div class="pdf-wrapper" @click="handlePdfClick">
                            <VueOfficePdf 
                                :src="fileBlob"
                                @rendered="handleRendered"
                                @error="handlePreviewError"
                            />
                        </div>
                        
                        <!-- 签名预览层 -->
                        <div 
                            v-for="(signature, index) in signatures" 
                            :key="'sig-' + index"
                            class="signature-preview"
                            :style="{
                                left: signature.x + 'px',
                                top: signature.y + 'px'
                            }"
                            @click.stop="removeSignature(index)"
                        >
                            <img :src="signatureImage" alt="签名" />
                            <el-icon class="remove-icon"><Close /></el-icon>
                        </div>
                        
                        <!-- 批注预览层 -->
                        <div 
                            v-for="(annotation, index) in annotations" 
                            :key="'ann-' + index"
                            class="annotation-preview"
                            :style="{
                                left: annotation.x + 'px',
                                top: annotation.y + 'px'
                            }"
                            @click.stop
                        >
                            <input
                                v-if="annotation.editing"
                                v-model="annotation.text"
                                class="annotation-input"
                                placeholder="输入批注..."
                                @blur="finishAnnotationEdit(index)"
                                @keyup.enter="finishAnnotationEdit(index)"
                            />
                            <div 
                                v-else
                                class="annotation-text"
                                @dblclick="startAnnotationEdit(index)"
                            >
                                {{ annotation.text || '空批注' }}
                            </div>
                            <el-icon class="remove-icon" @click="removeAnnotation(index)"><Close /></el-icon>
                        </div>
                    </div>
                    
                    <!-- 加载中 -->
                    <div v-if="previewLoading" class="preview-loading">
                        <el-icon class="is-loading"><Loading /></el-icon>
                        <span>文档加载中...</span>
                    </div>
                    
                    <!-- 预览失败提示 -->
                    <el-alert 
                        v-if="previewError" 
                        type="error" 
                        :title="previewError" 
                        :closable="false"
                        style="margin-top: 10px;"
                    />
                </div>
            </el-form-item>
            
            <el-form-item :label="t('document.document.auditForm.result')" prop="result">
                <el-radio-group v-model="auditForm.result">
                    <el-radio label="3">{{ t('document.document.auditForm.pass') }}</el-radio>
                    <el-radio label="2">{{ t('document.document.auditForm.reject') }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('document.document.auditForm.reason')" prop="reason"
                v-if="auditForm.result === '2'">
                <el-input v-model="auditForm.reason" type="textarea" :rows="3"
                    :placeholder="t('document.document.auditForm.reasonPlaceholder')" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="loading" type="primary" @click="submitForm">{{
                    t('document.document.button.submit') }}</el-button>
                <el-button @click="handleCancel">{{ t('document.document.button.cancel') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Loading, Close, Edit, ChatLineSquare, Setting } from '@element-plus/icons-vue';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
import request from '@/utils/request';
import WpsEditor from '@/components/WpsEditor/index.vue';
import { useUserStore } from '@/store/modules/user';

interface TextAnnotation {
    x: number;
    y: number;
    text: string;
    editing: boolean;
    timestamp: number;
}

interface Signature {
    x: number;
    y: number;
    pageX: number;
    pageY: number;
    page: number;
}

interface Document {
    id: number | string;
    name?: string;
    ossId?: number | string;
    fileName?: string;
}

interface AuditData {
    documentId: number | string;
    result: number;
    rejectReason?: string;
}

interface Props {
    modelValue: boolean;
    document?: Document | null;
    title?: string;
    auditApi: (data: AuditData) => Promise<any>;
}

interface Emits {
    (e: 'update:modelValue', value: boolean): void;
    (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const { t } = useI18n();
const userStore = useUserStore();

const dialogVisible = ref(false);
const loading = ref(false);
const auditFormRef = ref<FormInstance>();
const previewLoading = ref(false);
const previewError = ref('');
const fileBlob = ref<ArrayBuffer | null>(null);
const fileUrl = ref(''); // 文件 URL，用于 WPS 编辑器
const useWpsEditor = ref(false); // 是否使用 WPS 编辑器
const wpsMode = ref<'simple' | 'normal'>('normal'); // WPS 编辑模式
const wpsEditorRef = ref<InstanceType<typeof WpsEditor>>();
const pdfContainerRef = ref<HTMLDivElement>();
const signatures = ref<Array<{ x: number; y: number; pageX: number; pageY: number; page: number }>>([]);
const annotations = ref<Array<{ x: number; y: number; text: string; page: number; editing: boolean }>>([]);
const annotationMode = ref<'signature' | 'text'>('signature'); // 当前模式：签名或批注

// WPS 高级选项
const wpsOptions = ref({
    enableComment: true,
    enableRevision: true,
    enableWatermark: false,
    watermarkText: '',
    enableDownload: true,
    enablePrint: true,
    enableCopy: true,
    enableSave: true,
    enableShare: false,
    enableHistory: false,
    readOnly: false
});

// 签名 SVG 图片（Base64 编码）
const signatureImage = ref('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNmZmYiIHN0cm9rZT0iIzQwOWVmZiIgc3Ryb2tlLXdpZHRoPSIyIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzQwOWVmZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+562+5ZCNPC90ZXh0Pjwvc3ZnPg==');

const dialogVisible = ref(false);
const loading = ref(false);
const auditFormRef = ref<FormInstance>();
const previewLoading = ref(false);
const previewError = ref('');
const fileBlob = ref<ArrayBuffer | null>(null);
const fileUrl = ref(''); // 文件 URL，用于 WPS 编辑器
const useWpsEditor = ref(false); // 是否使用 WPS 编辑器
const pdfContainerRef = ref<HTMLDivElement>();
const signatures = ref<Array<{ x: number; y: number; pageX: number; pageY: number; page: number }>>([]);
const annotations = ref<Array<{ x: number; y: number; text: string; page: number; editing: boolean }>>([]);
const annotationMode = ref<'signature' | 'text'>('signature'); // 当前模式：签名或批注
// 签名 SVG 图片（Base64 编码）
const signatureImage = ref('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjUwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNmZmYiIHN0cm9rZT0iIzQwOWVmZiIgc3Ryb2tlLXdpZHRoPSIyIi8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzQwOWVmZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZG9taW5hbnQtYmFzZWxpbmU9Im1pZGRsZSI+562+5ZCNPC90ZXh0Pjwvc3ZnPg==');

// 审核表单数据
const auditForm = ref({
    id: 0 as number | string,
    result: '3', // 默认通过
    reason: ''
});

// 获取文件类型
const fileType = computed(() => {
    if (!props.document?.fileName) return '';
    const fileName = props.document.fileName.toLowerCase();
    if (fileName.endsWith('.docx') || fileName.endsWith('.doc')) return 'docx';
    if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) return 'xlsx';
    if (fileName.endsWith('.pdf')) return 'pdf';
    return '';
});

// 判断是否可以预览
const canPreview = computed(() => {
    return ['docx', 'xlsx', 'pdf'].includes(fileType.value);
});

// 审核表单验证规则
const auditRules = reactive({
    result: [
        {
            required: true,
            message: t('document.document.auditRule.resultRequired'),
            trigger: 'change'
        }
    ],
    reason: [
        {
            required: true,
            message: t('document.document.auditRule.reasonRequired'),
            trigger: 'blur'
        }
    ]
});

// 下载文件用于预览
const downloadFileForPreview = async () => {
    if (!props.document?.ossId || !canPreview.value) {
        previewLoading.value = false;
        return;
    }

    try {
        previewLoading.value = true;
        previewError.value = '';
        fileBlob.value = null;
        fileUrl.value = '';
        signatures.value = [];
        annotations.value = [];

        // 构建文件 URL（用于 WPS 编辑器）
        const baseURL = import.meta.env.VITE_APP_BASE_API;
        fileUrl.value = `${baseURL}/resource/oss/downloadWithoutPermission/${props.document.ossId}`;

        // 如果不使用 WPS 编辑器，下载文件用于 vue-office 预览
        if (!useWpsEditor.value) {
            const response = await request({
                url: `/resource/oss/downloadWithoutPermission/${props.document.ossId}`,
                method: 'get',
                responseType: 'arraybuffer'
            });

            fileBlob.value = response;
        }
    } catch (error) {
        console.error('下载文件失败:', error);
        previewError.value = '文件下载失败，无法预览';
        previewLoading.value = false;
    }
};

// WPS 编辑器就绪
const handleWpsReady = () => {
    previewLoading.value = false;
    console.log('WPS 编辑器就绪');
};

// WPS 编辑器保存
const handleWpsSave = (data: any) => {
    console.log('WPS 保存文档:', data);
    ElMessage.success('文档已保存');
};

// WPS 文件变化
const handleWpsFileChange = (data: any) => {
    console.log('WPS 文件变化:', data);
};

// 处理 PDF 点击事件
const handlePdfClick = (event: MouseEvent) => {
    if (!pdfContainerRef.value) return;

    const container = pdfContainerRef.value;
    const rect = container.getBoundingClientRect();
    
    // 计算点击位置相对于容器的坐标
    const x = event.clientX - rect.left + container.scrollLeft;
    const y = event.clientY - rect.top + container.scrollTop;

    if (annotationMode.value === 'signature') {
        // 添加签名
        signatures.value.push({
            x: x - 50, // 签名图片宽度的一半，使其居中
            y: y - 25, // 签名图片高度的一半，使其居中
            pageX: x,
            pageY: y,
            page: 1
        });
        console.log('添加签名:', { x, y });
    } else {
        // 添加批注
        annotations.value.push({
            x: x - 75, // 批注框宽度的一半
            y: y - 20, // 批注框高度的一半
            text: '',
            page: 1,
            editing: true
        });
        // 自动聚焦到新添加的批注输入框
        nextTick(() => {
            const inputs = document.querySelectorAll('.annotation-input');
            const lastInput = inputs[inputs.length - 1] as HTMLInputElement;
            if (lastInput) {
                lastInput.focus();
            }
        });
        console.log('添加批注:', { x, y });
    }
};

// 移除签名
const removeSignature = (index: number) => {
    signatures.value.splice(index, 1);
};

// 移除批注
const removeAnnotation = (index: number) => {
    annotations.value.splice(index, 1);
};

// 完成批注编辑
const finishAnnotationEdit = (index: number) => {
    if (annotations.value[index]) {
        annotations.value[index].editing = false;
    }
};

// 开始编辑批注
const startAnnotationEdit = (index: number) => {
    if (annotations.value[index]) {
        annotations.value[index].editing = true;
        nextTick(() => {
            const inputs = document.querySelectorAll('.annotation-input');
            const input = inputs[index] as HTMLInputElement;
            if (input) {
                input.focus();
            }
        });
    }
};

// 监听modelValue变化
watch(
    () => props.modelValue,
    (val) => {
        dialogVisible.value = val;
        if (val && props.document) {
            auditForm.value = {
                id: props.document.id,
                result: '3', // 默认通过
                reason: ''
            };
            // 重置预览状态
            previewLoading.value = true;
            previewError.value = '';
            fileBlob.value = null;
            // 下载文件用于预览
            downloadFileForPreview();
            // 重置表单验证
            nextTick(() => {
                auditFormRef.value?.clearValidate();
            });
        }
    }
);

// 监听dialogVisible变化
watch(dialogVisible, (val) => {
    emit('update:modelValue', val);
    if (!val) {
        auditForm.value = {
            id: 0,
            result: '3',
            reason: ''
        };
        previewLoading.value = false;
        previewError.value = '';
        fileBlob.value = null;
        fileUrl.value = '';
        signatures.value = [];
        annotations.value = [];
        annotationMode.value = 'signature';
        useWpsEditor.value = false;
    }
});

// 监听 useWpsEditor 变化
watch(useWpsEditor, () => {
    downloadFileForPreview();
});

// 文档渲染完成
const handleRendered = () => {
    previewLoading.value = false;
    console.log('文档渲染完成');
};

// 文档预览错误
const handlePreviewError = (error: any) => {
    previewLoading.value = false;
    previewError.value = '文档预览失败，请尝试下载后查看';
    console.error('文档预览错误:', error);
};

// 取消操作
const handleCancel = () => {
    dialogVisible.value = false;
};

// 提交表单
const submitForm = () => {
    auditFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            loading.value = true;
            try {
                const auditData: AuditData = {
                    documentId: auditForm.value.id,
                    result: parseInt(auditForm.value.result),
                    rejectReason: auditForm.value.reason
                };
                await props.auditApi(auditData);
                ElMessage.success(t('document.document.message.auditSuccess'));
                dialogVisible.value = false;
                emit('success');
            } catch (error) {
                console.error(t('document.document.message.auditFailed'), error);
                ElMessage.error(t('document.document.message.auditFailed'));
            } finally {
                loading.value = false;
            }
        }
    });
};
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.document-preview {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    position: relative;
    
    .editor-switch {
        padding: 10px;
        background: #f5f7fa;
        border-bottom: 1px solid #dcdfe6;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 15px;
    }
    
    .wps-options {
        .el-checkbox {
            display: block;
            margin-bottom: 8px;
        }
    }
    
    .preview-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 500px;
        color: #909399;
        
        .el-icon {
            font-size: 32px;
            margin-bottom: 10px;
        }
    }
}

.pdf-container {
    position: relative;
    width: 100%;
    height: 500px;
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
    
    .pdf-toolbar {
        padding: 10px;
        background: #fff;
        border-bottom: 1px solid #dcdfe6;
        display: flex;
        gap: 15px;
        align-items: center;
        flex-shrink: 0;
        
        .toolbar-tip {
            color: #909399;
            font-size: 13px;
        }
    }
    
    .pdf-wrapper {
        position: relative;
        flex: 1;
        overflow: auto;
        cursor: crosshair;
        
        :deep(canvas) {
            display: block;
            margin: 0 auto;
            background: white;
        }
    }
    
    .annotation-preview {
        position: absolute;
        min-width: 150px;
        background: #fff3cd;
        border: 2px solid #ffc107;
        border-radius: 4px;
        padding: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        cursor: move;
        z-index: 10;
        
        .annotation-input {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 13px;
            outline: none;
            
            &:focus {
                border-color: #409eff;
            }
        }
        
        .annotation-text {
            min-height: 30px;
            padding: 4px 8px;
            cursor: text;
            word-break: break-all;
            white-space: pre-wrap;
            color: #333;
            font-size: 13px;
        }
        
        .remove-icon {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            background: #f56c6c;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
            
            &:hover {
                background: #f78989;
            }
        }
    }
    
    .signature-preview {
        position: absolute;
        width: 100px;
        height: 50px;
        cursor: pointer;
        transition: all 0.3s;
        z-index: 10;
        
        &:hover {
            transform: scale(1.1);
            
            .remove-icon {
                opacity: 1;
            }
        }
        
        img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            border: 2px solid #409eff;
            border-radius: 4px;
            background: rgba(64, 158, 255, 0.1);
        }
        
        .remove-icon {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            background: #f56c6c;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 12px;
        }
    }
}
</style>
