import { buildExportBaseName, type ExportFileNameOptions } from '@/utils/echartMethod'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import { exportExcel } from '@/views/system/reportForms/export.js'

/** 解析 Luckysheet 接口返回的 sheet 数据 */
export function parseLuckysheetSheets(sheets: any[]) {
    sheets.forEach((item: any) => {
        if (item.data1) {
            try {
                item.data = JSON.parse(item.data1)
            } catch {
                /* ignore invalid json */
            }
        }
        if (!item.config) item.config = {}
        if (item.row == null) item.row = 36
        if (item.column == null) item.column = 18
        if (!item.data) item.data = []
        item.celldata?.forEach((cell: any) => {
            if (item.data?.[cell.r]?.[cell.c]?.v != null) {
                item.data[cell.r][cell.c] = cell.v
            }
        })
    })
}

declare const luckysheet: any

const DEFAULT_REPORT_OPTIONS = {
    title: '',
    lang: 'zh',
    showtoolbar: false,
    showinfobar: false,
    showsheetbar: true,
}

/** 销毁已有 Luckysheet 实例，避免重复 create 导致 DOM 堆积 */
export function destroyLuckysheet() {
    try {
        if (typeof luckysheet !== 'undefined' && luckysheet.destroy) {
            luckysheet.destroy()
        }
    } catch {
        /* ignore */
    }
}

/** 解析 sheet 数据、销毁旧实例并渲染报表 */
export function renderLuckysheetReport(
    container: string,
    sheets: any[],
    options: Record<string, any> = {}
) {
    if (!Array.isArray(sheets) || sheets.length === 0) {
        destroyLuckysheet()
        return
    }
    parseLuckysheetSheets(sheets)
    destroyLuckysheet()
    nextTick(() => {
        requestAnimationFrame(() => {
            if (!document.getElementById(container)) return
            luckysheet.create({
                container,
                ...DEFAULT_REPORT_OPTIONS,
                ...options,
                data: sheets,
            })
        })
    })
}

/** 安全导出 Luckysheet，无数据时提示并返回 false */
export function exportLuckysheetFile(filenameOrOptions: string | ExportFileNameOptions, hasData = true): boolean {
    if (!hasData) {
        ElMessage.warning('暂无数据')
        return false
    }
    try {
        if (typeof luckysheet === 'undefined' || !luckysheet.getAllSheets) {
            ElMessage.warning('暂无数据')
            return false
        }
        const sheets = luckysheet.getAllSheets()
        if (!sheets?.length) {
            ElMessage.warning('暂无数据')
            return false
        }
        const filename =
            typeof filenameOrOptions === 'string' ? filenameOrOptions : buildExportBaseName(filenameOrOptions)
        exportExcel(sheets, filename)
        ElMessage.success('生成成功')
        return true
    } catch {
        ElMessage.warning('导出失败，请先加载报表数据')
        return false
    }
}
