<template>
    <el-row :gutter="20">
        <el-col :span="8">
            <el-form label-width="68px">
                <BatchYearSelect v-model:batch-id="batchId" :batch-list="batchList" />
            </el-form>
        </el-col>
        <el-col :span="16">
            <class-statistic-table exact-mode @stat-click="handleStatClick"/>
        </el-col>
    </el-row>
    <el-divider/>
    <div v-if="!hasBuiltPaper" class="text-center">
        <el-button type="primary" size="large" @click="handleSubmit">生成试卷</el-button>
    </div>
    <built-paper-list ref="built" @send="handleSubmit" />
    
    <!-- 学生列表弹窗 -->
    <student-list-dialog ref="studentDialogRef" :stat-type-map="statTypeMap"/>
</template>

<script setup name="PaperExactIntelligent">
import { ref, computed } from 'vue'
import consts from "@/utils/consts.js";
import {useProvidePaperBatchCondition} from "@/views/dz/papers/hooks/usePaperBatchCondition.js";
import {useProvidePaperClassStatisticCondition} from "@/views/dz/papers/hooks/usePaperClassStatisticCondition.js";
import ClassStatisticTable from "@/views/dz/papers/components/plugs/class-statistic-table.vue";
import {ElMessage} from "element-plus";
import {buildPaperExactIntelligent} from "@/api/dz/papers.js";
import {useInjectGlobalLoading} from "@/views/hooks/useGlobalLoading.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 BatchYearSelect from "@/views/dz/papers/components/BatchYearSelect.vue";

const type = consts.enums.buildType.ExactIntelligent
const {batchId, batchList, onBatchReady} = useProvidePaperBatchCondition(type, true)
const {selectedClasses, classList, loadClassStatistic} = useProvidePaperClassStatisticCondition()
const {loading} = useInjectGlobalLoading()
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 (statArgs) {
        if (statArgs.examType) queryParams.examType = statArgs.examType
        if (statArgs.universityId) queryParams.universityId = statArgs.universityId
        if (statArgs.majorGroup) queryParams.majorGroup = statArgs.majorGroup
        if (statArgs.majorPlanId) queryParams.majorPlanId = statArgs.majorPlanId
    }
    
    // 打开学生列表弹窗
    studentDialogRef.value?.open(row, statType, type, batchId.value, queryParams)
}

const handleSubmit = async function () {
    if (!batchId.value) return ElMessage.error('请选择批次')
    const classIds = selectedClasses.value.map(c => c.classId)
    if (!classIds.length) return ElMessage.error('请选择班级')

    try {
        loading.value = true
        const commit = {buildType: type, batchId: batchId.value, classIds}
        await buildPaperExactIntelligent(commit)
        ElMessage.success('生成成功')
        await _loadClassStatistic()
    } finally {
        loading.value = false
    }
}

let statArgs = null // 保留参数，生成组卷后刷新用
const _loadClassStatistic = async () => {
    selectedClasses.value = []
    classList.value = []
    await loadClassStatistic(statArgs)
}

onBatchReady(async (payload) => {
    statArgs = payload
    await _loadClassStatistic()
    await built.value.loadBuiltPaper(payload)
})

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

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

defineExpose({ refresh })
</script>

<style scoped>
</style>