<template>
    <div v-loading="questionLoading" element-loading-text="加载试题中...">
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form label-width="68px">
                    <el-form-item label="批次">
                        <el-select v-model="batchId" clearable style="width: 227px">
                            <el-option v-for="b in batchList" :label="b.name" :value="b.batchId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="考生类型">
                        <el-select v-model="examType" clearable style="width: 227px">
                            <el-option v-for="e in examTypes" :label="e.dictLabel" :value="e.dictValue"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="院校">
                        <el-select v-model="universityId" clearable style="width: 227px">
                            <el-option v-for="u in universities" :label="u.name" :value="u.id"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专业组">
                        <el-select v-model="majorGroup" clearable style="width: 227px">
                            <el-option v-for="g in majorGroups" :label="g" :value="g"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专业">
                        <el-select v-model="majorPlanId" clearable style="width: 227px">
                            <el-option v-for="m in majors" :label="m.majorName" :value="m.id"/>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="16">
                <class-statistic-table exact-mode hand-mode @stat-click="handleStatClick"/>
            </el-col>
        </el-row>
        <el-divider/>
        <el-row v-if="!hasBuiltPaper" :gutter="20">
            <el-col :span="6">
                <knowledge-tree/>
            </el-col>
            <el-col :span="18">
                <question-hand exact-mode @submit="handleSubmit"/>
            </el-col>
        </el-row>
        <built-paper-list ref="built" @send="handleSubmit" />
        
        <!-- 学生列表弹窗 -->
        <student-list-dialog ref="studentDialogRef" :stat-type-map="statTypeMap"/>
    </div>
</template>

<script setup name="PaperExactHand">

import consts from "@/utils/consts.js";
import {useProvidePaperExactCondition} from "@/views/dz/papers/hooks/usePaperExactCondition.js";
import {useProvidePaperClassStatisticCondition} from "@/views/dz/papers/hooks/usePaperClassStatisticCondition.js";
import {useProvidePaperKnowledgeCondition} from "@/views/dz/papers/hooks/usePaperKnowledgeCondition.js";
import ClassStatisticTable from "@/views/dz/papers/components/plugs/class-statistic-table.vue";
import KnowledgeTree from "@/views/dz/papers/components/plugs/knowledge-tree.vue";
import QuestionHand from "@/views/dz/papers/components/plugs/question-hand.vue";
import {usePaperStorage} from "@/views/dz/papers/hooks/usePaperStorage.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import BuiltPaperList from "@/views/dz/papers/components/plugs/built-paper-list.vue";
import StudentListDialog from "@/views/dz/papers/components/plugs/student-list-dialog.vue";
import {useInjectGlobalLoading} from "@/views/hooks/useGlobalLoading.js";

const type = consts.enums.buildType.ExactHand
const {
    batchId, batchList,
    examType, examTypes,
    universityId, universities,
    majorGroup, majorGroups,
    majors, majorPlanId,
    conditionArgs, onConditionReady
} = useProvidePaperExactCondition(type)
const {selectedClasses, classList, loadClassStatistic} = useProvidePaperClassStatisticCondition()
const {knowledgeNode, knowledgeCheckNodes, loadKnowledge} = useProvidePaperKnowledgeCondition()
const {loading: globalLoading} = useInjectGlobalLoading()
const questionLoading = computed(() => globalLoading.value)
const built = ref(null)
const hasBuiltPaper = computed(() => built.value?.hasPaper)

// 统计字段映射
const statTypeMap = {
    'send': '组卷已完成',
    'total': '专业人数',
    'unexact': '未定向未组卷',
    'unfinish': '组卷未完成',
    'unsend': '定向未组卷'
}

// 学生列表弹窗引用
const studentDialogRef = ref(null)

// 处理统计字段点击
const handleStatClick = async (row, statType) => {
    if (!row || !statType || !batchId.value) {
        console.error('参数错误:', { row, statType, batchId: batchId.value })
        return
    }
    
    // 构建查询条件参数
    const queryParams = {}
    if (conditionArgs.value) {
        if (conditionArgs.value.examType) queryParams.examType = conditionArgs.value.examType
        if (conditionArgs.value.universityId) queryParams.universityId = conditionArgs.value.universityId
        if (conditionArgs.value.majorGroup) queryParams.majorGroup = conditionArgs.value.majorGroup
        if (conditionArgs.value.majorPlanId) queryParams.majorPlanId = conditionArgs.value.majorPlanId
    }
    
    // 打开学生列表弹窗
    studentDialogRef.value?.open(row, statType, type, batchId.value, queryParams)
}

const handleSubmit = async (questions) => {
    // 如果 questions 未定义，说明是从已生成试卷触发的，不需要处理
    if (!questions) return
    
    // validation
    if (!batchId.value) return ElMessage.error('请选择批次')
    if (!examType.value) return ElMessage.error('请选择考生类型')
    if (!universityId.value) return ElMessage.error('请选择院校')
    if (majorGroups.value.length && !majorGroup.value) return ElMessage.error('请选择专业组')
    if (majors.value.length && !majorPlanId.value) return ElMessage.error('请选择专业')
    const classIds = selectedClasses.value.map(c => c.classId)
    if (!classIds.length) return ElMessage.error('请选择班级')
    if (!questions.length) return ElMessage.error('请将试题加入试题篮')

    const paper = {
        buildType: type,
        batchId: toValue(batchId),
        examType: toValue(examType),
        universityId: toValue(universityId),
        majorGroup: toValue(majorGroup),
        majorPlanId: toValue(majorPlanId),
        classIds,
        questions
    }
    usePaperStorage(paper)
    // 检查当前路由，避免冗余导航
    if (router.currentRoute.value.name !== 'PaperDetail') {
        await router.push({name: 'PaperDetail'})
    } else {
        // 如果已经在详情页，添加时间戳参数强制刷新
        await router.replace({
            name: 'PaperDetail',
            query: { _t: Date.now() }
        })
    }
}

let statArg = null
const _loadClassStatistic = async () => {
    selectedClasses.value = []
    classList.value = []

    await loadClassStatistic(statArg)
}

onConditionReady(async (payload) => {
    statArg = payload
    knowledgeNode.value = null
    knowledgeCheckNodes.value = []

    await loadKnowledge(payload)
    await _loadClassStatistic()
    await built.value.loadBuiltPaper(payload)
})

watch(conditionArgs, () => built.value.reset())

// 刷新数据
const refresh = async () => {
    if (statArg) {
        await _loadClassStatistic()
        await built.value.loadBuiltPaper(statArg)
    }
}

defineExpose({ refresh })
</script>

<style scoped>

</style>