<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 />
                </el-aside>

                <el-main class="">
                    <div class="panel-shell p-6">
                        <div class="text-lg font-semibold mb-4">学案查询</div>
                        <div class="flex flex-wrap items-center gap-3 mb-4">
                            <el-input v-model="searchName" placeholder="按姓名查询" clearable style="max-width: 220px" />
                            <el-button type="primary" @click="onSearch">查询</el-button>
                            <el-button @click="onReset">重置</el-button>
                        </div>
                        <div class="hidden sm:block overflow-x-auto">
                            <el-table ref="tableRef" :data="rows" border class="min-w-[720px]" v-loading="loading" row-key="id">
                                <el-table-column type="expand">
                                    <template #default="{ row }">
                                        <div class="p-3">
                                            <div class="text-sm font-semibold mb-2">学案</div>
                                            <div class="overflow-x-auto">
                                                <el-table :data="row.plans || []" size="small" border class="min-w-[600px]">
                                                    <el-table-column prop="title" label="标题" min-width="280" />
                                                    <el-table-column label="状态" width="120">
                                                        <template #default="{ row: plan }">
                                                            <el-tag :type="plan.isFinished === 1 ? 'success' : 'info'"
                                                                effect="plain">
                                                                {{ plan.isFinished === 1 ? '已完成' : '未完成' }}
                                                            </el-tag>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column label="操作" width="200" fixed="right">
                                                        <template #default="{ row: plan }">
                                                            <el-button type="primary" size="small"
                                                                :loading="downloadingIds.includes(plan.id)"
                                                                @click="onDownload(plan)">下载</el-button>
                                                            <el-button class="ml-2" type="primary" size="small"
                                                                :disabled="plan.isFinished === 1"
                                                                :loading="finishingIds.includes(plan.id)"
                                                                @click="onFinish(row.id, plan.id, plan)">完成</el-button>
                                                        </template>
                                                    </el-table-column>
                                                </el-table>
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" label="姓名" min-width="140" />
                                <el-table-column prop="className" label="班级" min-width="140" />
                                <el-table-column prop="gradeName" label="年级" min-width="140" />
                            </el-table>
                        </div>
                        <div class="sm:hidden space-y-3">
                            <div v-for="row in rows" :key="row.id" class="panel-shell p-4">
                                <div class="text-base font-semibold mb-2">{{ row.name }}</div>
                                <div class="text-sm text-gray-700 mb-1">班级：{{ row.className }}</div>
                                <div class="text-sm text-gray-700 mb-3">年级：{{ row.gradeName }}</div>
                                <div class="flex justify-between items-center">
                                    <div class="text-sm font-medium">学案</div>
                                    <el-button size="small" @click="toggleMobileExpand(row.id)">
                                        {{ mobileExpanded[row.id] ? '收起' : '展开' }}
                                    </el-button>
                                </div>
                                <div v-if="mobileExpanded[row.id]" class="mt-3 space-y-2">
                                    <div v-for="plan in (row.plans || [])" :key="plan.id"
                                        class="rounded-lg border border-white/30 bg-white/50 p-3">
                                        <div class="text-sm font-medium mb-2">{{ plan.title }}</div>
                                        <div class="mb-2">
                                            <el-tag :type="plan.isFinished === 1 ? 'success' : 'info'" effect="plain">
                                                {{ plan.isFinished === 1 ? '已完成' : '未完成' }}
                                            </el-tag>
                                        </div>
                                        <div class="flex gap-2">
                                            <el-button type="primary" size="small"
                                                :loading="downloadingIds.includes(plan.id)"
                                                @click="onDownload(plan)">下载</el-button>
                                            <el-button type="primary" size="small"
                                                :disabled="plan.isFinished === 1"
                                                :loading="finishingIds.includes(plan.id)"
                                                @click="onFinish(row.id, plan.id, plan)">完成</el-button>
                                        </div>
                                    </div>
                                </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>
                </el-main>
            </el-container>


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

<script setup>
import Header from '@/layouts/components/Header.vue'
import { ref, onMounted } from 'vue'
import { findStudentLessonPlans, finishLessonPlan } from '@/api/studentLessonPlans'
import { downloadLessonPlan } from '@/api/plan'
import { showMessage } from '@/composables/util'
import Sidebar from '@/layouts/components/Sidebar.vue'

const rows = ref([])
const loading = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const searchName = ref('')
const tableRef = ref(null)
const downloadingIds = ref([])
const finishingIds = ref([])
const mobileExpanded = ref({})

function toggleMobileExpand(id) {
    const v = mobileExpanded.value[id]
    mobileExpanded.value[id] = !v
}

async function fetchLessonPlans() {
    loading.value = true
    try {
        const res = await findStudentLessonPlans(pageNo.value, pageSize.value, searchName.value || '')
        const d = res.data
        rows.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
    }
}

function handlePageChange(p) {
    pageNo.value = p
    fetchLessonPlans()
}
function handleSizeChange(s) {
    pageSize.value = s
    pageNo.value = 1
    fetchLessonPlans()
}
function onSearch() {
    pageNo.value = 1
    fetchLessonPlans()
}
function onReset() {
    searchName.value = ''
    pageNo.value = 1
    fetchLessonPlans()
}

async function onDownload(plan) {
    if (!plan?.id) {
        showMessage('无效的计划ID', 'error')
        return
    }
    if (!downloadingIds.value.includes(plan.id)) {
        downloadingIds.value = [...downloadingIds.value, plan.id]
    }
    try {
        await downloadLessonPlan({ id: plan.id })
        showMessage('开始下载', 'success')
    } finally {
        downloadingIds.value = downloadingIds.value.filter(id => id !== plan.id)
    }
}

async function onFinish(studentId, planId, plan) {
    if (!studentId || !planId) {
        showMessage('参数错误', 'error')
        return
    }
    if (!finishingIds.value.includes(planId)) {
        finishingIds.value = [...finishingIds.value, planId]
    }
    try {
        const res = await finishLessonPlan(studentId, planId)
        const d = res.data
        if (d?.success !== false) {
            plan.isFinished = 1
            showMessage('已标记完成', 'success')
        } else {
            showMessage(d?.message || '标记失败', 'error')
        }
    } catch (e) {
        showMessage('标记失败', 'error')
    } finally {
        finishingIds.value = finishingIds.value.filter(id => id !== planId)
    }
}

onMounted(() => {
    fetchLessonPlans()
})

</script>
