import { toValue } from "vue";
import { downloadPaper } from "@/api/dz/papers.js";
import { ElMessage } from "element-plus";
import { saveAs } from "file-saver";
import { blobValidate } from "@/utils/ruoyi";

/**
 * 试卷下载通用 hook
 * @param {ComputedRef|Ref} queryParams - 查询参数
 * @returns {Function} handleDownload - 下载处理函数
 */
export function usePaperDownload(queryParams) {
    /**
     * 处理下载
     * @param {Number|String} paperId - 试卷ID（可选，如果不传则从queryParams中获取）
     * @param {String} paperName - 试卷名称（可选，用于生成文件名）
     */
    const handleDownload = async (paperId, paperName) => {
        try {
            // 如果没有传入paperId，尝试从queryParams中获取
            if (!paperId && queryParams) {
                const params = toValue(queryParams)
                paperId = params.paperId
                paperName = paperName || params.paperName
            }
            
            if (!paperId) {
                ElMessage.error('试卷ID不存在')
                return
            }
            
            const response = await downloadPaper({ paperId })
            
            // 检查响应是否为 blob
            if (blobValidate(response)) {
                const blob = new Blob([response])
                // 生成文件名，使用paperName或默认名称
                const filename = paperName 
                    ? `${paperName}_${Date.now()}.docx`
                    : `试卷_${Date.now()}.docx`
                saveAs(blob, filename)
                ElMessage.success('下载成功')
            } else {
                // 如果不是 blob，尝试解析错误信息
                if (response instanceof Blob) {
                    const text = await response.text()
                    try {
                        const errorObj = JSON.parse(text)
                        ElMessage.error(errorObj.msg || errorObj.message || '下载失败')
                    } catch (e) {
                        ElMessage.error('下载失败')
                    }
                } else if (response && response.msg) {
                    ElMessage.error(response.msg || '下载失败')
                } else {
                    ElMessage.error('下载失败')
                }
            }
        } catch (error) {
            console.error('下载失败:', error)
            const errorMsg = error?.response?.data?.msg || error?.message || '下载失败，请稍后重试'
            ElMessage.error(errorMsg)
        }
    }

    return {
        handleDownload
    }
}

