<template>
    <el-form ref="queryRef" :model="queryParams" :rules="rules" label-width="68px" inline>
        <el-form-item label="批次" prop="batchId">
            <el-select v-model="batchId" clearable @change="handleQuery" style="width: 172px">
                <el-option v-for="b in batchList" :label="formatBatchName(b)" :value="b.batchId"/>
            </el-select>
        </el-form-item>
        <el-form-item label="考生类型" prop="examType">
                <el-select v-model="queryParams.examType" clearable @change="handleQuery" style="width: 172px">
                    <el-option
                        v-for="dict in exam_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
        </el-form-item>
        <el-form-item label="组卷类型" prop="buildType">
                <el-select v-model="queryParams.buildType" clearable @change="handleQuery" style="width: 172px">
                    <el-option
                        v-for="dict in build_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
        </el-form-item>
        <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        
        <Table 
            :data="list" 
            :columns="columns" 
            :actions="actions"
            :total="total"
            :query-params="queryParams"
            @get-list="getList"
            @action="handleAction"
        >
            <template #batchName="{row}">
                <span>{{ getBatchDisplayName(row) }}</span>
            </template>
            <template #buildType="{row}">
                <dict-tag v-if="row && row.buildType && build_type" :options="build_type" :value="row.buildType" />
                <span v-else>-</span>
            </template>
            <template #examType="{row}">
                <dict-tag v-if="row && row.examType && exam_type" :options="exam_type" :value="row.examType" />
                <span v-else>-</span>
            </template>
            <template #questionInfo="{row}">
                <span class="question-info-link" @click="handleShowTypes(row)">{{ getQuestionInfo(row) }}</span>
            </template>
            <template #duration="{row}">
                <span>{{ getDuration(row) }}</span>
            </template>
            <template #createTime="{row}">
                <span>{{ row.createTime ? parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
            </template>
            <template #paperName="{row}">
                <span class="paper-name-link" @click="handleShowPaperDetail(row)">{{ row.paperName || '-' }}</span>
            </template>
            <template #download="{row}">
                <el-button type="primary" link @click="handleDownload(row.paperId, row.paperName)" v-hasPermi="['learn:paper:download']">下载</el-button>
                <el-button type="success" link @click="handleShowPaperQuestion(row.paperId)">题目</el-button>
                <el-button type="info" link @click="handleEditPaper(row)">编辑</el-button>
                <el-button type="warning" link @click="handleSendPaper(row)">发送</el-button>
            </template>
        </Table>
        
        <!-- 题目类型详情弹窗 -->
        <el-dialog v-model="typesDialogVisible" title="题目类型详情" width="600px" destroy-on-close>
            <el-table :data="typesList" style="width: 100%">
                <el-table-column label="题目类型" prop="type" width="150" align="center"/>
                <el-table-column label="数量" prop="count" width="120" align="center"/>
                <el-table-column label="分数" prop="score" width="120" align="center"/>
            </el-table>
        </el-dialog>
        
        <!-- 试卷题目详情弹窗 -->
        <el-dialog v-model="paperDetailDialogVisible" :title="currentPaperName || '试卷题目详情'" width="80%" destroy-on-close>
            <div class="paper-detail-container" v-loading="paperDetailLoading">
                <div class="paper-info-header">
                    <div class="paper-info-item">
                        <span class="paper-info-label">试卷名称：</span>
                        <span class="paper-info-value">{{ currentPaperName || '-' }}</span>
                    </div>
                    <div class="paper-info-item">
                        <span class="paper-info-label">科目名称：</span>
                        <span class="paper-info-value">{{ currentSubjectName || '-' }}</span>
                    </div>
                </div>
                <div v-for="(question, index) in questionList" :key="question.id" class="question-item">
                    <div class="question-header">
                        <span class="question-index">{{ index + 1 }}.</span>
                        <span class="question-id">题目ID: {{ question.id }}</span>
                        <span class="question-type">题型: {{ question.type }}</span>
                        <span class="question-score">分数: {{ question.score }}</span>
                        <span class="question-knowledge" v-if="question.knowledgeId">知识点ID: {{ question.knowledgeId }}</span>
                    </div>
                    <div class="question-title">{{ question.title }}</div>
                    <div class="question-options" v-if="question.options && question.options.length > 0">
                        <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                            <span class="option-label">{{ getOptionLabel(optIndex) }}.</span>
                            <span class="option-content">{{ option }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
        
        <!-- 试卷题目弹窗 -->
        <el-dialog v-model="paperQuestionDialogVisible" title="试卷题目" width="90%" destroy-on-close>
            <div style="height: 70vh; overflow: auto;">
                <QuestionsComponent v-if="paperQuestionDialogVisible" :paper-id="currentPaperId" :hide-actions="true" />
            </div>
        </el-dialog>
        
        <!-- 编辑试卷弹窗 -->
        <el-dialog v-model="editPaperDialogVisible" title="编辑试卷" width="600px" destroy-on-close>
            <el-form ref="editPaperFormRef" :model="editPaperForm" :rules="editPaperRules" label-width="120px">
                <el-form-item label="试卷名称" prop="paperName">
                    <el-input v-model="editPaperForm.paperName" placeholder="请输入试卷名称" maxlength="200" show-word-limit />
                </el-form-item>
                <el-form-item label="试卷年份" prop="year">
                    <el-input-number v-model="editPaperForm.year" :min="2000" :max="2100" placeholder="请输入试卷年份" style="width: 100%" />
                </el-form-item>
                <el-form-item label="试卷类型" prop="buildType">
                    <el-select v-model="editPaperForm.buildType" clearable placeholder="请选择试卷类型" style="width: 100%">
                        <el-option
                            v-for="dict in build_type"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="科目ID" prop="subjectId">
                    <el-select 
                        v-model="editPaperForm.subjectId" 
                        clearable 
                        filterable 
                        placeholder="请选择科目" 
                        style="width: 100%"
                        :loading="subjectListLoading"
                    >
                        <el-option-group v-for="g in groupedSubjects" :key="g.label" :label="g.label">
                            <el-option 
                                v-for="s in g.items" 
                                :key="s.subjectId" 
                                :label="`${s.subjectName}(${s.subjectId})`" 
                                :value="s.subjectId"
                            />
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="考生类型" prop="examType">
                    <el-select v-model="editPaperForm.examType" clearable placeholder="请选择考生类型" style="width: 100%">
                        <el-option
                            v-for="dict in exam_type"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="试卷ID" prop="paperId">
                    <el-input-number v-model="editPaperForm.paperId" :min="1" placeholder="请输入试卷ID" style="width: 100%" />
                </el-form-item>
                <el-form-item label="定向Key" prop="directKey">
                    <el-input v-model="editPaperForm.directKey" placeholder="请输入定向Key" maxlength="200" />
                </el-form-item>
                <!-- <el-form-item label="生成条件" prop="conditions">
                    <el-input 
                        v-model="editPaperForm.conditions" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入试卷生成条件" 
                        maxlength="500"
                        show-word-limit
                    />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editPaperDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleConfirmEdit" :loading="editing">确 定</el-button>
                </div>
            </template>
        </el-dialog>
        
        <!-- 发送试卷弹窗 -->
        <el-dialog v-model="sendPaperDialogVisible" title="发送试卷" width="60%" destroy-on-close>
            <el-form :model="sendPaperForm" label-width="100px">
                <SchoolClassSelect
                    ref="schoolClassSelectRef"
                    v-model="sendPaperForm"
                    :enable-campus="true"
                    :multiple-class="true"
                    :auto-load="false"
                    school-label="所在学校"
                    school-class-label="学校班级"
                    campus-label="培训校区"
                    campus-class-label="校区班级"
                    school-placeholder="请选择所在学校"
                    school-class-placeholder="请选择学校班级"
                    campus-placeholder="请选择培训校区"
                    campus-class-placeholder="请选择校区班级"
                    @change="handleSchoolClassChange"
                />
                <el-form-item label="学生列表">
                    <div style="max-height: 400px; overflow-y: auto; border: 1px solid #dcdfe6; border-radius: 4px; padding: 10px;">
                        <el-checkbox-group v-model="selectedStudentIds" v-loading="studentListLoading">
                            <div class="student-checkbox-container">
                                <el-checkbox 
                                    v-for="student in studentList" 
                                    :key="student.cardId" 
                                    :label="student.userId || student.cardId"
                                    :disabled="student.isSend === true"
                                    :class="{ 'is-sent': student.isSend === true }"
                                    class="student-checkbox-item"
                                >
                                    <span :class="{ 'text-gray': student.isSend === true }">
                                        {{ student.nickName || student.userName || `卡片${student.cardNo || student.cardId}` }}
                                        <span v-if="student.isSend === true" class="sent-tag">(已发送)</span>
                                    </span>
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>
                        <div v-if="!studentListLoading && studentList.length === 0" style="text-align: center; color: #909399; padding: 20px;">
                            请先选择学校和班级或校区和校区班级
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="sendPaperDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="handleConfirmSend" :loading="sending">确 定</el-button>
                </div>
            </template>
        </el-dialog>
</template>

<script setup name="ListPaperRecords">
import { ref, computed, getCurrentInstance, onMounted, markRaw, nextTick, watch } from 'vue'
import { useInjectGlobalLoading } from "@/views/hooks/useGlobalLoading.js"
import { getPapers, getFrontPaperDetail, sendPaper, updatePaper, getPaperSubjects, getPaperExamTypes } from "@/api/dz/papers.js"
import { listPaper_question } from "@/api/learn/paper_question.js"
import { listCards2 } from "@/api/dz/cards.js"
import SchoolClassSelect from '@/views/dz/components/SchoolClassSelect.vue'
import { ElMessage } from 'element-plus'
import Table from '@/components/Table/index.vue'
import DictTag from '@/components/DictTag/index.vue'
import consts from "@/utils/consts.js"
import { listToMap } from "@/utils/index.js"
import { useProvidePaperBatchCondition } from "@/views/dz/papers/hooks/usePaperBatchCondition.js"
import { usePaperDownload } from "@/views/dz/papers/hooks/usePaperDownload.js"
import { parseTime } from "@/utils/ruoyi.js"
import Pagination from '@/components/Pagination/index.vue'
import QuestionsComponent from '@/views/learn/questions/index.vue'

const { proxy } = getCurrentInstance()
const { exam_type } = proxy.useDict("exam_type")
const { build_type } = proxy.useDict("build_type")
const { loading } = useInjectGlobalLoading()

// 批次相关 - 使用 useProvidePaperBatchCondition hook
const {
    batchList,
    batchId,
    formatBatchName,
    getBatchDisplayName
} = useProvidePaperBatchCondition(null, false)

// 查询参数
const queryParams = ref({
    examType: '',
    buildType: '',
    pageNum: 1,
    pageSize: 10
})

// 下载功能
const { handleDownload } = usePaperDownload(queryParams)

// 表单验证规则
const rules = {}

// 列表数据
const list = ref([])
const total = ref(0)

// 题目类型详情弹窗
const typesDialogVisible = ref(false)
const typesList = ref([])

// 试卷题目详情弹窗
const paperDetailDialogVisible = ref(false)
const paperDetailLoading = ref(false)
const questionList = ref([])
const currentPaperName = ref('')
const currentSubjectName = ref('')

// 试卷题目弹窗
const paperQuestionDialogVisible = ref(false)
const currentPaperId = ref(null)

// 编辑试卷弹窗
const editPaperDialogVisible = ref(false)
const editPaperFormRef = ref(null)
const editPaperForm = ref({
    id: null,
    paperName: '',
    year: null,
    buildType: '',
    subjectId: null,
    examType: '',
    paperId: null,
    directKey: '',
    conditions: ''
})
const editPaperRules = {
    paperName: [
        { required: true, message: '请输入试卷名称', trigger: 'blur' }
    ],
    year: [
        { required: true, message: '请输入试卷年份', trigger: 'blur' }
    ]
}
const editing = ref(false)
const currentEditPaperRow = ref(null)

// 科目列表（用于编辑表单）
const subjectList = ref([])
const groupedSubjects = computed(() => {
    const groups = []
    subjectList.value.forEach(s => {
        const match = groups.find(g => g.label == s.groupName)
        if (!match) {
            groups.push({
                label: s.groupName,
                items: [s]
            })
        } else {
            match.items.push(s)
        }
    })
    return groups
})
const subjectListLoading = ref(false)

// 发送试卷弹窗
const sendPaperDialogVisible = ref(false)
const sendPaperForm = ref({
    schoolId: null,
    schoolClassIds: null,
    campusId: null,
    campusClassIds: null,
    classId: null // 用于兼容原有逻辑
})
const studentList = ref([])
const selectedStudentIds = ref([])
const studentListLoading = ref(false)
const sending = ref(false)
const currentPaperRow = ref(null)


// 获取题数/总分显示
const getQuestionInfo = (row) => {
    if (!row) return '-'
    const number = row.number || 0
    const totalScore = row.totalScore || 0
    return `${number}/${totalScore}`
}

// 获取时长（分钟）
const getDuration = (row) => {
    if (!row || !row.paperInfo) return '-'
    try {
        // paperInfo 可能是 JSON 字符串或对象
        const paperInfo = typeof row.paperInfo === 'string' ? JSON.parse(row.paperInfo) : row.paperInfo
        if (paperInfo && paperInfo.time) {
            const minutes = Math.round(paperInfo.time / 60)
            return `${minutes}分钟`
        }
    } catch (e) {
        console.error('解析 paperInfo 失败:', e)
    }
    return '-'
}

// 显示题目类型详情
const handleShowTypes = (row) => {
    if (!row || !row.paperInfo) {
        typesList.value = []
        typesDialogVisible.value = true
        return
    }
    try {
        // paperInfo 可能是 JSON 字符串或对象
        const paperInfo = typeof row.paperInfo === 'string' ? JSON.parse(row.paperInfo) : row.paperInfo
        if (paperInfo && Array.isArray(paperInfo.types)) {
            typesList.value = paperInfo.types.map(t => ({
                type: t.type || '-',
                count: t.count || 0,
                score: t.score || 0
            }))
        } else {
            typesList.value = []
        }
    } catch (e) {
        console.error('解析 paperInfo 失败:', e)
        typesList.value = []
    }
    typesDialogVisible.value = true
}

// 显示试卷题目详情
const handleShowPaperDetail = async (row) => {
    if (!row || !row.paperId) {
        ElMessage.warning('试卷ID不存在')
        return
    }
    
    // 保存试卷名称和科目名称
    currentPaperName.value = row.paperName || ''
    currentSubjectName.value = row.subjectName || ''
    
    paperDetailDialogVisible.value = true
    paperDetailLoading.value = true
    questionList.value = []
    
    try {
        const response = await getFrontPaperDetail('', row.paperId)
        if (response && response.code === 200 && response.data && response.data.questions) {
            // 处理题目数据
            questionList.value = response.data.questions.map((q, index) => ({
                index: index + 1,
                id: q.id || '-',
                title: q.title || '-',
                type: q.type || '-',
                options: q.options || [],
                knowledgeId: q.knowledgeId || '-',
                score: q.score || 0
            }))
        } else {
            ElMessage.warning('获取试卷详情失败')
            questionList.value = []
        }
    } catch (error) {
        console.error('获取试卷详情失败:', error)
        ElMessage.error('获取试卷详情失败')
        questionList.value = []
    } finally {
        paperDetailLoading.value = false
    }
}

// 获取选项标签（A, B, C, D, E, F, G...）
const getOptionLabel = (index) => {
    const labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    return labels[index] || String(index + 1)
}

// 显示试卷题目
const handleShowPaperQuestion = (paperId) => {
    if (!paperId) {
        ElMessage.warning('试卷ID不存在')
        return
    }
    
    currentPaperId.value = paperId
    paperQuestionDialogVisible.value = true
}

// 显示编辑试卷弹窗
const handleEditPaper = async (row) => {
    if (!row || !row.paperId) {
        ElMessage.warning('试卷信息不存在')
        return
    }
    
    currentEditPaperRow.value = row
    editPaperForm.value = {
        id: row.paperId,
        paperName: row.paperName || '',
        year: row.year || null,
        buildType: row.buildType || '',
        subjectId: row.subjectId || null,
        examType: row.examType || '',
        paperId: row.paperId || null,
        directKey: row.directKey || '',
        conditions: row.conditions || ''
    }
    
    // 加载科目列表（如果有 examType 和 buildType）
    if (row.examType && row.buildType) {
        await loadSubjectList(row.buildType, row.examType)
    }
    
    editPaperDialogVisible.value = true
}

// 加载科目列表
const loadSubjectList = async (buildType, examType) => {
    if (!buildType || !examType) {
        subjectList.value = []
        return
    }
    
    subjectListLoading.value = true
    try {
        const response = await getPaperSubjects({
            buildType,
            examType
        })
        if (response && response.code === 200 && response.data) {
            subjectList.value = response.data
        } else {
            subjectList.value = []
        }
    } catch (error) {
        console.error('加载科目列表失败:', error)
        subjectList.value = []
    } finally {
        subjectListLoading.value = false
    }
}

// 监听考生类型变化，重新加载科目列表
watch(() => editPaperForm.value.examType, async (newExamType) => {
    if (editPaperDialogVisible.value && newExamType && currentEditPaperRow.value?.buildType) {
        editPaperForm.value.subjectId = null // 清空科目选择
        await loadSubjectList(currentEditPaperRow.value.buildType, newExamType)
    }
})

// 确认编辑试卷
const handleConfirmEdit = async () => {
    if (!editPaperFormRef.value) return
    
    try {
        await editPaperFormRef.value.validate()
    } catch (error) {
        return
    }
    
    if (!editPaperForm.value.id) {
        ElMessage.warning('试卷ID不存在')
        return
    }
    
    editing.value = true
    try {
        const response = await updatePaper({
            id: editPaperForm.value.id,
            paperName: editPaperForm.value.paperName,
            year: editPaperForm.value.year,
            buildType: editPaperForm.value.buildType,
            subjectId: editPaperForm.value.subjectId,
            examType: editPaperForm.value.examType,
            paperId: editPaperForm.value.paperId,
            directKey: editPaperForm.value.directKey,
            conditions: editPaperForm.value.conditions
        })
        
        if (response && response.code === 200) {
            ElMessage.success('编辑成功')
            editPaperDialogVisible.value = false
            // 刷新列表
            await getList()
        } else {
            ElMessage.error(response?.msg || '编辑失败')
        }
    } catch (error) {
        console.error('编辑试卷失败:', error)
        ElMessage.error(error?.msg || error?.message || '编辑试卷失败')
    } finally {
        editing.value = false
    }
}

// 学校班级选择组件的引用
const schoolClassSelectRef = ref(null)

// 显示发送试卷弹窗
const handleSendPaper = async (row) => {
    if (!row || !row.paperId) {
        ElMessage.warning('试卷信息不存在')
        return
    }
    
    currentPaperRow.value = row
    sendPaperForm.value = {
        schoolId: null,
        schoolClassIds: null,
        campusId: null,
        campusClassIds: null,
        classId: null
    }
    studentList.value = []
    selectedStudentIds.value = []
    sendPaperDialogVisible.value = true
    
    // 等待弹窗打开后，再加载学校列表和校区列表
    await nextTick()
    if (schoolClassSelectRef.value) {
        await Promise.all([
            schoolClassSelectRef.value.loadSchoolList(true),
            schoolClassSelectRef.value.loadCampusList()
        ])
    }
}

// 学校班级变化处理
const handleSchoolClassChange = async (data) => {
    // 更新表单数据
    sendPaperForm.value.schoolId = data.schoolId
    sendPaperForm.value.schoolClassIds = data.schoolClassIds
    sendPaperForm.value.campusId = data.campusId
    sendPaperForm.value.campusClassIds = data.campusClassIds
    
    // 判断是否有学校班级或校区班级
    const hasSchoolClass = data.schoolClassIds && (
        (Array.isArray(data.schoolClassIds) && data.schoolClassIds.length > 0) ||
        (!Array.isArray(data.schoolClassIds) && data.schoolClassIds)
    )
    const hasCampusClass = data.campusClassIds && (
        (Array.isArray(data.campusClassIds) && data.campusClassIds.length > 0) ||
        (!Array.isArray(data.campusClassIds) && data.campusClassIds)
    )
    
    // 如果选择了班级，加载学生列表
    if ((hasSchoolClass && data.schoolId) || (hasCampusClass && data.campusId)) {
        await loadStudentList()
    } else {
        studentList.value = []
        selectedStudentIds.value = []
    }
}

// 加载学生列表
const loadStudentList = async () => {
    studentListLoading.value = true
    try {
        const params = {
            pageNum: 1,
            pageSize: 10000 // 获取所有学生
        }
        
        // 传递 paperId，用于判断学生是否已发送
        // 从表格数据看，row 中有 paperId 字段（对应 learn_paper.id）
        if (currentPaperRow.value) {
            if (currentPaperRow.value.paperId) {
                params.paperId = currentPaperRow.value.paperId
            } else {
                console.warn('paperId 不存在，无法判断学生是否已发送', currentPaperRow.value)
            }
        }
        
        // 优先使用学校班级，如果没有则使用校区班级
        if (sendPaperForm.value.schoolId && sendPaperForm.value.schoolClassIds) {
            // 使用学校班级
            const classIds = Array.isArray(sendPaperForm.value.schoolClassIds) 
                ? sendPaperForm.value.schoolClassIds 
                : [sendPaperForm.value.schoolClassIds]
            
            // 如果有多个班级，需要分别查询或使用第一个班级
            // 这里先使用第一个班级，如果需要支持多班级，可以循环查询
            params.schoolId = sendPaperForm.value.schoolId
            params.classId = classIds[0]
        } else if (sendPaperForm.value.campusId && sendPaperForm.value.campusClassIds) {
            // 使用校区班级
            const classIds = Array.isArray(sendPaperForm.value.campusClassIds) 
                ? sendPaperForm.value.campusClassIds 
                : [sendPaperForm.value.campusClassIds]
            
            params.campusId = sendPaperForm.value.campusId
            params.campusClassId = classIds[0]
        } else {
            studentList.value = []
            selectedStudentIds.value = []
            studentListLoading.value = false
            return
        }
        
        const response = await listCards2(params)
        if (response && response.rows) {
            // 从卡片数据中提取学生信息
            // 只保留已关联用户的卡片（有nickName表示已关联用户）
            studentList.value = response.rows
                .filter(card => card.nickName || card.cardId) // 保留有昵称或卡片ID的记录
                .map(card => ({
                    userId: card.userId || null, // userId可能不存在，使用cardId作为标识
                    cardId: card.cardId,
                    nickName: card.nickName || card.cardNo || `卡片${card.cardId}`,
                    userName: card.userName || null,
                    cardNo: card.cardNo,
                    isSend: card.isSend || false // 保留 isSend 字段
                }))
        } else {
            studentList.value = []
        }
    } catch (error) {
        console.error('加载学生列表失败:', error)
        ElMessage.error('加载学生列表失败')
        studentList.value = []
    } finally {
        studentListLoading.value = false
    }
}

// 确认发送
const handleConfirmSend = async () => {
    if (!currentPaperRow.value || !currentPaperRow.value.paperId) {
        ElMessage.warning('试卷信息不存在')
        return
    }
    
    // 检查学校班级或校区班级（至少选择一组）
    const hasSchoolClass = sendPaperForm.value.schoolId && sendPaperForm.value.schoolClassIds && (
        (Array.isArray(sendPaperForm.value.schoolClassIds) && sendPaperForm.value.schoolClassIds.length > 0) ||
        (!Array.isArray(sendPaperForm.value.schoolClassIds) && sendPaperForm.value.schoolClassIds)
    )
    const hasCampusClass = sendPaperForm.value.campusId && sendPaperForm.value.campusClassIds && (
        (Array.isArray(sendPaperForm.value.campusClassIds) && sendPaperForm.value.campusClassIds.length > 0) ||
        (!Array.isArray(sendPaperForm.value.campusClassIds) && sendPaperForm.value.campusClassIds)
    )
    
    if (!hasSchoolClass && !hasCampusClass) {
        ElMessage.warning('请选择学校班级或校区班级')
        return
    }
    
    if (!selectedStudentIds.value || selectedStudentIds.value.length === 0) {
        ElMessage.warning('请至少选择一个学生')
        return
    }
    
    sending.value = true
    try {
        // 获取 testPaperId（表格中的 id 字段，对应 learn_test_paper.id）
        // 从 SQL 查询看，返回的字段是 t1.id，应该就是 id
        // 如果 id 不存在，打印调试信息
        const testPaperId = currentPaperRow.value.id
        
        if (!testPaperId) {
            // 打印完整的数据结构，帮助调试
            console.error('当前行数据:', JSON.stringify(currentPaperRow.value, null, 2))
            console.error('可用的字段:', Object.keys(currentPaperRow.value))
            ElMessage.error('试卷ID不存在，请检查数据。已打印调试信息到控制台')
            return
        }
        
        // 获取选中的学生的 cardId 列表
        const selectedCardIds = studentList.value
            .filter(student => selectedStudentIds.value.includes(student.userId || student.cardId))
            .map(student => student.cardId)
            .filter(cardId => cardId != null)
        
        if (selectedCardIds.length === 0) {
            ElMessage.warning('请至少选择一个有效的学生')
            return
        }
        
        // 调用发送试卷的API
        await sendPaper(testPaperId, selectedCardIds)
        ElMessage.success(`试卷已发送给 ${selectedCardIds.length} 个学生`)
        sendPaperDialogVisible.value = false
        // 刷新列表
        await getList()
    } catch (error) {
        console.error('发送试卷失败:', error)
        ElMessage.error(error?.msg || error?.message || '发送试卷失败')
    } finally {
        sending.value = false
    }
}

// 表格列定义
const columns = [
    { label: 'ID', prop: 'id', width: 80 },
    { label: '批次', prop: 'batchName', minWidth: 150, type: 'slot', slotName: 'batchName' },
    { label: '组卷类型', prop: 'buildType', width: 120, type: 'slot', slotName: 'buildType' },
    { label: '科目名称', prop: 'subjectName', minWidth: 120 },
    { label: '考生类型', prop: 'examType', width: 120, type: 'slot', slotName: 'examType' },
    { label: '试卷名称', prop: 'paperName', minWidth: 200, showOverflowTooltip: true, type: 'slot', slotName: 'paperName' },
    { label: '试卷年份', prop: 'year', width: 100 },
    { label: '试卷类型', prop: 'paperType', width: 120 },
    { label: '题数/总分', prop: 'questionInfo', width: 100, type: 'slot', slotName: 'questionInfo' },
    { label: '时长(分钟)', prop: 'duration', width: 120, type: 'slot', slotName: 'duration' },
    { label: '创建时间', prop: 'createTime', width: 160, type: 'slot', slotName: 'createTime' },
    { label: '操作', prop: 'download', width: 280, type: 'slot', slotName: 'download' }
]

// 操作按钮
const actions = []

// 搜索
const handleQuery = () => {
    queryParams.value.pageNum = 1
    queryParams.value.buildType = queryParams.value.buildType || ''
    getList()
}

// 重置
const resetQuery = () => {
    proxy.resetForm('queryRef')
    batchId.value = ''
    queryParams.value.examType = ''
    queryParams.value.buildType = ''
    queryParams.value.pageNum = 1
    handleQuery()
}

// 获取列表数据
const getList = () => {
    loading.value = true
    
    const params = {
        batchId: batchId.value || '',
        examType: queryParams.value.examType || '',
        buildType: queryParams.value.buildType || '',
        pageNum: queryParams.value.pageNum || 1,
        pageSize: queryParams.value.pageSize || 10
    }
    
    getPapers(params).then(response => {
        // 自动补全组卷类型名称
        const buildTypeMap = listToMap(consts.enums.buildTypes, i => i.id, i => i.name)
        if (response.rows) {
            response.rows.forEach(r => {
                if (r.buildTypeName) return
                r.buildTypeName = buildTypeMap[r.buildType] || r.buildType
            })
            list.value = response.rows
            total.value = response.total
        } else if (response.data) {
            // 处理分页数据结构
            const data = response.data
            if (Array.isArray(data)) {
                list.value = data.map(r => {
                    if (r.buildTypeName) return r
                    r.buildTypeName = buildTypeMap[r.buildType] || r.buildType
                    return r
                })
                total.value = response.total || data.length
            } else {
                list.value = []
                total.value = 0
            }
        } else {
            list.value = []
            total.value = 0
        }
    }).catch(error => {
        console.error('获取试卷列表失败:', error)
        list.value = []
        total.value = 0
    }).finally(() => {
        loading.value = false
    })
}

// 处理操作
const handleAction = (action, row) => {
    // 可以根据需要添加操作逻辑
    console.log('Action:', action, row)
}

// 刷新方法（供父组件调用）
const refresh = () => {
    getList()
}

// 暴露方法
defineExpose({ refresh })

// 初始化加载数据
onMounted(() => {
    getList()
})
</script>

<style scoped>
.question-info-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
}

.question-info-link:hover {
    color: #66b1ff;
}

.paper-name-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: underline;
}

.paper-name-link:hover {
    color: #66b1ff;
}

.paper-detail-container {
    max-height: 70vh;
    overflow-y: auto;
    padding: 20px;
}

.paper-info-header {
    display: flex;
    gap: 30px;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #e4e7ed;
}

.paper-info-item {
    display: flex;
    align-items: center;
    font-size: 16px;
}

.paper-info-label {
    font-weight: 600;
    color: #606266;
    margin-right: 8px;
}

.paper-info-value {
    color: #303133;
    font-weight: 500;
}

.question-item {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
    page-break-inside: avoid;
}

.question-item:last-child {
    border-bottom: none;
}

.question-header {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #606266;
}

.question-index {
    font-weight: bold;
    font-size: 16px;
    color: #303133;
}

.question-id,
.question-type,
.question-score,
.question-knowledge {
    font-size: 13px;
    color: #909399;
}

.question-title {
    font-size: 15px;
    line-height: 1.6;
    color: #303133;
    margin-bottom: 15px;
    margin-left: 25px;
}

.question-options {
    margin-left: 25px;
    margin-bottom: 10px;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.option-item {
    display: flex;
    align-items: flex-start;
    line-height: 1.6;
    font-size: 14px;
    width: calc(50% - 10px);
    min-width: 200px;
}

.option-label {
    font-weight: 500;
    color: #606266;
    margin-right: 8px;
    min-width: 20px;
}

.option-content {
    color: #303133;
    flex: 1;
}

/* 学生复选框容器 */
.student-checkbox-container {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

/* 学生复选框项 - 一行显示3个 */
.student-checkbox-item {
    flex: 0 0 calc(33.333% - 8px);
    min-width: 200px;
    max-width: calc(33.333% - 8px);
}

/* 已发送的学生样式 */
.is-sent {
    opacity: 0.6;
}

.text-gray {
    color: #909399;
}

.sent-tag {
    color: #909399;
    font-size: 12px;
    margin-left: 4px;
}
</style>

