<template>
    <el-row :gutter="20">
        <el-col :span="6">
            <knowledge-tree allow-multiple/>
        </el-col>
        <el-col :span="18">
            <el-form label-width="68px">
                <BatchYearSelect v-model:batch-id="batchId" :batch-list="batchList" />
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="省份">
                            <ie-select 
                                v-model="area.selected" 
                                v-model:selectedItem="area.selectedItem" 
                                :options="area.list" 
                                label-key="areaName" 
                                value-key="areaId" 
                                clearable 
                                filterable
                                style="width: 100%"
                                placeholder="请选择省份"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="考生类型">
                            <el-select v-model="selectedExamType" clearable filterable style="width: 100%" placeholder="请选择考生类型">
                                <el-option v-for="e in examTypeList" :label="e.dictLabel" :value="e.dictValue"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="科目">
                            <el-select v-model="selectedSubjectId" clearable filterable style="width: 100%" placeholder="请选择科目">
                                <el-option v-for="s in subjectList" :label="`${s.subjectName}(${s.subjectId})`" :value="s.subjectId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-divider v-if="!hasBuiltPaper" />
            <div v-if="!hasBuiltPaper">
            <question-intelligent @submit="handleSubmit" />
            </div>
        </el-col>
    </el-row>
    <built-paper-list ref="built" @send="handleSubmit" />
</template>

<script setup name="PaperFullIntelligent">
import { ref, computed, watch } from 'vue'
import consts from "@/utils/consts.js";
import {useProvidePaperFullCondition} from "@/views/dz/papers/hooks/usePaperFullCondition.js";
import {useProvidePaperClassStatisticCondition} from "@/views/dz/papers/hooks/usePaperClassStatisticCondition.js";
import KnowledgeTree from "@/views/dz/papers/components/plugs/knowledge-tree.vue";
import {useProvidePaperKnowledgeCondition} from "@/views/dz/papers/hooks/usePaperKnowledgeCondition.js";
import QuestionIntelligent from "@/views/dz/papers/components/plugs/question-intelligent.vue";
import {ElMessage} from "element-plus";
import {buildPaperFullKnowledgeIntelligent} from "@/api/dz/papers.js";
import BuiltPaperList from "@/views/dz/papers/components/plugs/built-paper-list.vue";
import IeSelect from '@/components/IeSelect/index.vue'
import useProvinceExamTypeSubject from '@/views/dz/hooks/useProvinceExamTypeSubject.js'

const type = consts.enums.buildType.FullIntelligent
const {
    batchId,
    batchList,
    examType: paperExamType,
    examTypes: paperExamTypes,
    subjectId: paperSubjectId,
    groupedSubjects,
    conditionArgs,
    onConditionReady,
    onBatchReady
} = useProvidePaperFullCondition(type)

// 使用通用的省份-考生类型-科目联动 hook
const {
    area,
    selectedExamType,
    examTypeList,
    selectedSubjectId,
    subjectList
} = useProvinceExamTypeSubject({
    autoLoadArea: true,
    loadExamType: true,
    onlyVHS: false
})

// 同步到 paperExamType 和 paperSubjectId（用于原有的条件逻辑）
watch(selectedExamType, (val) => {
    paperExamType.value = val || ''
})

watch(selectedSubjectId, (val) => {
    paperSubjectId.value = val || ''
})
const {selectedClasses, classList, loadClassStatistic} = useProvidePaperClassStatisticCondition()
const {knowledgeNode, knowledgeCheckNodes, loadKnowledge} = useProvidePaperKnowledgeCondition()
const built = ref(null)
const hasBuiltPaper = computed(() => built.value?.hasPaper)

const handleSubmit = async (qTypes) => {
    // validation
    // if (!batchId.value) return ElMessage.error('请选择批次')
    if (!batchId.value) batchId.value = '1'
    if (!knowledgeCheckNodes.value.length) return ElMessage.error('请选择知识点')
    // qTypes 已经是过滤后的数组（count > 0），不需要再过滤
    if (!qTypes.length || qTypes.every(t => !t.count)) return ElMessage.error('请填写题量')
    // 知识点组卷不校验班级
    const classIds = selectedClasses.value?.map(c => c.classId) || []

    // build
    // 如果 paperExamType 或 paperSubjectId 为空，使用页面中选择的值
    const finalExamType = toValue(paperExamType) || selectedExamType.value || ''
    const finalSubjectId = toValue(paperSubjectId) || selectedSubjectId.value || null
    
    const commit = {
        buildType: type,
        batchId: toValue(batchId),
        examType: finalExamType,
        subjectId: finalSubjectId,
        knowledgeIds: knowledgeCheckNodes.value.map(k => k.id),
        types: qTypes.map(t => ({
            type: t.dictValue,
            title: t.dictLabel,
            count: t.count,
            score: t.score || 1
        })),
        classIds
    }
    await buildPaperFullKnowledgeIntelligent(commit)
    ElMessage.success('生成成功')
    _loadClassStatistic()
}

let statArg = null
let previousSubjectId = null // 保存上一次的科目ID
const _loadClassStatistic = async () => {
    selectedClasses.value = []
    classList.value = []

    await loadClassStatistic(statArg)
}
onConditionReady(async (payload) => {
    statArg = payload
    
    // 判断是否是科目切换（只有 subjectId 变化，其他条件不变）
    const isSubjectChange = previousSubjectId !== null && 
                           previousSubjectId !== payload.subjectId &&
                           statArg && 
                           statArg.batchId === payload.batchId &&
                           statArg.examType === payload.examType
    
    // 如果不是科目切换，或者是首次加载，则清空知识点
    if (!isSubjectChange) {
    knowledgeNode.value = null
    knowledgeCheckNodes.value = []
    }
    
    // 保存当前的科目ID
    previousSubjectId = payload.subjectId

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

// 监听批次变化，调用接口
onBatchReady(async (payload) => {
    // 如果已经有完整的条件参数，更新批次ID；否则只使用批次
    if (statArg) {
        statArg = { ...statArg, batchId: payload.batchId }
    } else {
        statArg = payload
    }
    await _loadClassStatistic()
    await built.value.loadBuiltPaper(statArg)
})

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

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

defineExpose({ refresh })
</script>

<style scoped>

</style>
