<template>
	<div class="app-container">

		<div v-if="modeTag == 'list'">
			<!-- 查询表单 -->
			<a-form :model="queryParam" layout="inline" class="search-form">
				<a-form-item label="题目ID：">
					<a-input v-model:value="queryParam.id" placeholder="请输入题目ID" allow-clear />
				</a-form-item>

				<!-- <a-form-item label="年级：">
					<a-select
						v-model:value="queryParam.level"
						placeholder="请选择年级"
						@change="levelChange"
						allow-clear
						style="width: 120px"
					>
						<a-select-option v-for="item in levelEnum" :key="item.key" :value="item.key">
							{{ item.value }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="学科：">
					<a-select v-model:value="queryParam.subjectId" placeholder="请选择学科" allow-clear style="width: 200px">
						<a-select-option v-for="item in subjectFilter" :key="item.id" :value="item.id">
							{{ item.name }} ( {{ item.levelName }} )
						</a-select-option>
					</a-select>
				</a-form-item> -->
				<a-form-item>
					<a-button type="primary" @click="submitForm">查询</a-button>
					<!--				<a-button type="primary" @click="openDrawer('add')" style="margin-left: 8px">添加</a-button>-->
				</a-form-item>
			</a-form>

			<!-- 数据表格 -->
			<a-table
				:loading="listLoading"
				:data-source="tableData"
				:columns="columns"
				:pagination="false"
				row-key="id"
				class="data-table"
				:locale="{ emptyText: '暂无数据' }"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'action'">
						<a-button style="margin-right: 10px" type="primary" @click="handleOk(record)">选择
						</a-button>
						<!--					<a-button size="small" @click="openDrawer('edit', record.id)">编辑</a-button>-->
						<!--					<a-button size="small" type="primary" danger @click="deletePaper(record)" style="margin-left: 8px">-->
						<!--						删除-->
						<!--					</a-button>-->
					</template>
				</template>
			</a-table>

			<!-- 分页 -->
			<a-pagination
				v-if="total > 0"
				:current="queryParam.pageIndex"
				:page-size="queryParam.pageSize"
				:total="total"
				:show-size-changer="true"
				:show-quick-jumper="true"
				:show-total="(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`"
				@change="handlePageChange"
				@show-size-change="handlePageSizeChange"
				class="pagination"
			/>

			<!-- 编辑/添加 抽屉 -->
			<a-drawer
				:visible="drawerVisible"
				:title="drawerTitle"
				placement="right"
				width="900"
				@close="closeDrawer"
				destroyOnClose
			>
				<!--			<FormEdit v-if="drawerVisible" :id="editId" @success="onEditSuccess" />-->
			</a-drawer>
		</div>

		<div v-if="modeTag == 'item'">
			<a-table
				:loading="listLoading"
				:data-source="itemDatas"
				:columns="columns"
				:pagination="false"
				row-key="id"
				class="data-table"
				:locale="{ emptyText: '暂无数据' }"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'action'">
						<a-button style="margin-right: 10px" type="primary" @click="handleReset(record)">重新选择
						</a-button>
						<!--					<a-button size="small" @click="openDrawer('edit', record.id)">编辑</a-button>-->
						<!--					<a-button size="small" type="primary" danger @click="deletePaper(record)" style="margin-left: 8px">-->
						<!--						删除-->
						<!--					</a-button>-->
					</template>
				</template>
			</a-table>
		</div>

	</div>
</template>

<script setup>
	import { ref, reactive, computed, onMounted } from 'vue'
	import { message, Modal } from 'ant-design-vue'
	import { useExamStore } from '@/store/exam'
	import examPaperApi from '@/api/exam/paper/examPaperApi'
	// import FormEdit from './form.vue'
	import { parseTime } from '@/utils/exam'
	const emit = defineEmits(['handlerEx'])
	const examStore = useExamStore()

	const modeTag = ref('list')
	const itemDatas = ref([])
	// 响应式数据
	const queryParam = reactive({
		id: null,
		// level: null,
		// subjectId: null,
		current: 1,
		size: 10
	})

	const subjectFilter = ref([])
	const listLoading = ref(false)
	const tableData = ref([])
	const total = ref(0)

	// Drawer 控制
	const drawerVisible = ref(false)
	const drawerTitle = ref('')
	const editId = ref(null)

	function openDrawer(type, id = null) {
		if (type === 'add') {
			drawerTitle.value = '添加试卷'
			editId.value = null
		} else {
			drawerTitle.value = '编辑试卷'
			editId.value = id
		}
		drawerVisible.value = true
	}
	function closeDrawer() {
		drawerVisible.value = false
	}
	function onEditSuccess() {
		closeDrawer()
		search()
	}
	const open=() =>{
		examStore.initSubject(search)
	}
	// 表格列配置
	const columns = [
		{
			title: 'Id',
			dataIndex: 'id',
			key: 'id',
			width: 90
		},
		{
			title: '学科',
			dataIndex: 'subjectId',
			key: 'subjectId',
			width: 200,
			customRender: ({ text }) => examStore.subjectEnumFormat(text)
		},
		{
			title: '名称',
			dataIndex: 'name',
			key: 'name'
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			key: 'createTime',
			width: 200,
			customRender: ({ text }) => parseTime(text, '{y}-{m}-{d} {h}:{i}:{s}')
		},
		{
			title: '操作',
			key: 'action',
			width: 160,
			align: 'center'
		}
	]
	// 计算属性
	const levelEnum = computed(() => examStore.getLevelEnum)

	// 方法
	const submitForm = () => {
		queryParam.pageIndex = 1
		search()
	}

	const search = async () => {
		listLoading.value = true
		try {
			const response = await examPaperApi.pageList(queryParam)
			if (response) {
				const data = response
				tableData.value = data.records || []
				total.value = data.total || 0
				queryParam.pageIndex = data.current || 1
				listLoading.value = false
			} else {
				message.error(response.message || '获取数据失败')
			}
		} catch (error) {
			console.error('获取试卷列表失败:', error)
			message.error('获取数据失败')
		} finally {
			listLoading.value = false
		}
	}

	const deletePaper = async (row) => {
		try {
			// 显示确认对话框
			const confirmed = await new Promise((resolve) => {
				Modal.confirm({
					title: '确认删除',
					content: `确定要删除试卷"${row.name}"吗？`,
					okText: '确定',
					cancelText: '取消',
					onOk: () => resolve(true),
					onCancel: () => resolve(false)
				})
			})

			if (!confirmed) return

			await examPaperApi.deletePaper(row.id)
			search()
		} catch (error) {
			console.error('删除试卷失败:', error)
			message.error('删除失败')
		}
	}

	const levelChange = () => {
		queryParam.subjectId = null
		subjectFilter.value = examStore.subjects.filter((data) => data.level === queryParam.level)
	}

	const handlePageChange = (page, pageSize) => {
		queryParam.pageIndex = page
		queryParam.pageSize = pageSize
		search()
	}

	const handlePageSizeChange = (current, size) => {
		queryParam.pageIndex = 1
		queryParam.pageSize = size
		search()
	}
	const handleOk = (item) => {
		console.log("选取了",item)
		modeTag.value = 'item'
		itemDatas.value = []
		itemDatas.value.push(item)

		emit('handlerEx', [item])

	}
	const handleReset = (item) => {
		console.log("选取了",item)
		modeTag.value = 'list'
		itemDatas.value = []
		queryParam.pageIndex = 1
		search()

		emit('handlerEx', null)
	}
	const getItemData = () => {
	  return 	itemDatas.value
	}
	const edit = async (id) => {
		modeTag.value = 'item'
		listLoading.value = true
		try {
			const response = await examPaperApi.pageList({id :id,current : 1 ,size:10 })
			if (response) {
				const data = response
				itemDatas.value = data.records || []
				listLoading.value = false
			} else {
				message.error(response.message || '获取数据失败')
			}
		} catch (error) {
			console.error('获取试卷列表失败:', error)
			message.error('获取数据失败')
		} finally {
			listLoading.value = false
		}

	}

	// 生命周期
	onMounted(async () => {

	})

	defineExpose({getItemData,edit,open})
</script>

<style lang="less" scoped>
	.app-container {
		padding: 24px;
		background: #fff;

		.search-form {
			margin-bottom: 24px;
			padding: 24px;
			background: #fafafa;
			border-radius: 6px;
		}

		.data-table {
			margin-bottom: 24px;
		}

		.pagination {
			text-align: right;
		}
	}
</style>
