<template>
	<div class="student-details-page">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<a-input
				v-model:value="searchForm.keyword"
				placeholder="姓名/学号/手机"
				style="width: 180px; margin-right: 12px"
			/>
			<a-select v-model:value="searchForm.type" placeholder="选择学生类型" style="width: 150px; margin-right: 12px">
				<a-select-option value="">全部类型</a-select-option>
				<a-select-option value="普通">普通</a-select-option>
				<a-select-option value="VIP">VIP</a-select-option>
			</a-select>
			<a-select v-model:value="searchForm.status" placeholder="状态选项" style="width: 120px; margin-right: 12px">
				<a-select-option value="">全部状态</a-select-option>
				<a-select-option value="启用">启用</a-select-option>
				<a-select-option value="禁用">禁用</a-select-option>
			</a-select>
			<a-range-picker v-model:value="searchForm.date" style="margin-right: 12px; width: 240px" />
			<a-button type="primary" @click="onSearch" style="margin-right: 8px">查询</a-button>
			<a-button @click="onReset">重置</a-button>
		</div>
		<!-- 操作按钮 -->
		<div class="action-bar">
			<a-button type="primary" @click="onAddStudent" style="margin-right: 8px">+ 新增学员</a-button>
			<a-button>导入导出</a-button>
		</div>
		<!-- 表格 -->
		<a-table
			row-key="id"
			:columns="columns"
			:data-source="pagedData"
			:pagination="false"
			:row-selection="rowSelection"
			bordered
			class="student-table"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'status'">
					<span>
						<a-badge status="success" v-if="record.status === '启用'" text="启用" />
						<a-badge status="default" v-else text="禁用" />
					</span>
				</template>
				<template v-else-if="column.dataIndex === 'online'">
					<span>
						<a-badge status="success" v-if="record.online" text="在线" />
						<a-badge status="default" v-else text="离线" />
					</span>
				</template>
				<template v-else-if="column.dataIndex === 'actions'">
					<a-space>
						<a-button size="small" @click="onDetail(record)">详情</a-button>
						<a-button size="small" @click="onEdit(record)">编辑</a-button>
						<a-button size="small" @click="onSetting(record)">设置</a-button>
						<a-button size="small" danger @click="onDelete(record)">删除</a-button>
					</a-space>
				</template>
			</template>
		</a-table>
		<!-- 批量操作和分页 -->
		<div class="table-footer">
			<div class="batch-actions">
				<a-button @click="onSelectAll">选择全部</a-button>
				<a-button @click="onInvertSelect">反向选择</a-button>
				<a-dropdown>
					<a-button>更多操作 <DownOutlined /></a-button>
					<template #overlay>
						<a-menu>
							<a-menu-item>批量启用</a-menu-item>
							<a-menu-item>批量禁用</a-menu-item>
							<a-menu-item>批量删除</a-menu-item>
						</a-menu>
					</template>
				</a-dropdown>
			</div>
			<a-pagination
				:current="currentPage"
				:page-size="pageSize"
				:total="filteredData.length"
				@change="onPageChange"
				show-quick-jumper
				:show-total="(total) => `共${total}条`"
				style="margin-left: auto"
			/>
			<a-select v-model:value="pageSize" style="width: 100px; margin-left: 16px" @change="onPageSizeChange">
				<a-select-option :value="10">10/页</a-select-option>
				<a-select-option :value="20">20/页</a-select-option>
				<a-select-option :value="50">50/页</a-select-option>
			</a-select>
		</div>
		<!-- 新增学员弹窗 -->
		<a-modal
			v-model:visible="addStudentVisible"
			title="新增学员"
			width="720px"
			:footer="null"
			@cancel="handleAddStudentCancel"
		>
			<div class="add-student-modal">
				<!-- 左侧部门成员树 -->
				<div class="left-panel">
<!--					<a-input-->
<!--						v-model:value="searchDeptMember"-->
<!--						placeholder="输入部门名称"-->
<!--						allow-clear-->
<!--						class="search-input"-->
<!--						@input="onDeptMemberSearch"-->
<!--					/>-->
					<div class="dept-list">
						<template v-for="dept in filteredDepartments" :key="dept.id">
							<div class="dept-name" @click="toggleDept(dept.id)">
								<DownOutlined v-if="expandedDeptIds.includes(dept.id)" style="margin-right: 4px" />
								<RightOutlined v-else style="margin-right: 4px" />
								{{ dept.name }}
							</div>
							<div v-if="expandedDeptIds.includes(dept.id)" class="member-list">
								<a-checkbox-group :value="checkedMemberIds" @change="onMemberCheckChange">
									<div v-for="member in dept.members" :key="member.id" class="member-item">
										<a-checkbox :value="member.id" :disabled="isCheckedLimit(member.id)">
											<UserOutlined style="margin-right: 4px" />{{ member.name }}
										</a-checkbox>
									</div>
								</a-checkbox-group>
							</div>
						</template>
					</div>
				</div>
				<!-- 右侧已选成员列表 -->
				<div class="right-panel">
					<div class="selected-header">
						已选 {{ selectedMembers.length }}/30
						<a @click="clearSelected" style="float: right; color: #1890ff">清空</a>
					</div>
					<div class="selected-list">
						<div v-for="member in selectedMembers" :key="member.id" class="selected-item">
							<UserOutlined style="margin-right: 4px" />{{ member.name }}
							<CloseOutlined class="remove-icon" @click="removeSelected(member.id)" />
						</div>
					</div>
				</div>
			</div>
			<div class="modal-footer">
				<a-button @click="handleAddStudentCancel">取消</a-button>
				<a-button type="primary" @click="handleAddStudentOk">确定</a-button>
			</div>
		</a-modal>
		<!-- 详情弹窗 -->
		<a-modal
			v-model:visible="detailVisible"
			title="个人实名认证"
			width="900px"
			:footer="null"
			@cancel="() => (detailVisible = false)"
		>
			<div class="student-detail-modal">
				<a-table
					:pagination="false"
					:show-header="false"
					:data-source="[detailData]"
					:columns="[{ title: '', dataIndex: 'id', key: 'id' }]"
					style="display: none"
				/>
				<table class="detail-table">
					<tr>
						<th>ID编号</th>
						<th>学生姓名</th>
						<th>手机号码</th>
						<th>性别</th>
					</tr>
					<tr>
						<td>{{ detailData.id }}</td>
						<td>{{ detailData.name }}</td>
						<td>{{ detailData.phone }}</td>
						<td>{{ detailData.gender }}</td>
					</tr>
					<tr>
						<th>所在院系</th>
						<th>所在班级</th>
						<th>生日</th>
						<th>所在城市</th>
					</tr>
					<tr>
						<td>{{ detailData.college }}</td>
						<td>{{ detailData.className }}</td>
						<td>{{ detailData.birthday }}</td>
						<td>{{ detailData.city }}</td>
					</tr>
					<tr>
						<th>学籍状态</th>
						<th>在线状态</th>
						<th>注册时间</th>
						<th>最后登录</th>
					</tr>
					<tr>
						<td>{{ detailData.educationStatus }}</td>
						<td>{{ detailData.onlineStatus }}</td>
						<td>{{ detailData.registerTime }}</td>
						<td>{{ detailData.lastLogin }}</td>
					</tr>
				</table>
				<div class="modal-btn-bar">
					<a-button type="primary" style="width: 120px; margin-top: 24px" @click="() => (detailVisible = false)">
						关闭</a-button
					>
				</div>
			</div>
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { DownOutlined } from '@ant-design/icons-vue'
	import { getDepartmentMembers } from '@/api/course/courseDetail'
	import { getStudentDetail } from '@/api/course/courseDetail'

	// mock数据
	const allStudents = ref([
		// 生成20条mock数据
		...Array.from({ length: 20 }).map((_, i) => ({
			id: i + 1,
			studentNo: 'xy' + String(100000 + i),
			name: '张小刚',
			gender: i % 2 === 0 ? '男' : '女',
			status: '启用',
			phone: '18088889999',
			online: true,
			lastLogin: '2020-11-25 23:26:08'
		}))
	])

	const searchForm = ref({
		keyword: '',
		type: '',
		status: '',
		date: []
	})

	const columns = [
		{ title: '学号', dataIndex: 'studentNo', align: 'center' },
		{ title: '姓名', dataIndex: 'name', align: 'center' },
		{ title: '性别', dataIndex: 'gender', align: 'center' },
		{ title: '账号状态', dataIndex: 'status', align: 'center' },
		{ title: '手机', dataIndex: 'phone', align: 'center' },
		{ title: '在线状态', dataIndex: 'online', align: 'center' },
		{ title: '最后登录', dataIndex: 'lastLogin', align: 'center' },
		{ title: '操作', dataIndex: 'actions', align: 'center', width: 220 }
	]

	const currentPage = ref(1)
	const pageSize = ref(10)
	const selectedRowKeys = ref([])

	const addStudentVisible = ref(false)
	const departments = ref([])
	const searchDeptMember = ref('')
	const expandedDeptIds = ref([])
	const checkedMemberIds = ref([])
	const selectedMembers = ref([])

	const detailVisible = ref(false)
	const detailData = ref({})

	const filteredData = computed(() => {
		let data = allStudents.value
		if (searchForm.value.keyword) {
			data = data.filter(
				(item) =>
					item.name.includes(searchForm.value.keyword) ||
					item.studentNo.includes(searchForm.value.keyword) ||
					item.phone.includes(searchForm.value.keyword)
			)
		}
		if (searchForm.value.status) {
			data = data.filter((item) => item.status === searchForm.value.status)
		}
		// 这里可以加更多筛选条件
		return data
	})

	const pagedData = computed(() => {
		const start = (currentPage.value - 1) * pageSize.value
		return filteredData.value.slice(start, start + pageSize.value)
	})

	const rowSelection = {
		selectedRowKeys: selectedRowKeys.value,
		onChange: (keys) => {
			selectedRowKeys.value = keys
		}
	}

	function onSearch() {
		currentPage.value = 1
	}
	function onReset() {
		searchForm.value = { keyword: '', type: '', status: '', date: [] }
		currentPage.value = 1
	}
	function onPageChange(page) {
		currentPage.value = page
	}
	function onPageSizeChange(size) {
		pageSize.value = size
		currentPage.value = 1
	}
	function onSelectAll() {
		selectedRowKeys.value = pagedData.value.map((item) => item.id)
	}
	function onInvertSelect() {
		const currentIds = pagedData.value.map((item) => item.id)
		selectedRowKeys.value = currentIds.filter((id) => !selectedRowKeys.value.includes(id))
	}
	function onAddStudent() {
		addStudentVisible.value = true
		// 默认展开所有部门
		expandedDeptIds.value = departments.value.map((d) => d.id)
	}
	function handleAddStudentCancel() {
		addStudentVisible.value = false
	}
	function handleAddStudentOk() {
		// TODO: 选中成员加入主表
		addStudentVisible.value = false
	}
	function onDeptMemberSearch() {
		// 搜索时自动展开所有部门
		expandedDeptIds.value = filteredDepartments.value.map((d) => d.id)
	}
	function toggleDept(id) {
		if (expandedDeptIds.value.includes(id)) {
			expandedDeptIds.value = expandedDeptIds.value.filter((did) => did !== id)
		} else {
			expandedDeptIds.value.push(id)
		}
	}
	function onMemberCheckChange(ids) {
		// 限制最多30人
		if (ids.length > 30) {
			ids = ids.slice(0, 30)
		}
		checkedMemberIds.value = ids
		updateSelectedMembers()
	}
	function isCheckedLimit(id) {
		return checkedMemberIds.value.length >= 30 && !checkedMemberIds.value.includes(id)
	}
	function updateSelectedMembers() {
		// 根据 checkedMemberIds 更新 selectedMembers
		const all = []
		departments.value.forEach((dept) => {
			dept.members.forEach((m) => all.push({ ...m, deptName: dept.name }))
		})
		selectedMembers.value = all.filter((m) => checkedMemberIds.value.includes(m.id))
	}
	function removeSelected(id) {
		checkedMemberIds.value = checkedMemberIds.value.filter((mid) => mid !== id)
		updateSelectedMembers()
	}
	function clearSelected() {
		checkedMemberIds.value = []
		updateSelectedMembers()
	}
	const filteredDepartments = computed(() => {
		if (!searchDeptMember.value) return departments.value
		// 部门名或成员名匹配
		return departments.value
			.map((dept) => {
				const matchDept = dept.name.includes(searchDeptMember.value)
				const filteredMembers = dept.members.filter((m) => m.name.includes(searchDeptMember.value))
				if (matchDept || filteredMembers.length) {
					return {
						...dept,
						members: matchDept ? dept.members : filteredMembers
					}
				}
				return null
			})
			.filter(Boolean)
	})
	onMounted(async () => {
		departments.value = await getDepartmentMembers()
	})
	function onDetail(record) {
		getStudentDetail().then((data) => {
			detailData.value = data
			detailVisible.value = true
		})
	}
	function onEdit(record) {
		// TODO: 编辑弹窗
	}
	function onSetting(record) {
		// TODO: 设置弹窗
	}
	function onDelete(record) {
		// TODO: 删除确认
	}
</script>

<style lang="less" scoped>
	.student-details-page {
		background: #fff;
		border-radius: 12px;
		margin: 0 auto;
		padding: 32px 32px 24px 32px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
		height: calc(100vh - 400px);
		overflow: auto;
		.search-bar {
			display: flex;
			align-items: center;
			margin-bottom: 18px;
		}
		.action-bar {
			margin-bottom: 16px;
			display: flex;
			align-items: center;
		}
		.student-table {
			margin-bottom: 12px;
			.ant-table-thead > tr > th {
				background: #f7f8fa;
				font-weight: 600;
				color: #222;
				font-size: 15px;
			}
			.ant-table-tbody > tr > td {
				font-size: 14px;
				color: #333;
			}
			.ant-btn {
				font-size: 13px;
				padding: 0 10px;
				border-radius: 4px;
			}
			.ant-btn-dangerous {
				background: #fff1f0;
				color: #ff4d4f;
				border: 1px solid #ffccc7;
			}
		}
		.table-footer {
			display: flex;
			align-items: center;
			margin-top: 12px;
			.batch-actions {
				display: flex;
				align-items: center;
				gap: 8px;
			}
		}
	}
	.add-student-modal {
		display: flex;
		min-height: 400px;
		.left-panel {
			width: 320px;
			border-right: 1px solid #f0f0f0;
			padding-right: 16px;
			.search-input {
				margin-bottom: 12px;
			}
			.dept-list {
				max-height: 340px;
				overflow-y: auto;
			}
			.dept-name {
				font-weight: 600;
				margin: 8px 0 4px 0;
				cursor: pointer;
				display: flex;
				align-items: center;
			}
			.member-list {
				margin-left: 20px;
				margin-bottom: 8px;
			}
			.member-item {
				margin: 4px 0;
				display: flex;
				align-items: center;
			}
		}
		.right-panel {
			flex: 1;
			padding-left: 24px;
			.selected-header {
				font-weight: 600;
				margin-bottom: 8px;
			}
			.selected-list {
				min-height: 340px;
				max-height: 340px;
				overflow-y: auto;
				.selected-item {
					display: flex;
					align-items: center;
					background: #f5f5f5;
					border-radius: 4px;
					padding: 4px 8px;
					margin-bottom: 6px;
					.remove-icon {
						margin-left: auto;
						color: #999;
						cursor: pointer;
					}
				}
			}
		}
	}
	.modal-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 18px;
	}
	.student-detail-modal {
		.detail-table {
			width: 100%;
			border-collapse: collapse;
			margin-bottom: 0;
			th,
			td {
				border: 1px solid #e8e8e8;
				padding: 12px 16px;
				text-align: left;
				font-size: 15px;
				background: #fff;
			}
			th {
				background: #fafafa;
				font-weight: 600;
				color: #222;
			}
			tr:not(:first-child) td {
				color: #333;
			}
		}
		.modal-btn-bar {
			text-align: center;
		}
	}
</style>
