<template>
    <div class="index-lists">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="报名编号" prop="applicationNumber">
                    <el-input class="w-[280px]" v-model="queryParams.applicationNumber" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input class="w-[280px]" v-model="queryParams.name" />
                </el-form-item>
                <el-form-item label="审核状态" prop="approvalStatus">
                    <el-select
                        v-model="queryParams.approvalStatus"
                        class="w-[280px]"
                        clearable
                        @change="getLists()"
                    >
                        <el-option label="待审核" :value="0" />
                        <el-option label="已审核" :value="1" />
                        <el-option label="审核不通过" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="报名时间" prop="applicationTime">
                    <daterange-picker
                        v-model:startTime="queryParams.applicationTimeStart"
                        v-model:endTime="queryParams.applicationTimeEnd"
                    />
                </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 class="flex mb-4">
                <el-button
                    v-perms="['stuRegistration/edit']"
                    @click="handleBatchApproval(0)"
                    :disabled="selectedIds.length === 0"
                >
                    批量撤销
                </el-button>
                <el-button
                    v-perms="['stuRegistration/edit']"
                    type="success"
                    @click="handleBatchApproval(1)"
                    :disabled="selectedIds.length === 0"
                >
                    批量通过
                </el-button>
                <el-button
                    v-perms="['stuRegistration/edit']"
                    type="danger"
                    @click="handleBatchApproval(2)"
                    :disabled="selectedIds.length === 0"
                    class="ml-2"
                >
                    批量拒绝
                </el-button>
            </div>
            <el-table
                ref="tableRef"
                class="mt-4"
                size="large"
                v-loading="pager.loading"
                :data="pager.lists"
                @selection-change="handleSelectionChange"
                border
            >
                <el-table-column type="selection" width="55" />
                <el-table-column label="报名编号" min-width="100">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            link
                            @click="handleShowDetail(row.baseInfoId)"
                            style="text-decoration: underline"
                        >
                            {{ row.applicationNumber }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="name" min-width="100" />
                <el-table-column
                    label="性别"
                    prop="gender"
                    min-width="100"
                    :formatter="formatGender"
                />
                <el-table-column label="籍贯" prop="nativePlace" min-width="100" />
                <el-table-column
                    label="审核状态"
                    prop="approvalStatus"
                    min-width="100"
                    :formatter="formatRegistrationStatus"
                />
                <el-table-column label="报名时间" prop="applicationTime" min-width="100" />
                <el-table-column label="操作" width="240" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-perms="['stuRegistration/edit']"
                            @click="handleRoEdit(row)"
                            :disabled="row.approvalStatus == 0"
                        >
                            撤销
                        </el-button>
                        <el-button
                            v-perms="['stuRegistration/edit']"
                            type="success"
                            @click="handleYesEdit(row)"
                            :disabled="row.approvalStatus != 0"
                        >
                            通过
                        </el-button>
                        <el-button
                            v-perms="['stuRegistration/edit']"
                            type="danger"
                            @click="handleNoEdit(row)"
                            :disabled="row.approvalStatus != 0"
                        >
                            拒绝
                        </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" />
        <base-popup ref="detailRef" />
    </div>
</template>
<script lang="ts" setup name="stuRegistration">
import {
    stuRegistrationRegistration,
    stuRegistrationRegistrationLists
} from '@/api/stuRegistration'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'

import BasePopup from '../Base.vue'
import EditPopup from './edit.vue'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const detailRef = shallowRef<InstanceType<typeof BasePopup>>()
const showEdit = ref(false)
const queryParams = reactive({
    name: '',
    baseInfoId: '',
    approvalStatus: '',
    applicationNumber: '',
    rejectionReason: '',
    admissionStatus: '',
    paymentStatus: '',
    registrationStatus: 0,
    applicationTimeStart: '',
    applicationTimeEnd: ''
})

const formData = reactive({
    id: [] as number[],
    operation: 0,
    reason: ''
})

const formatRegistrationStatus = (row: any, column: any, cellValue: any) => {
    const statusMap: Record<string | number, string> = {
        '0': '待审核',
        '1': '已审核',
        '2': '审核不通过'
    }
    const statusText = statusMap[String(cellValue)] || cellValue
    // 当审核状态为2（不通过）时，显示拒绝原因
    if (cellValue === 2 && row.rejectionReason) {
        return `${statusText} ： ${row.rejectionReason}`
    }
    return statusText
}

const formatGender = (value: number) => {
    const map: Record<number, string> = {
        0: '未知',
        1: '男',
        2: '女'
    }
    return map[value] || '未知'
}

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

// 存储所有选中的学生ID（跨分页）
const selectedIds = ref<number[]>([])

// 处理表格选择变化（同步跨分页选中状态）
const handleSelectionChange = (rows: any[]) => {
    const currentPageSelectedIds = rows.map((row) => row.id)
    const currentPageAllIds = pager.lists.map((row) => row.id)
    currentPageAllIds.forEach((id) => {
        if (!currentPageSelectedIds.includes(id)) {
            const index = selectedIds.value.indexOf(id)
            if (index > -1) {
                selectedIds.value.splice(index, 1)
            }
        }
    })

    currentPageSelectedIds.forEach((id) => {
        if (!selectedIds.value.includes(id)) {
            selectedIds.value.push(id)
        }
    })
}

// 表格实例引用
const tableRef = shallowRef<any>(null)

// 初始化选中状态（分页切换后回显）
const initSelection = async () => {
    await nextTick()
    if (!tableRef.value || !pager.lists.length) return
    tableRef.value.clearSelection()
    pager.lists.forEach((row: any) => {
        if (selectedIds.value.includes(row.id)) {
            tableRef.value.toggleRowSelection(row, true)
        }
    })
}

// 监听表格数据变化（分页切换/刷新后触发）
watch(
    () => pager.lists,
    () => {
        initSelection()
    },
    { deep: true }
)

// 批量审核处理
const handleBatchApproval = async (operation: number) => {
    let validIds: number[] = []
    let tipText = ''
    // 根据操作类型区分校验规则
    switch (operation) {
        case 0: // 批量撤销：只能操作 已审核(1)/审核不通过(2) 的记录
            validIds = selectedIds.value.filter((id) => {
                const row = pager.lists.find((item: any) => item.id === id)
                return row && row.approvalStatus !== 0
            })
            tipText = '请选择已审核/审核不通过的学生进行撤销'
            break
        case 1: // 批量通过：只能操作 待审核(0) 的记录
            validIds = selectedIds.value.filter((id) => {
                const row = pager.lists.find((item: any) => item.id === id)
                return row && row.approvalStatus === 0
            })
            tipText = '请选择待审核的学生进行通过操作'
            break
        case 2: // 批量拒绝：只能操作 待审核(0) 的记录
            validIds = selectedIds.value.filter((id) => {
                const row = pager.lists.find((item: any) => item.id === id)
                return row && row.approvalStatus === 0
            })
            tipText = '请选择待审核的学生进行拒绝操作'
            break
        default:
            return feedback.msgWarning('不支持的操作类型')
    }

    // 校验选中的有效数据
    if (validIds.length === 0) {
        return feedback.msgWarning(tipText)
    }

    try {
        // 统一接口参数（和edit.vue保持一致，用ids数组）
        await stuRegistrationRegistration({
            id: validIds, // 替换原id为ids，和批量逻辑统一
            operation
        })
        // 操作成功提示
        const operationText = { 0: '撤销', 1: '通过', 2: '拒绝' }[operation]
        feedback.msgSuccess(`批量${operationText}成功`)
        // 清空选中状态 + 刷新列表
        selectedIds.value = []
        getLists()
    } catch (err: any) {
        feedback.msgError(`批量操作失败：${err.message || '服务器异常'}`)
    }
}

const handleShowDetail = async (id: number) => {
    await nextTick()
    detailRef.value?.open(id)
}

const handleRoEdit = async (data: any) => {
    formData.id[0] = data.id
    formData.operation = 0
    const editData: any = { ...formData }
    await stuRegistrationRegistration(editData)
    getLists()
}

const handleYesEdit = async (data: any) => {
    formData.id = [data.id]
    formData.operation = 1
    const editData: any = { ...formData }
    await stuRegistrationRegistration(editData)
    getLists()
}

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

getLists()
</script>
