<template>
    <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>
        </el-col>
        <el-col :span="16">
            <class-statistic-table exact-mode/>
        </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 ref="built" @send="handleSubmit" />
</template>

<script setup name="PaperExactIntelligent">
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 BuiltPaper from "@/views/dz/papers/components/plugs/built-paper.vue";

const type = consts.enums.buildType.ExactIntelligent
const {batchId, batchList, onBatchReady} = useProvidePaperBatchCondition(type)
const {selectedClasses, classList, loadClassStatistic} = useProvidePaperClassStatisticCondition()
const {loading} = useInjectGlobalLoading()
const built = ref(null)
const hasBuiltPaper = computed(() => built.value?.hasPaper)

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())
</script>

<style scoped>

</style>