<template>
    <div class="document-excel">
        <div class="viewer-container">
            <div id="luckysheet" class="excel-wrapper"></div>
            <div v-if="loading" class="overlay state-panel">
                <i class="el-icon-loading state-icon"></i>
                <p>正在加载 Excel 文档，请稍候...</p>
            </div>
            <div v-else-if="error" class="overlay state-panel">
                <i class="el-icon-warning-outline state-icon"></i>
                <p>{{ error }}</p>
                <el-button type="primary" @click="reload">重新加载</el-button>
            </div>
            <div v-else-if="!excelUrl" class="overlay state-panel">
                <i class="el-icon-document state-icon"></i>
                <p>暂未指定 Excel 文件，请通过路由参数 url 传入文件地址。</p>
            </div>
        </div>
    </div>
</template>

<script>
import 'jquery-mousewheel'
import LuckySheet from 'luckysheet'
import * as XLSX from 'xlsx'
import 'luckysheet/dist/plugins/css/pluginsCss.css'
import 'luckysheet/dist/plugins/plugins.css'
import 'luckysheet/dist/css/luckysheet.css'
import 'luckysheet/dist/assets/iconfont/iconfont.css'

const DEFAULT_EXCEL_URL = 'http://192.168.0.14:9090/smart-bid/technicalSolutionDatabase/2025/11/12/928206a2fdc74c349781f441d9c010f8.xlsx'

export default {
    name: 'DocumentExcel',
    data() {
        return {
            loading: false,
            error: null,
            excelUrl: null,
            workbook: null,
            luckySheetInstance: null
        }
    },
    computed: {
        routeExcelUrl() {
            return this.$route.query.url || this.$route.params.url;
        }
    },
    watch: {
        routeExcelUrl: {
            immediate: true,
            handler(newUrl) {
                if (newUrl) {
                    this.excelUrl = newUrl;
                    this.loadExcel();
                } else {
                    // 如果没有传入URL，使用默认URL
                    this.excelUrl = DEFAULT_EXCEL_URL;
                    this.loadExcel();
                }
            }
        }
    },
    mounted() {
        // 容器元素在模板中始终存在，无需额外初始化
    },
    beforeUnmount() {
        // 组件销毁时清理 LuckySheet 实例
        this.destroyLuckySheet();
    },
    methods: {
        // 加载 Excel 文件
        async loadExcel() {
            if (!this.excelUrl) {
                this.error = 'Excel 文件地址为空';
                return;
            }

            this.loading = true;
            this.error = null;

            try {
                // 获取 Excel 文件
                const response = await fetch(this.excelUrl);
                if (!response.ok) {
                    throw new Error(`文件加载失败: ${response.status} ${response.statusText}`);
                }

                // 转换为 ArrayBuffer
                const arrayBuffer = await response.arrayBuffer();
                
                // 使用 XLSX 解析 Excel 文件
                const workbook = XLSX.read(arrayBuffer, { type: 'array' });
                this.workbook = workbook;

                // 转换为 LuckySheet 需要的格式
                const luckySheetData = this.convertToLuckySheet(workbook);
                
                // 渲染 LuckySheet
                this.renderLuckySheet(luckySheetData);

            } catch (err) {
                console.error('加载 Excel 文件失败:', err);
                this.error = `加载失败: ${err.message}`;
            } finally {
                this.loading = false;
            }
        },

        // 将 XLSX 工作簿转换为 LuckySheet 格式
        convertToLuckySheet(workbook) {
            if (!workbook || !workbook.SheetNames || workbook.SheetNames.length === 0) {
                throw new Error('Excel 文件格式无效或没有工作表');
            }

            const sheets = [];
            
            workbook.SheetNames.forEach((sheetName, index) => {
                const worksheet = workbook.Sheets[sheetName];
                if (!worksheet) {
                    return;
                }

                // 获取工作表数据
                let sheetData = [];
                try {
                    sheetData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });
                } catch (error) {
                    console.error(`读取工作表 ${sheetName} 失败:`, error);
                    sheetData = [];
                }

                if (!Array.isArray(sheetData)) {
                    sheetData = [];
                }

                // 计算行列范围
                const ref = worksheet['!ref'] ? XLSX.utils.decode_range(worksheet['!ref']) : null;
                const rowCount = ref ? ref.e.r + 1 : Math.max(sheetData.length, 36);
                const colCount = ref ? ref.e.c + 1 : Math.max(sheetData[0]?.length || 0, 26);
                
                // 构建单元格数据
                const celldata = [];
                let maxRow = 0;
                let maxCol = 0;

                sheetData.forEach((row, rowIndex) => {
                    if (row && Array.isArray(row)) {
                        maxRow = Math.max(maxRow, rowIndex);
                        row.forEach((cell, colIndex) => {
                            if (cell !== null && cell !== undefined && cell !== '') {
                                maxCol = Math.max(maxCol, colIndex);
                                const cellType = typeof cell === 'number' ? 'n' : 'g';
                                
                                celldata.push({
                                    r: rowIndex,
                                    c: colIndex,
                                    v: {
                                        v: cell,
                                        ct: { fa: 'General', t: cellType },
                                        m: String(cell)
                                    }
                                });
                            }
                        });
                    }
                });

                // 处理合并单元格
                const mergeConfig = {};
                const merges = worksheet['!merges'] || [];
                if (Array.isArray(merges)) {
                    merges.forEach(merge => {
                        if (merge?.s && merge?.e) {
                            const r = merge.s.r;
                            const c = merge.s.c;
                            const rs = merge.e.r - merge.s.r + 1;
                            const cs = merge.e.c - merge.s.c + 1;
                            
                            if (typeof r === 'number' && typeof c === 'number' && 
                                typeof rs === 'number' && typeof cs === 'number' &&
                                rs > 0 && cs > 0) {
                                mergeConfig[`${r}_${c}`] = { r, c, rs, cs };
                            }
                        }
                    });
                }
                
                // 构建 LuckySheet 配置
                const sheetConfig = {
                    name: sheetName,
                    index: index === 0 ? '0' : String(Math.random()),
                    status: index === 0 ? 1 : 0,
                    order: index === 0 ? 0 : 1,
                    row: Math.max(maxRow + 1, 36),
                    column: Math.max(maxCol + 1, 26),
                    celldata: celldata,
                    config: {
                        merge: mergeConfig
                    }
                };
                
                sheets.push(sheetConfig);
            });
            
            if (sheets.length === 0) {
                throw new Error('Excel 文件中没有有效数据');
            }

            return sheets;
        },

        // 渲染 LuckySheet
        renderLuckySheet(sheetData) {
            // 等待 loading 状态更新和 DOM 渲染
            this.$nextTick(() => {
                // 再次等待确保容器元素已渲染
                setTimeout(() => {
                    try {
                        const container = document.getElementById('luckysheet');
                        if (!container) {
                            throw new Error('容器元素不存在');
                        }

                        // 确保容器有尺寸
                        if (container.offsetWidth === 0 || container.offsetHeight === 0) {
                            setTimeout(() => this.renderLuckySheet(sheetData), 100);
                            return;
                        }

                        // 清空容器
                        container.innerHTML = '';

                        // 销毁现有的 LuckySheet 实例
                        if (this.luckySheetInstance) {
                            try {
                                LuckySheet.destroy();
                            } catch (e) {
                                console.warn('销毁旧实例失败:', e);
                            }
                        }

                        // 初始化 LuckySheet - 只保留基础配置
                        this.luckySheetInstance = LuckySheet.create({
                            container: 'luckysheet',
                            data: sheetData,
                            allowEdit: false,
                            showtoolbar: false,
                            showsheetbar: sheetData.length > 1,
                            showstatisticBar: true,
                            enableAddRow: false,
                            enableAddCol: false,
                        });

                        console.log('LuckySheet 初始化成功');

                    } catch (err) {
                        console.error('LuckySheet 渲染失败:', err);
                        this.error = `表格渲染失败: ${err.message}`;
                    }
                }, 200);
            });
        },

        // 重新加载
        reload() {
            this.loadExcel();
        },

        // 销毁 LuckySheet 实例
        destroyLuckySheet() {
            try {
                LuckySheet.destroy();
                this.luckySheetInstance = null;
            } catch (err) {
                console.warn('销毁 LuckySheet 失败:', err);
            }
        },

        // 导出 Excel 文件
        exportExcel() {
            if (!this.luckySheetInstance) {
                this.$message.warning('没有可导出的数据');
                return;
            }

            try {
                // 获取 LuckySheet 数据
                const luckysheetData = LuckySheet.getAllSheets();
                
                // 创建工作簿
                const workbook = XLSX.utils.book_new();
                
                // 遍历所有工作表
                luckysheetData.forEach((sheet) => {
                    // 转换单元格数据为二维数组
                    const maxRow = Math.max(...sheet.celldata.map(cell => cell.r)) + 1;
                    const maxCol = Math.max(...sheet.celldata.map(cell => cell.c)) + 1;
                    
                    const data = [];
                    for (let r = 0; r < maxRow; r++) {
                        const row = [];
                        for (let c = 0; c < maxCol; c++) {
                            const cell = sheet.celldata.find(item => item.r === r && item.c === c);
                            row.push(cell ? cell.v : '');
                        }
                        data.push(row);
                    }
                    
                    // 创建工作表
                    const worksheet = XLSX.utils.aoa_to_sheet(data);
                    
                    // 添加工作表到工作簿
                    XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name);
                });
                
                // 导出文件
                XLSX.writeFile(workbook, 'exported-excel.xlsx');
                this.$message.success('导出成功');
                
            } catch (err) {
                console.error('导出失败:', err);
                this.$message.error('导出失败');
            }
        }
    }
}
</script>

<style scoped>
.document-excel {
    height: 90vh;
    background: #f5f5f5;
}

.viewer-container {
    position: relative;
    height: 100%;
    width: 100%;
}

.overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.state-panel {
    text-align: center;
    padding: 20px;
}

.state-icon {
    font-size: 48px;
    color: #409EFF;
    margin-bottom: 16px;
}

.state-panel p {
    margin: 16px 0;
    color: #606266;
    font-size: 14px;
}

.excel-wrapper {
    height: 100%;
    width: 100%;
    background: white;
}

/* 确保 LuckySheet 样式正确应用 */
:deep(#luckysheet) {
    height: 100% !important;
    width: 100% !important;
}


::v-deep #luckysheet_info_detail{
    display: none !important;
}
</style>