<template>
    <div class="common-layout">
        <el-container class="min-h-screen">
            <el-header>
                <Header></Header>
            </el-header>

            <el-container class="pt-4">
                <el-aside width="200px" class="hidden md:block sidebar-fixed">
                    <Sidebar></Sidebar>
                </el-aside>

                <el-main class="h-full">
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        <div class="lg:col-span-1 flex flex-col gap-6">
                        <div class="panel-shell p-6">
                            <div class="text-lg font-semibold mb-4">班级列表</div>
                            <div class="hidden sm:block overflow-x-auto">
                                <el-table ref="classTableRef" :data="classes" border class="min-w-[520px]" v-loading="loading" highlight-current-row
                                    row-key="id" :current-row-key="selectedClassId" @row-click="onClassRowClick">
                                    <el-table-column prop="title" label="班级名称" min-width="160" />
                                    <el-table-column prop="gradeName" label="年级" min-width="120" />
                                    <el-table-column label="操作" width="120" fixed="right">
                                        <template #default="{ row }">
                                            <el-button type="danger" size="small" @click.stop="onDeleteClass(row)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <div class="sm:hidden space-y-3">
                                <div v-for="row in classes" :key="row.id" class="panel-shell p-4">
                                    <div class="text-base font-semibold mb-1">{{ row.title }}</div>
                                    <div class="text-sm mb-2">年级：{{ row.gradeName }}</div>
                                    <div class="flex gap-2">
                                        <el-button size="small" type="primary" @click="onClassRowClick(row)">选择</el-button>
                                        <el-button size="small" type="danger" @click="onDeleteClass(row)">删除</el-button>
                                    </div>
                                </div>
                            </div>
                                <div class="mt-4 flex justify-end">
                                    <el-pagination background layout="prev, pager, next, sizes, total"
                                        :total="totalCount" :page-size="pageSize" :current-page="pageNo"
                                        @current-change="handlePageChange" @size-change="handleSizeChange" />
                                </div>
                                <div class="mt-3 flex justify-end">
                                    <el-button type="primary" @click="showAddClassDialog = true">新增班级</el-button>
                                </div>
                                <AddClassDialog v-model="showAddClassDialog" :default-grade-id="selectedGradeId"
                                    @success="fetchClasses" />
                            </div>
                        </div>

                    <div class="panel-shell p-6 lg:col-span-1 lg:row-span-2">
                        <div class="text-lg font-semibold mb-4">学生查询</div>
                        <div class="flex flex-wrap items-center gap-3 mb-4">
                            <el-input v-model="studentName" placeholder="按姓名查询" clearable style="max-width: 220px" />
                            <el-tag v-if="selectedClassId" effect="plain">班级：{{ selectedClassTitle }}</el-tag>
                                <el-tag v-if="selectedGradeId" effect="plain">年级：{{ selectedGradeTitle }}</el-tag>
                                <el-button type="primary" @click="fetchStudents">查询</el-button>
                                <el-button @click="resetStudentFilters">重置</el-button>
                                <el-button type="success" :disabled="selectedStudentIds.length !== 1"
                                    @click="showGenerateDialog = true">
                                    生成试题
                                </el-button>
                                <el-button type="warning" :disabled="selectedStudentIds.length !== 1"
                                    @click="showLessonPlanDialog = true">
                                    生成学案
                                </el-button>
                            </div>
                            <div class="hidden sm:block overflow-x-auto">
                                <el-table ref="studentTableRef" :data="students" border class="min-w-[760px]"
                                    v-loading="studentLoading" @selection-change="onStudentSelectionChange">
                                    <el-table-column type="selection" width="48" />
                                    <el-table-column prop="name" label="姓名" min-width="120" />
                                    <el-table-column prop="className" label="班级" min-width="120" />
                                    <el-table-column prop="gradeName" label="年级" min-width="120" />
                                    <el-table-column prop="phone" label="学案" min-width="120">
                                        <template #default="{ row }">
                                            <template v-if="generatingPercents[row.id] !== undefined">
                                                <div class="flex items-center gap-2">
                                                    <el-progress :percentage="generatingPercents[row.id]" :stroke-width="8" />
                                                </div>
                                            </template>
                                            <template v-else>
                                                <div class="flex items-center gap-2">
                                                    <el-button type="primary" size="small" @click="planStudentId = row.id; showPlanListDialog = true">查看学案</el-button>
                                                </div>
                                            </template>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="240" fixed="right">
                                        <template #default="{ row }">
                                            <el-button type="info" size="small" @click.stop="onShowAnalysis(row)">学情分析</el-button>
                                            <el-button type="primary" size="small" @click.stop="onViewStudent(row)">详情</el-button>
                                            <el-button type="danger" size="small" @click.stop="onDeleteStudent(row)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <div class="sm:hidden space-y-3">
                                <div v-for="row in students" :key="row.id" class="panel-shell p-4">
                                    <div class="flex items-center justify-between mb-1">
                                        <div class="text-base font-semibold">{{ row.name }}</div>
                                        <el-checkbox
                                            :model-value="isStudentSelected(row.id)"
                                            @change="(val) => setStudentSelection(row.id, val)">
                                            选中
                                        </el-checkbox>
                                    </div>
                                    <div class="text-sm mb-1">班级：{{ row.className }}</div>
                                    <div class="text-sm mb-2">年级：{{ row.gradeName }}</div>
                                    <template v-if="generatingPercents[row.id] !== undefined">
                                        <div class="mb-2">
                                            <el-progress :percentage="generatingPercents[row.id]" :stroke-width="8" />
                                        </div>
                                    </template>
                                    <div class="flex flex-wrap gap-2">
                                        <el-button size="small" @click="planStudentId = row.id; showPlanListDialog = true">查看学案</el-button>
                                        <el-button size="small" type="info" @click="onShowAnalysis(row)">学情分析</el-button>
                                        <el-button size="small" type="primary" @click="onViewStudent(row)">详情</el-button>
                                        <el-button size="small" type="danger" @click="onDeleteStudent(row)">删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-4 flex justify-end">
                                <el-pagination background layout="prev, pager, next, sizes, total"
                                    :total="studentTotalCount" :page-size="studentPageSize"
                                    :current-page="studentPageNo" @current-change="handleStudentPageChange"
                                    @size-change="handleStudentSizeChange" />
                            </div>
                            <ExamGenerateDialog v-model="showGenerateDialog" :student-ids="selectedStudentIds"
                                :default-grade-id="selectedGradeId" />
                            <div class="mt-3 flex justify-end">
                                <el-button type="primary" @click="showAddStudentDialog = true">新增学生</el-button>
                            </div>
                            <AddStudentDialog v-model="showAddStudentDialog" :default-class-id="selectedClassId"
                                :default-grade-id="selectedGradeId" @success="fetchStudents" />
                            <LessonPlanDialog v-model="showLessonPlanDialog" :student-id="selectedStudentIds[0]"
                                @success="onLessonPlanGenerateSuccess" />
                            <StudentPlanListDialog v-model="showPlanListDialog" :student-id="planStudentId" />
                            <el-dialog v-model="showAnalysisDialog" title="学情分析" width="60%">
                                <StudyAnalysis v-if="showAnalysisDialog" :student-id="analysisStudentId" />
                            </el-dialog>
                        </div>

                    <div class="panel-shell p-6" v-loading="gradeLoading">
                        <div class="text-lg font-semibold mb-4">年级列表</div>
                        <div class="hidden sm:block overflow-x-auto">
                            <el-table ref="gradeTableRef" :data="grades" border class="min-w-[360px]" highlight-current-row
                                row-key="id" :current-row-key="selectedGradeId" @row-click="onGradeRowClick">
                                <el-table-column prop="title" label="年级名称" min-width="160" />
                            </el-table>
                        </div>
                        <div class="sm:hidden space-y-3">
                            <div v-for="row in grades" :key="row.id" class="panel-shell p-4">
                                <div class="text-base font-semibold mb-1">{{ row.title }}</div>
                                <div class="flex gap-2">
                                    <el-button size="small" type="primary" @click="onGradeRowClick(row)">选择</el-button>
                                    <el-button size="small" type="danger" @click="onDeleteGrade(row)">删除</el-button>
                                </div>
                            </div>
                        </div>
                            <div class="mt-4 flex justify-end">
                                <el-pagination background layout="prev, pager, next, sizes, total"
                                    :total="gradeTotalCount" :page-size="gradePageSize" :current-page="gradePageNo"
                                    @current-change="handleGradePageChange" @size-change="handleGradeSizeChange" />
                            </div>
                        </div>

                    </div>
                </el-main>
            </el-container>

        </el-container>
    </div>
</template>

<script setup>
import Header from '@/layouts/components/Header.vue'
import Sidebar from '@/layouts/components/Sidebar.vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { getClassList, deleteClass } from '@/api/class'
import { getGradeList, deleteGrade } from '@/api/grade'
import { getStudentList, deleteStudent } from '@/api/student'
import ExamGenerateDialog from '@/layouts/components/ExamGenerateDialog.vue'
import AddClassDialog from '@/layouts/components/AddClassDialog.vue'
import AddGradeDialog from '@/layouts/components/AddGradeDialog.vue'
import AddStudentDialog from '@/layouts/components/AddStudentDialog.vue'
import LessonPlanDialog from '@/layouts/components/LessonPlanDialog.vue'
import StudentPlanListDialog from '@/layouts/components/StudentPlanListDialog.vue'
import StudyAnalysis from '@/layouts/components/student/StudyAnalysis.vue'
import { getUnitList, deleteUnit } from '@/api/unit'
import AddUnitDialog from '@/layouts/components/AddUnitDialog.vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { checkIsGenerated } from '@/api/plan'

const classes = ref([])
const pageNo = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const loading = ref(false)
const classTableRef = ref(null)
const selectedClassId = ref(null)
const selectedClassTitle = ref('')
const showAddClassDialog = ref(false)

const grades = ref([])
const gradePageNo = ref(1)
const gradePageSize = ref(10)
const gradeTotalCount = ref(0)
const gradeLoading = ref(false)
const gradeTableRef = ref(null)
const selectedGradeId = ref(null)
const selectedGradeTitle = ref('')
const showAddGradeDialog = ref(false)

const students = ref([])
const studentPageNo = ref(1)
const studentPageSize = ref(10)
const studentTotalCount = ref(0)
const studentLoading = ref(false)
const studentName = ref('')
const studentTableRef = ref(null)
const selectedStudentIds = ref([])
const showGenerateDialog = ref(false)
const showAddStudentDialog = ref(false)
const showLessonPlanDialog = ref(false)
const generatingPercents = ref({})
const pollingTimers = {}
const showPlanListDialog = ref(false)
const planStudentId = ref(null)
const showAnalysisDialog = ref(false)
const analysisStudentId = ref(null)

function isStudentSelected(id) {
    return selectedStudentIds.value.includes(id)
}
function setStudentSelection(id, selected) {
    const exists = selectedStudentIds.value.includes(id)
    if (selected && !exists) {
        selectedStudentIds.value = [...selectedStudentIds.value, id]
    } else if (!selected && exists) {
        selectedStudentIds.value = selectedStudentIds.value.filter(x => x !== id)
    }
}

const units = ref([])
const unitPageNo = ref(1)
const unitPageSize = ref(10)
const unitTotalCount = ref(0)
const unitLoading = ref(false)
const unitTableRef = ref(null)
const showAddUnitDialog = ref(false)
const router = useRouter()

async function fetchClasses() {
    loading.value = true
    try {
        const res = await getClassList(pageNo.value, pageSize.value)
        const d = res.data
        classes.value = Array.isArray(d.data) ? d.data : []
        totalCount.value = d.totalCount || 0
        pageNo.value = d.pageNo || pageNo.value
        pageSize.value = d.pageSize || pageSize.value
    } finally {
        loading.value = false
    }
}

async function fetchGrades() {
    gradeLoading.value = true
    try {
        const res = await getGradeList(gradePageNo.value, gradePageSize.value)
        const d = res.data
        grades.value = Array.isArray(d.data) ? d.data : []
        gradeTotalCount.value = d.totalCount || 0
        gradePageNo.value = d.pageNo || gradePageNo.value
        gradePageSize.value = d.pageSize || gradePageSize.value
    } finally {
        gradeLoading.value = false
    }
}

async function fetchStudents() {
    studentLoading.value = true
    try {
        const payload = {
            name: studentName.value || null,
            classId: selectedClassId.value ?? null,
            gradeId: selectedGradeId.value ?? null,
            pageNo: studentPageNo.value,
            pageSize: studentPageSize.value
        }
        const res = await getStudentList(payload)
        const d = res.data
        students.value = Array.isArray(d.data) ? d.data : []
        studentTotalCount.value = d.totalCount || 0
        studentPageNo.value = d.pageNo || studentPageNo.value
        studentPageSize.value = d.pageSize || studentPageSize.value
        ensurePollingForCurrentStudents()
    } finally {
        studentLoading.value = false
    }
}

function handlePageChange(p) {
    pageNo.value = p
    fetchClasses()
}
function handleSizeChange(s) {
    pageSize.value = s
    pageNo.value = 1
    fetchClasses()
}

function handleGradePageChange(p) {
    gradePageNo.value = p
    fetchGrades()
}
function handleGradeSizeChange(s) {
    gradePageSize.value = s
    gradePageNo.value = 1
    fetchGrades()
}

function handleStudentPageChange(p) {
    studentPageNo.value = p
    fetchStudents()
}
function handleStudentSizeChange(s) {
    studentPageSize.value = s
    studentPageNo.value = 1
    fetchStudents()
}
function onStudentSelectionChange(rows) {
    selectedStudentIds.value = rows.map(r => r.id)
}
function onViewStudent(row) {
    router.push(`/student/${row.id}`)
}
function onShowAnalysis(row) {
    analysisStudentId.value = row.id
    showAnalysisDialog.value = true
}
function onClassRowClick(row) {
    selectedClassId.value = row.id
    selectedClassTitle.value = row.title
    classTableRef.value?.setCurrentRow(row)
    studentPageNo.value = 1
    fetchStudents()
}
function onGradeRowClick(row) {
    selectedGradeId.value = row.id
    selectedGradeTitle.value = row.title
    gradeTableRef.value?.setCurrentRow(row)
    studentPageNo.value = 1
    fetchStudents()
}

function startLessonPlanPolling(studentId) {
    if (!studentId) return
    if (pollingTimers[studentId]) return
    const pollOnce = async () => {
        try {
            const res = await checkIsGenerated(studentId)
            const d = res?.data
            const ok = d?.success === false || d?.success === false || d === false
            if (ok) {
                const p = Number(generatingPercents.value[studentId]) || 1
                generatingPercents.value[studentId] = Math.min(p + 5, 95)
            } else {
                if (generatingPercents.value[studentId] !== undefined) {
                    delete generatingPercents.value[studentId]
                }
            }
        } catch (e) {
            const p = Number(generatingPercents.value[studentId]) || 1
            generatingPercents.value[studentId] = Math.min(p + 3, 95)
        }
    }
    pollOnce()
    pollingTimers[studentId] = setInterval(pollOnce, 10000)
}
function onLessonPlanGenerateSuccess(payload) {
    const sid = payload?.studentId || selectedStudentIds.value?.[0]
    startLessonPlanPolling(sid)
}
function ensurePollingForCurrentStudents() {
    (students.value || []).forEach(s => startLessonPlanPolling(s.id))
}
function stopPolling(studentId) {
    const t = pollingTimers[studentId]
    if (t) {
        clearInterval(t)
        delete pollingTimers[studentId]
    }
    if (generatingPercents.value[studentId] !== undefined) {
        delete generatingPercents.value[studentId]
    }
}
function stopAllPolling() {
    Object.keys(pollingTimers).forEach(id => stopPolling(id))
}
onUnmounted(() => {
    stopAllPolling()
})
onBeforeRouteLeave(() => {
    stopAllPolling()
})
async function onDeleteStudent(row) {
    try {
        await ElMessageBox.confirm('确认删除该学生？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteStudent(row.id)
        ElMessage.success('删除成功')
        if (selectedStudentIds.value?.length) {
            selectedStudentIds.value = selectedStudentIds.value.filter(id => id !== row.id)
            studentTableRef.value?.toggleRowSelection(row, false)
        }
        await fetchStudents()
    } catch (e) {
        if (e === 'cancel' || e === 'close') return
        ElMessage.error('删除失败')
    }
}
async function onDeleteClass(row) {
    try {
        await ElMessageBox.confirm('确认删除该班级？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteClass(row.id)
        ElMessage.success('删除成功')
        if (selectedClassId.value === row.id) {
            selectedClassId.value = null
            selectedClassTitle.value = ''
            classTableRef.value?.setCurrentRow()
        }
        await fetchClasses()
    } catch (e) {
        if (e === 'cancel' || e === 'close') return
        ElMessage.error('删除失败')
    }
}
function resetStudentFilters() {
    studentName.value = ''
    selectedClassId.value = null
    selectedClassTitle.value = ''
    selectedGradeId.value = null
    selectedGradeTitle.value = ''
    classTableRef.value?.setCurrentRow()
    gradeTableRef.value?.setCurrentRow()
    studentPageNo.value = 1
    fetchStudents()
}

async function onDeleteGrade(row) {
    try {
        await deleteGrade(row.id)
        ElMessage.success('删除成功')
        if (selectedGradeId.value === row.id) {
            selectedGradeId.value = null
            selectedGradeTitle.value = ''
            gradeTableRef.value?.setCurrentRow()
        }
        await fetchGrades()
    } catch (e) {
        ElMessage.error('删除失败')
    }
}

async function fetchUnits() {
    unitLoading.value = true
    try {
        const res = await getUnitList(unitPageNo.value, unitPageSize.value)
        const d = res.data
        units.value = Array.isArray(d.data) ? d.data : []
        unitTotalCount.value = d.totalCount || 0
        unitPageNo.value = d.pageNo || unitPageNo.value
        unitPageSize.value = d.pageSize || unitPageSize.value
    } finally {
        unitLoading.value = false
    }
}
function handleUnitPageChange(p) {
    unitPageNo.value = p
    fetchUnits()
}
function handleUnitSizeChange(s) {
    unitPageSize.value = s
    unitPageNo.value = 1
    fetchUnits()
}
async function onDeleteUnit(row) {
    try {
        const res = await deleteUnit(row.id)
        const data = res.data
        console.log(data)
        if (data.success) {
            ElMessage.success('删除成功')
        } else {
            ElMessage.error(data.message || '删除失败')
        }
        await fetchUnits()
    } catch (e) {
        ElMessage.error('删除失败')
    }
}

onMounted(() => {
    fetchClasses()
    fetchGrades()
    fetchStudents()
    fetchUnits()
})
</script>
