<template>
    <home-container title="文档详情" :customStyle="{backgroundPosition:'0px -65px'}">
        <view class="doc-detail-container">
            <!-- 文档信息部分 -->
            <view class="doc-info">
                <text class="doc-title">{{ documentInfo.documentTitle || '文档标题' }}</text>
                <view class="doc-meta">
                    <text class="meta-item">创建人：{{ documentInfo.createBy || '管理员' }}</text>
                    <text class="meta-item">创建时间：{{ formatDate(documentInfo.createTime) }}</text>
                </view>
            </view>

            <!-- 文件预览容器 -->
            <view class="preview-container" v-if="loading">
                <view class="loading-indicator">
                    <text>正在加载文档...</text>
                </view>
            </view>

            <view class="preview-container" v-else-if="documentInfo.documentUrl">
                <!-- 只预览PDF格式文件 -->
                <view v-if="isPdfFile" class="pdf-viewer">
                    <!-- App端：blob URL预览方案 -->
                    <view v-if="isApp" class="app-pdf-viewer">
                        <view class="pdf-notice">
                            <text class="pdf-tip">PDF文件预览</text>
                            <text class="pdf-tip">点击下方按钮下载并预览PDF文件</text>
                        </view>
                        <button class="open-pdf-btn" @tap="downloadAndGenerateBlobUrl" :disabled="isDownloading">
                            {{ isDownloading ? '正在下载...' : '下载并预览PDF' }}
                        </button>
                        <view v-if="pdfLoadError" class="error-notice">
                            <text>PDF加载失败，请重试</text>
                        </view>
                        
                        <!-- blob URL预览区域 -->
                        <view v-if="localPdfUrl && !pdfLoading" class="blob-preview-area">
                            <web-view 
                                :src="localPdfUrl" 
                                :key="webViewKey"
                                @message="handleWebViewMessage"
                                @load="handleWebViewLoad"
                                @error="handleWebViewError">
                            </web-view>
                        </view>
                        
                        <!-- 加载遮罩层 -->
                        <view v-if="pdfLoading" class="pdf-loading-mask">
                            <view class="loading-content">
                                <text class="loading-text">PDF加载中...</text>
                                <button class="reload-btn" @tap="downloadAndGenerateBlobUrl">重新加载</button>
                            </view>
                        </view>
                    </view>
                    
                    <!-- H5端：web-view预览方案 -->
                    <view v-else class="web-pdf-viewer">
                        <web-view 
                            :src="getPdfViewUrl()" 
                            :key="webViewKey"
                            @message="handleWebViewMessage"
                            @load="handleWebViewLoad"
                            @error="handleWebViewError">
                        </web-view>
                        <!-- 加载遮罩层 -->
                        <view v-if="pdfLoading" class="pdf-loading-mask">
                            <view class="loading-content">
                                <text class="loading-text">PDF加载中...</text>
                                <button v-if="isApp" class="reload-btn" @tap="reloadWebView">重新加载</button>
                            </view>
                        </view>
                    </view>
                </view>
                <view v-else class="file-viewer">
                    <!-- 非PDF文件，提示用户 -->
                    <view class="file-notice">
                        <text>仅支持PDF格式文件预览</text>
                        <button class="download-btn" @click="downloadFile">下载文件</button>
                    </view>
                </view>
            </view>

            <view class="preview-container" v-else>
                <view class="file-notice">
                    <text>暂无文件信息</text>
                </view>
            </view>
        </view>
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import { getWorkDocu } from "@/api/workDocu/workDocu.js";
import config from '@/config';
export default {
    components: {
        HomeContainer
    },
    data() {
        return {
            documentInfo: {
                docTitle: '',
                createUser: '',
                createTime: '',
                documentUrl: '',
                fileType: ''
            },
            loading: true,
            docId: '',
            pdfLoading: true,
            baseUrl: config.baseUrl,
            isApp: false, // 是否为App环境
            webViewKey: 0, // web-view强制刷新key
            pdfLoadError: false, // PDF加载错误状态
            localPdfUrl: '', // 本地PDF文件URL
            isDownloading: false // 是否正在下载
        };
    },
    computed: {
        // 判断是否为PDF文件
        isPdfFile() {
            return this.documentInfo.fileType === 'pdf' ||
                (this.documentInfo.documentUrl && this.documentInfo.documentUrl.toLowerCase().endsWith('.pdf'));
        }
    },
    onLoad(options) {
        // 从路由参数中获取文档ID
        if (options && options.id) {
            this.docId = options.id;
            this.fetchDocumentDetail();
        }
        
     
    },
    methods: {
        
        // 确保URL以斜杠结尾
        ensureTrailingSlash(url) {
            return url.endsWith('/') ? url : url + '/';
        },
        
        formatDate(timeString) {
            if (!timeString) return '';
            const date = new Date(timeString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        // 获取文档详情
        async fetchDocumentDetail() {
            this.loading = true;
            try {
                // 调用真实的API获取文档详情
                const response = await getWorkDocu(this.docId);

                // 根据实际API返回的数据结构进行处理
                // 注意字段映射：documentTitle替代docTitle，createBy替代createUser
                this.documentInfo = response.data;
             
                
            } catch (error) {
                console.error('获取文档详情失败:', error);
                uni.showToast({
                    title: '加载文档失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
                // 文档加载完成后，设置PDF加载状态
                if (this.isPdfFile && this.documentInfo.documentUrl) {
                    // 延迟一段时间隐藏加载提示
                    setTimeout(() => {
                        this.pdfLoading = false;
                    }, 2000);
                }
            }
        },
        
        // 处理web-view消息
        handleWebViewMessage(e) {
            console.log('web-view message:', e);
            this.pdfLoading = false;
        },

        // 下载文件
        downloadFile() {
            if (!this.documentInfo.documentUrl) return;

            uni.showModal({
                title: '提示',
                content: '确定要下载此文件吗？',
                success: (res) => {
                    if (res.confirm) {
                        // 使用uni-app的下载API
                        uni.downloadFile({
                            url: this.documentInfo.documentUrl,
                            success: (downloadResult) => {
                                if (downloadResult.statusCode === 200) {
                                    // 保存文件到本地
                                    uni.saveFile({
                                        tempFilePath: downloadResult.tempFilePath,
                                        success: (saveResult) => {
                                            uni.showToast({
                                                title: '下载成功',
                                                icon: 'success'
                                            });
                                            // 提示用户打开文件
                                            uni.showModal({
                                                title: '下载成功',
                                                content: '文件已下载完成，是否打开？',
                                                success: (openRes) => {
                                                    if (openRes.confirm) {
                                                        // 打开下载的文件
                                                        uni.openDocument({
                                                            filePath: saveResult.savedFilePath,
                                                            showMenu: true,
                                                            success: () => {
                                                                console.log('打开文档成功');
                                                            },
                                                            fail: (error) => {
                                                                console.error('打开文档失败:', error);
                                                                uni.showToast({
                                                                    title: '打开失败，请手动打开',
                                                                    icon: 'none'
                                                                });
                                                            }
                                                        });
                                                    }
                                                }
                                            });
                                        },
                                        fail: (error) => {
                                            console.error('保存文件失败:', error);
                                            uni.showToast({
                                                title: '保存失败',
                                                icon: 'none'
                                            });
                                        }
                                    });
                                }
                            },
                            fail: (error) => {
                                console.error('下载文件失败:', error);
                                uni.showToast({
                                    title: '下载失败',
                                    icon: 'none'
                                });
                            }
                        });
                    }
                }
            });
        },

        // 下载文件并生成blob URL（App端专用）
        async downloadAndGenerateBlobUrl() {
            if (!this.documentInfo.documentUrl) {
                uni.showToast({
                    title: '文件链接无效',
                    icon: 'none'
                });
                return;
            }
            
            // 如果正在下载，直接返回
            if (this.isDownloading) {
                return;
            }
            
            this.isDownloading = true;
            this.pdfLoading = true;
            
            // 显示加载提示
            uni.showLoading({
                title: '正在下载PDF...',
                mask: true
            });
            
            try {
                // 下载文件到本地
                const downloadResult = await new Promise((resolve, reject) => {
                    uni.downloadFile({
                        url: this.documentInfo.documentUrl,
                        success: resolve,
                        fail: reject
                    });
                });
                
                if (downloadResult.statusCode === 200) {
                    // 读取文件内容并生成blob URL
                    const fileData = await this.readFileAsArrayBuffer(downloadResult.tempFilePath);
                    const blob = new Blob([fileData], { type: 'application/pdf' });
                    const blobUrl = URL.createObjectURL(blob);
                    
                    // 保存blob URL
                    this.localPdfUrl = blobUrl;
                    
                    uni.hideLoading();
                    uni.showToast({
                        title: 'PDF加载成功',
                        icon: 'success'
                    });
                    
                    // 强制刷新web-view
                    this.webViewKey++;
                    this.pdfLoading = false;
                    
                } else {
                    throw new Error(`下载失败，状态码: ${downloadResult.statusCode}`);
                }
            } catch (error) {
                console.error('下载生成blob URL失败:', error);
                uni.hideLoading();
                
                uni.showToast({
                    title: 'PDF加载失败，请重试',
                    icon: 'none'
                });
                
                // 标记加载错误状态
                this.pdfLoadError = true;
                this.pdfLoading = false;
            } finally {
                this.isDownloading = false;
            }
        },
        
        // 读取文件为ArrayBuffer
        readFileAsArrayBuffer(filePath) {
            return new Promise((resolve, reject) => {
                if (typeof plus !== 'undefined') {
                    // App端使用plus.io读取文件
                    plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
                        entry.file((file) => {
                            const fileReader = new plus.io.FileReader();
                            fileReader.onload = (e) => {
                                resolve(e.target.result);
                            };
                            fileReader.onerror = reject;
                            fileReader.readAsArrayBuffer(file);
                        }, reject);
                    }, reject);
                } else {
                    // H5端使用XMLHttpRequest
                    const xhr = new XMLHttpRequest();
                    xhr.open('GET', filePath, true);
                    xhr.responseType = 'arraybuffer';
                    xhr.onload = () => {
                        if (xhr.status === 200) {
                            resolve(xhr.response);
                        } else {
                            reject(new Error(`读取文件失败: ${xhr.status}`));
                        }
                    };
                    xhr.onerror = reject;
                    xhr.send();
                }
            });
        },
        
        // 获取PDF预览URL
        getPdfViewUrl() {
            // 如果已经有本地blob URL，优先使用
            if (this.localPdfUrl) {
                return this.localPdfUrl;
            }
            // 否则使用原始URL
            return this.documentInfo.documentUrl;
        }
    }
};
</script>

<style lang="scss" scoped>
.doc-detail-container {
    margin-top: 40rpx;
    padding: 30rpx;
    border-radius: 16rpx;
    background-color: #ffffff;
    min-height: calc(100vh - 177rpx);

    // 文档信息样式
    .doc-info {
        margin-bottom: 40rpx;
        border-bottom: 1rpx solid #eeeeee;
        padding-bottom: 30rpx;
        background-color: #fafafa;
        padding: 30rpx;
        border-radius: 10rpx;

        .doc-title {
            font-size: 36rpx;
            font-weight: bold;
            color: #333333;
            display: block;
            margin-bottom: 25rpx;
            line-height: 1.6;
            word-break: break-word;
        }

        .doc-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 40rpx;

            .meta-item {
                font-size: 26rpx;
                color: #666666;
                display: flex;
                align-items: center;
            }
            
        }
    }

    // 预览容器样式
    .preview-container {
        background-color: #f8f8f8;
        border-radius: 10rpx;
        overflow: hidden;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

        .pdf-viewer {
            width: 100%;
            height: calc(100vh - 400rpx);
            background-color: #ffffff;
            position: relative;
        }
        
        // 加载遮罩层
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10;
        }
        
        .loading-text {
            color: #666666;
            font-size: 32rpx;
            padding: 20rpx;
            background-color: white;
            border-radius: 8rpx;
            box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
        }

        // 加载状态样式
        .loading-indicator {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200rpx;
            color: #666666;
            font-size: 28rpx;
        }

        // 文件提示样式
        .file-notice {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 200rpx;
            color: #999999;
            font-size: 28rpx;

            .download-btn {
                margin-top: 30rpx;
                background-color: #007aff;
                color: #ffffff;
            }
        }
        
        .error-notice {
            margin-top: 20rpx;
            padding: 20rpx;
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            border-radius: 8rpx;
            text-align: center;
        }
        .error-notice text {
            color: #a8071a;
            font-size: 28rpx;
        }
        
        .blob-preview-area {
            margin-top: 30rpx;
            border: 1px solid #e8e8e8;
            border-radius: 8rpx;
            overflow: hidden;
            height: 600rpx;
        }
        .blob-preview-area web-view {
            width: 100%;
            height: 100%;
        }
    }
}
</style>