import {useInjectPaperExactCondition} from "@/views/dz/papers/hooks/usePaperExactCondition.js";
import {useInjectPaperFullCondition} from "@/views/dz/papers/hooks/usePaperFullCondition.js";
import {injectLocal, provideLocal} from "@vueuse/core";
import {useInjectLoading} from "@/views/hooks/useLoading.js";
import {getPaperQuestions, getPaperQuestionTypes} from "@/api/dz/papers.js";
import {ElMessage} from "element-plus";

const key = Symbol('PaperQuestionCondition')

export const useProvidePaperQuestionCondition = function (exactMode, allowMultiple, disableQuestionQuery = false) {
    // exactMode: exact condition & full condition
    // allowMultiple: multiple knowledge selection

    const keyword = ref('')
    const qtpye = ref('') // 历史遗留拼写错误
    const qTypes = ref([])

    const pageNum = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const questionList = ref([])

    const {
        subjectId, subjects, knowledgeId, knowledgeIds
    } = exactMode ? useInjectPaperExactCondition() : useInjectPaperFullCondition()
    const loading = useInjectLoading()

    // question cart
    const cart = ref([])
    const currentSubject = computed(() => {
        const demoId = cart.value[0]?.subjectId
        return subjects.value.find(s => s.subjectId == demoId)
    })
    const groupedQuestions = computed(() => {
        const results = {}
        cart.value.forEach(q => {
            if (!results[q.qtpye]) {
                results[q.qtpye] = []
            }
            results[q.qtpye].push(q)
        })
        return Object.keys(results).map(k => ({qtpye: k, questions: results[k]}))
    })
    const hasQuestion = (q) => {
        return cart.value.some(c => c.id == q.id)
    }
    const removeQuestion = (q) => {
        const idx = cart.value.findIndex(c => c.id == q.id)
        if (idx > -1) cart.value.splice(idx, 1)
    }
    const addQuestion = (q) => {
        if (currentSubject.value && currentSubject.value.subjectId != q.subjectId) {
            return ElMessage.error(`当前科目【${currentSubject.value.subjectName}】冲突`)
        }
        cart.value.push(q)
    }
    const removeQuestionGroup = (qtpye) => {
        const ls = groupedQuestions.value.find(g => g.qtpye == qtpye)?.questions
        ls?.forEach(q => removeQuestion(q))
    }
    const clearCart = () => cart.value = []

    // hooks
    watch([subjectId, knowledgeId, () => knowledgeIds.value.toString()], async ([subjectId, knowledgeId, knowledgeIds]) => {
        // clean
        qtpye.value = ''
        qTypes.value = []

        if (!subjectId) return
        if (!knowledgeId && !knowledgeIds) return
        const query = {subjectId, knowledgeIds: knowledgeId || knowledgeIds}
        const res = await getPaperQuestionTypes(query)
        qTypes.value = res.data
    })

    const questionQuery = computed(() => ({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        title: keyword.value,
        qtpye: qtpye.value,
        knowledgeId: knowledgeId.value,
        knowledges: knowledgeIds.value.toString()
    }))
    const getQuestionList = async function () {
        if (disableQuestionQuery) return // 智能组卷时不需要查询
        loading.value = true
        try {
            const res = await getPaperQuestions(questionQuery.value)
            total.value = res.total
            questionList.value = res.rows
        } finally {
            loading.value = false
        }
    }
    watch([keyword, qtpye, knowledgeId, () => knowledgeIds.value.toString()], async ([title, qtpye, knowledgeId, knowledges]) => {
        pageNum.value = 1
        questionList.value = []
        total.value = 0

        if (!knowledgeId && !knowledges) return // 有知识点即可以查询题库
        await getQuestionList(pageNum.value, pageSize.value)
    })

    const payload = {
        keyword, qtpye, qTypes, pageNum, pageSize, total, questionList, getQuestionList,
        cart, currentSubject, groupedQuestions,
        hasQuestion, addQuestion, removeQuestion, removeQuestionGroup, clearCart
    }
    provideLocal(key, payload)
    return payload
}

export const useInjectPaperQuestionCondition = function () {
    return injectLocal(key)
}