<template>
    <div class="index-lists">
        <el-card class="!border-none" shadow="never">
            <div style="display: flex; align-items: center; margin-bottom: 16px">
                <div style="font-size: 18px; font-weight: 500">
                    {{ classData.className }}
                </div>
                <div style="font-size: 16px; font-weight: 400; margin-left: 32px; color: #606266">
                    状态：{{ formatClassProgress(classData.classProgress) }}
                </div>
            </div>
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="教学任务业务编号" prop="taskCode">
                    <el-input class="w-[280px]" v-model="queryParams.taskCode" />
                </el-form-item>
                <el-form-item label="学期" prop="semesterId">
                    <el-select v-model="queryParams.semesterId" class="w-[280px]" clearable>
                        <el-option
                            v-for="college in getConfigLists.lists"
                            :key="college.id"
                            :value="college.id"
                            :label="college.config"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="课程" prop="courseId">
                    <el-select
                        v-model="queryParams.courseId"
                        placeholder="请输入课程名称搜索"
                        :remote="true"
                        :remote-method="handleCourseRemoteSearch"
                        :loading="courseSearchLoading"
                        filterable
                        clearable
                        remote-show-suffix
                        class="w-[280px]"
                    >
                        <el-option
                            v-for="item in getCourseLists.lists"
                            :key="item.id"
                            :value="item.id"
                            :label="item.courseName"
                        >
                            <template #default>
                                <span
                                    style="color: var(--el-text-color-secondary); font-size: 13px"
                                >
                                    {{ item.courseCode }}
                                </span>
                                <span style="margin-left: 8px">{{ item.courseName }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="教师" prop="teacherId">
                    <el-select
                        v-model="queryParams.teacherId"
                        placeholder="请输入教师名称搜索"
                        :remote="true"
                        :remote-method="handleTeacherRemoteSearch"
                        :loading="teacherSearchLoading"
                        filterable
                        clearable
                        remote-show-suffix
                        class="w-[280px]"
                    >
                        <el-option
                            v-for="item in getTeacherLists.lists"
                            :key="item.id"
                            :value="item.id"
                            :label="item.name"
                        >
                            <template #default>
                                <span
                                    style="color: var(--el-text-color-secondary); font-size: 13px"
                                >
                                    {{ item.teacherCode }}
                                </span>
                                <span style="margin-left: 8px">{{ item.name }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <div>
                <el-button v-perms="['task:add']" type="primary" @click="handleAdd()">
                    <template #icon>
                        <icon name="el-icon-Plus" />
                    </template>
                    新增
                </el-button>
            </div>
            <el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="教学任务业务编号" prop="taskCode" min-width="280" />
                <el-table-column label="学期" prop="semesterName" min-width="210" />
                <el-table-column label="课程" prop="courseName" min-width="100" />
                <el-table-column label="教师" prop="teacherName" min-width="100" />
                <el-table-column label="班级" prop="className" min-width="100" />
                <el-table-column label="周学时" prop="weeklyHours" min-width="100" />
                <el-table-column label="总周数" prop="totalWeeks" min-width="100" />
                <el-table-column label="状态" prop="status" min-width="100" />
                <el-table-column label="备注" prop="remark" min-width="100" />
                <el-table-column label="创建人" prop="createrName" min-width="100" />
                <el-table-column label="创建时间" prop="createdTime" min-width="100" />
                <el-table-column label="最后更新人" prop="updaterName" min-width="100" />
                <el-table-column label="最后更新时间" prop="updatedTime" min-width="100" />
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-perms="['task:edit']"
                            type="primary"
                            link
                            @click="handleEdit(row)"
                        >
                            编辑
                        </el-button>
                        <el-button
                            v-perms="['task:del']"
                            type="danger"
                            link
                            @click="handleDelete(row.id)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <edit-popup v-if="showEdit" ref="editRef" @success="getLists" @close="showEdit = false" />
    </div>
</template>
<script lang="ts" setup name="task">
import { classDetail } from '@/api/class'
import { configLists } from '@/api/config'
import { courseLists } from '@/api/course'
import { taskDelete, taskLists, taskSearch } from '@/api/task'
import { teacherLists } from '@/api/teacher'
import { timeNextSemester } from '@/api/time'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'

import EditPopup from './edit.vue'
const getConfigLists = ref<{
    lists: Array<{ id: number; academicYear: string; semesterCode: string; config: string }>
}>({ lists: [] })
const getCourseLists = ref<{
    lists: Array<{ id: number; courseName: string; courseCode: string }>
}>({ lists: [] })
const getTeacherLists = ref<{
    lists: Array<{ id: number; name: string; teacherCode: string }>
}>({ lists: [] })

const courseSearchLoading = ref(false)
const courseSearchTimer = ref<number | null>(null)
const teacherSearchLoading = ref(false)
const teacherSearchTimer = ref<number | null>(null)

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const showEdit = ref(false)
const route = useRoute()
const queryParams = reactive({
    taskCode: '',
    semesterId: '',
    courseId: '',
    teacherId: '',
    classId: Number(route.query.classId) || null,
    weeklyHours: '',
    totalWeeks: '',
    createdBy: '',
    updatedBy: ''
})
const classData = reactive({
    classCode: '',
    className: '',
    classProgress: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: taskLists,
    params: queryParams
})

const fetchConfigLists = async () => {
    try {
        const res = await configLists()
        const handleData = JSON.parse(JSON.stringify(res))
        handleData.lists = handleData.lists.map((item: any) => ({
            ...item,
            config: `${item.academicYear}${item.semesterCode == 'SPRING' ? ' 春' : ' 秋'}`
        }))
        getConfigLists.value = handleData
        await fetchSemester()
    } catch (err) {
        feedback.msgError('获取学期列表失败')
    }
}
const fetchSemester = async () => {
    try {
        const res = await timeNextSemester()
        console.log('res',res)
        if (res) {
            queryParams.semesterId = res.id
            console.log('semesterId',queryParams.semesterId)
            await getClassDetail()
            await getLists()
        }
    } catch (error) {
        console.error('获取学期信息失败', error)
    }
}

const fetchCourseLists = async (params: string) => {
    try {
        const res = await courseLists({
            courseName: params.trim() // 搜索关键词
        })
        getCourseLists.value = res
    } catch (err) {
        feedback.msgError('获取课程列表失败')
        getCourseLists.value = { lists: [] } // 失败时清空列表
    } finally {
        courseSearchLoading.value = false // 关闭加载状态
    }
}
const handleCourseRemoteSearch = (keyword: string) => {
    if (courseSearchTimer.value) clearTimeout(courseSearchTimer.value)

    courseSearchTimer.value = setTimeout(async () => {
        courseSearchLoading.value = true
        await fetchCourseLists(keyword)
    }, 300)
}

const fetchTeacherLists = async (params: string) => {
    try {
        const res = await teacherLists({
            name: params.trim() // 搜索关键词
        })
        getTeacherLists.value = res
    } catch (err) {
        feedback.msgError('获取教师列表失败')
        getTeacherLists.value = { lists: [] } // 失败时清空列表
    } finally {
        teacherSearchLoading.value = false // 关闭加载状态
    }
}
const handleTeacherRemoteSearch = (keyword: string) => {
    if (teacherSearchTimer.value) clearTimeout(teacherSearchTimer.value)

    teacherSearchTimer.value = setTimeout(async () => {
        teacherSearchLoading.value = true
        await fetchTeacherLists(keyword)
    }, 300)
}

onBeforeUnmount(() => {
    if (courseSearchTimer.value) clearTimeout(courseSearchTimer.value)
    if (teacherSearchTimer.value) clearTimeout(teacherSearchTimer.value)
})

const getClassDetail = async () => {
    try {
        console.log('route.query.classId', route.query.classId)
        const res = await classDetail({id: Number(route.query.classId)})
        classData.classCode = res.classCode
        classData.className = res.className
        console.log('queryParams.semesterId',queryParams.semesterId)
        const progressRes = await taskSearch({
            classId: Number(route.query.classId),
            semesterId: queryParams.semesterId
        })
        console.log('progressRes', progressRes)
        classData.classProgress = progressRes.arrangementProgress || '暂无进度信息'
    } catch (err) {
        feedback.msgError('获取班级详情失败')
        return null
    }
}

const formatClassProgress = (cellValue: any) => {
    const statusMap: Record<string, string> = {
        draft: '草稿',
        confirmed: '确认',
        published: '发布',
        archived: '归档',
        default: '默认'
    }
    return statusMap[String(cellValue)] || cellValue
}

const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
    editRef.value?.getClassDetail(Number(route.query.classId))
}

const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.getDetail(data)
}

const handleDelete = async (id: number) => {
    await feedback.confirm('确定要删除？')
    await taskDelete({ id })
    feedback.msgSuccess('删除成功')
    getLists()
}

fetchConfigLists()
fetchCourseLists('')
fetchTeacherLists('')
</script>
