<template>
	<div class="student-details-page">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<a-input
				v-model:value="searchForm.queryInfo"
				placeholder="姓名/学号/手机"
				style="width: 180px; margin-right: 12px"
			/>
			<a-select v-model:value="searchForm.gender" placeholder="选择学生性别" style="width: 150px; margin-right: 12px">
				<a-select-option value="男">男</a-select-option>
				<a-select-option value="女">女</a-select-option>
			</a-select>
			<a-select v-model:value="searchForm.userStatus" placeholder="请选择状态" style="width: 120px; margin-right: 12px">
				<a-select-option v-for="(item, index) in statusOptions" :key="index" :value="item.value">{{
					item.label
				}}</a-select-option>
			</a-select>
			<a-range-picker
				@change="handleDateChange"
				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-upload
				name="file"
				:showUploadList="false"
				:beforeUpload="beforeUpload"
				:customRequest="customRequest"
				accept=".xlsx,.xls"
			>
				<a-button>导入</a-button>
			</a-upload>
			<a-button style="margin-left: 10px" @click="downloadImport">下载导入模板</a-button>
		</div>
		<!-- 表格 -->
		<a-table
			:columns="columns"
			:row-key="rowKey"
			:data-source="pagedDatas"
			:pagination="false"
			:row-selection="rowSelection"
			:scroll="{ x: 1000, y: 320 }"
			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-popconfirm title="删除此条目？" @confirm="onDelete(record)">
							<a-button size="small" danger>删除</a-button>
						</a-popconfirm>
					</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="total"
				@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"
		>
			<studentSelection
				:studentIds="studentIdss"
				@close="handleAddStudentCancel"
				@confirm="confirmStudent"
			></studentSelection>
		</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.ACCOUNT }}</td>
						<td>{{ detailData.userIdName }}</td>
						<td>{{ detailData.phone }}</td>
						<td>{{ detailData.gender }}</td>
					</tr>
					<tr>
						<th>所在院系</th>
						<th>所在班级</th>
						<th>生日</th>
						<th>所在城市</th>
					</tr>
					<tr>
						<td>{{ detailData.orgIdName }}</td>
						<td>{{ detailData.className }}</td>
						<td>{{ detailData.birth }}</td>
						<td>{{ detailData.city }}</td>
					</tr>
					<tr>
						<th>学籍状态</th>
						<th>在线状态</th>
						<th>注册时间</th>
						<th>最后登录</th>
					</tr>
					<tr>
						<td>{{ detailData.userStatusName }}</td>
						<td>{{ detailData.isLoginName }}</td>
						<td>{{ detailData.createTime }}</td>
						<td>{{ detailData.latestLoginTime }}</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, reactive, computed, onMounted, unref} from 'vue'
	import { message } from 'ant-design-vue'
	import { DownOutlined } from '@ant-design/icons-vue'
	import { getDepartmentMembers } from '@/api/course/courseDetail'
	import studentDetailsApi from '@/api/courseCenter/studentDetails.js'
	import { getStudentDetail } from '@/api/course/courseDetail'
	import studentSelection from './studentSelection.vue'
	import tool from '@/utils/tool'
	const props = defineProps({
		//课程id
		courseInfoId: {
			type: Number,
			required: true,
			default: null
		}
	})
	// 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 ? '男' : '女',
			userStatus: '启用',
			phone: '18088889999',
			online: true,
			lastLogin: '2020-11-25 23:26:08'
		}))
	])

	const searchForm = reactive({
		queryInfo: null,
		gender: null,
		userStatus: null,
		date: [],
		startTime: null, // 新增开始时间字段
		endTime: null // 新增结束时间字段
	})

	const columns = [
		{ title: '学员编号', dataIndex: 'ACCOUNT', align: 'center' },
		{ title: '姓名', dataIndex: 'userIdName', align: 'center' },
		{ title: '性别', dataIndex: 'gender', align: 'center' },
		{ title: '账号状态', dataIndex: 'userStatusName', align: 'center' },
		{ title: '手机号', dataIndex: 'phone', align: 'center' },
		{ title: '在线状态', dataIndex: 'isLoginName', align: 'center' },
		{ title: '最后登录', dataIndex: 'latestLoginTime', align: 'center' },
		{ title: '操作', dataIndex: 'actions', fixed: 'right', align: 'center', width: 220 }
	]
	const studentIdss = ref([]) //学员回显id
	const statusOptions = tool.dictList('COMMON_STATUS') //学员状态
	const currentPage = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	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 pagedDatas = ref([])
	const rowKey = (record) => record.relateId

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

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

	const rowSelection = computed(() => {
		return {
			selectedRowKeys: unref(selectedRowKeys),
			onChange: (changeRowKeys) => {
				console.log(changeRowKeys, 'changeRowKeyschangeRowKeys')
				selectedRowKeys.value = changeRowKeys
			},
			hideDefaultSelections: true,
		}
	})
	//添加学员确认
	const confirmStudent = (StudentIds) => {
		console.log(StudentIds, '学员id')
		addStudentVisible.value = false
		searchForm.StudentIds = StudentIds.join(',')
		let params = {
			userIds: searchForm.StudentIds,
			courseId: props.courseInfoId
		}
		studentDetailsApi
			.add(params)
			.then((res) => {
				console.log(res, '学员添加')
				getList()
			})
			.catch((err) => {
				console.log(err)
			})
	}
	function onSearch() {
		currentPage.value = 1
		console.log(searchForm, '搜索参数')
		getList()
	}
	const getList = () => {
		const params = {
			queryInfo: searchForm.queryInfo,
			gender: searchForm.gender,
			userStatus: searchForm.userStatus,
			latestLoginStartTime: searchForm.startTime,
			latestLoginEndTime: searchForm.endTime,
			current: currentPage.value,
			size: pageSize.value,
			courseId: props.courseInfoId
		}
		studentDetailsApi
			.queryList(params)
			.then((res) => {
				console.log(res, '学院列表')
				pagedDatas.value = res.data.records
				total.value = res.data.total
			})
			.catch((err) => {
				console.log(err)
			})
	}
	function handleDateChange(dates, dateStrings) {
		// dates 是 Moment 对象数组，dateStrings 是格式化后的字符串数组
		if (dates && dates.length === 2) {
			searchForm.startTime = dateStrings[0] // 开始时间字符串
			searchForm.endTime = dateStrings[1] // 结束时间字符串
		} else {
			searchForm.startTime = null
			searchForm.endTime = null
		}
	}
	const importLoading = ref(false)
	// 文件上传前校验
	const beforeUpload = (file) => {
		const isExcel = file.type.includes('excel') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
		if (!isExcel) {
			message.error('只能上传Excel文件!')
			return false
		}
		return true
	}
	// 自定义上传实现
	const customRequest = async (options) => {
		const { file, onSuccess, onError } = options
		importLoading.value = true
		try {
			const formData = new FormData()
			formData.append('file', file)
			formData.append('courseId', props.courseInfoId)
			// 调用API接口
			const res = await studentDetailsApi.importStudents(formData)
			console.log(res)
			message.info(
				`成功导入 ${res.data.successCount} 条数据,导入失败:${
					res.data.errorCount
				} 条数据,失败下标为: ${res.data.errorDetail.map((item) => item.index).join(',')}`
			)
			onSuccess(res, file)
			getList() // 刷新列表
		} catch (error) {
			console.log(error)
			message.error(`导入失败: ${error}`)
			onError(error)
		} finally {
			importLoading.value = false
		}
	}
	function onReset() {
		searchForm.queryInfo = null
		searchForm.gender = null
		searchForm.userStatus = null
		searchForm.startTime = null
		searchForm.date = null
		searchForm.endTime = null
		currentPage.value = 1
		getList()
	}
	function onPageChange(page) {
		currentPage.value = page
		getList()
	}
	function onPageSizeChange(size) {
		pageSize.value = size
		currentPage.value = 1
		getList()
	}
	function onSelectAll() {
		console.log(pagedDatas.value)
		selectedRowKeys.value = pagedDatas.value.map((item) => item.relateId)
	}
	function onInvertSelect() {
		const currentIds = pagedDatas.value.map((item) => item.relateId)
		selectedRowKeys.value = currentIds.filter((id) => !selectedRowKeys.value.includes(id))
	}
	function onAddStudent() {
		addStudentVisible.value = true
		// 默认展开所有部门
		// expandedDeptIds.value = departments.value.map((d) => d.id)
	}
	function downloadImport() {
		studentDetailsApi
			.downloadImportlate()
			.then((res) => {
				console.log(res.data, 'messagemessagemessage')
				// 创建 blob 对象
				const blob = new Blob([res.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				// 创建下载链接
				const downloadUrl = window.URL.createObjectURL(blob)
				const link = document.createElement('a')
				link.href = downloadUrl

				// 设置下载文件名（可以从响应头获取或固定）
				link.download = '学生导入模板.xlsx'

				// 触发下载
				document.body.appendChild(link)
				link.click()

				// 清理
				window.URL.revokeObjectURL(downloadUrl)
				document.body.removeChild(link)
			})
			.catch((err) => {
				message.error('模板下载失败: ' + (err || err))
				console.error(err)
			})
	}
	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()
		getList()
	})
	function onDetail(record) {
		detailVisible.value = true
		let params = {
			id: record.relateId
		}
		studentDetailsApi
			.detail(params)
			.then((res) => {
				console.log(res, '学员详情')
				detailData.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	function onEdit(record) {
		// TODO: 编辑弹窗
	}
	function onSetting(record) {
		// TODO: 设置弹窗
	}
	function onDelete(record) {
		let params = [
			{
				id: record.relateId
			}
		]
		studentDetailsApi
			.delete(params)
			.then((res) => {
				console.log(res, '删除学员')
				getList()
			})
			.catch((err) => {
				console.log(err)
			})
	}
</script>

<style lang="less" scoped>
	.student-details-page {
		background: #fff;
		border-radius: 12px;
		width: 1200px;
		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>
