import {useStorage} from "@vueuse/core";

const key = 'PaperStorage'
export const usePaperStorage = function (body) {
    const bodyStr = JSON.stringify(body)
    const paper = useStorage(key, bodyStr)
    paper.value = bodyStr
    return {paper}
}

export const usePaperResolver = function () {
    const paper = useStorage(key, null)
    const paperLocal = ref(paper.value ? JSON.parse(paper.value) : null)
    const groupedQuestions = ref([])
    
    const resolvePaper = function () {
        if (!paperLocal.value || !paperLocal.value.questions) {
            groupedQuestions.value = []
            return
        }
        const results = {}
        paperLocal.value.questions.forEach(q => {
            if (!results[q.qtpye]) results[q.qtpye] = []
            results[q.qtpye].push(q)
        })
        groupedQuestions.value = Object.keys(results).map(g => ({
            title: g,
            list: results[g],
            num: results[g].length,
            score: results[g].reduce((acc, current) => acc + (current.score || 0), 0)
        }))
    }
    
    // 初始化时解析
    resolvePaper()
    
    // 监听 storage 变化，自动更新数据
    watch(paper, (newVal) => {
        if (newVal) {
            try {
                paperLocal.value = JSON.parse(newVal)
                resolvePaper()
            } catch (e) {
                console.error('解析试卷数据失败:', e)
            }
        } else {
            paperLocal.value = null
            groupedQuestions.value = []
        }
    }, { immediate: false })

    const toCommitPaper = function () {
        const questions = []
        groupedQuestions.value.forEach(g => questions.push(...g.list))
        return {
            ...paperLocal.value,
            questions
        }
    }

    return {
        paperLocal, groupedQuestions, resolvePaper, toCommitPaper
    }
}