<template>
	<div class="app-container">
		<a-form :model="queryParam" layout="inline" @submit.prevent>
			<a-form-item label="题目ID：">
				<a-input v-model:value="queryParam.id" allow-clear />
			</a-form-item>
			<a-form-item label="题目内容：">
				<a-input v-model:value="queryParam.content" allow-clear />
			</a-form-item>
			<!-- <a-form-item label="年级：">
				<a-select
					v-model:value="queryParam.level"
					placeholder="年级"
					allow-clear
					@change="levelChange"
					style="width: 100px"
				>
					<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" allow-clear style="width: 100px">
					<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 label="题库类型：">
				<a-select v-model:value="queryParam.bankType" placeholder="题库类型" allow-clear style="width: 100px">
					<a-select-option v-for="item in bankTypeEnum" :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.questionType" allow-clear style="width: 100px">
					<a-select-option v-for="item in questionTypeEnum" :key="item.key" :value="item.key">{{
						item.value
					}}</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item>
				<a-button type="primary" @click="submitForm">查询</a-button>
				<a-dropdown>
					<a-button type="primary" class="link-left">添加</a-button>
					<template #overlay>
						<a-menu>
							<a-menu-item v-for="item in editUrlEnum" :key="item.key" @click="openDrawer(item.value)">
								{{ item.name }}
							</a-menu-item>
						</a-menu>
					</template>
				</a-dropdown>
				<a-upload :customRequest="handleImportExcel" :showUploadList="false" accept=".xlsx,.xls" class="link-left">
					<a-button type="primary">导入Excel</a-button>
				</a-upload>
			</a-form-item>
		</a-form>
		<a-table
			:loading="listLoading"
			:data-source="tableData"
			:pagination="false"
			row-key="id"
			bordered
			style="margin-top: 16px"
			tableLayout="fixed"
			:scroll="{ x: 'max-content' }"
		>
			<a-table-column title="Id" data-index="id" key="id" width="90px" />
			<a-table-column
				title="题库类型"
				data-index="bankType"
				key="bankType"
				width="150px"
				:customRender="bankTypeFormatter"
			/>
			<a-table-column
				title="题型"
				data-index="questionType"
				key="questionType"
				width="90px"
				:customRender="questionTypeFormatter"
			/>
			<a-table-column title="题干" data-index="shortTitle" key="shortTitle" ellipsis width="350px" />
			<a-table-column title="分数" data-index="score" key="score" width="90px" />
			<a-table-column title="难度" data-index="difficult" key="difficult" width="110px">
				<template #default="{ text }">
					<StarFilled v-for="n in Number(text)" :key="n" style="color: #faad14" />
					<StarOutlined v-for="n in 5 - Number(text)" :key="'empty' + n" style="color: #e8e8e8" />
				</template>
			</a-table-column>
			<a-table-column title="创建时间" data-index="createTime" key="createTime" width="180px">
				<template #default="{ text }">
					{{ parseTime(text, '{y}-{m}-{d} {h}:{i}:{s}') }}
				</template>
			</a-table-column>
			<a-table-column title="操作" key="action" width="200px">
				<template #default="{ record }">
					<a-button size="small" style="margin-right: 8px" @click="showQuestion(record)">预览</a-button>
					<a-button size="small" style="margin-right: 8px" @click="editQuestion(record)">编辑</a-button>
					<a-button size="small" danger @click="deleteQuestion(record)">删除</a-button>
				</template>
			</a-table-column>
		</a-table>
		<custom-pagination
			v-show="total > 0"
			:total="total"
			:page-size="queryParam.pageSize"
			:current="queryParam.pageIndex"
			:showSizeChanger="true"
			@change="onPageChange"
			@showSizeChange="onPageSizeChange"
			style="margin-top: 16px; text-align: right; display: flex; justify-content: center"
		/>
		<a-modal v-model:visible="questionShow.dialog" width="800px" :footer="null" :bodyStyle="{ padding: '24px' }">
			<div v-if="questionShow.loading" style="text-align: center; padding: 40px 0">
				<a-spin />
			</div>
			<div v-else>
				<!-- 题目预览内容，Show.vue 为空可先简单展示 -->
				<div v-if="questionShow.question">
					<h3>题型：{{ enumFormat(questionTypeEnum, questionShow.qType) }}</h3>
					<div v-html="questionShow.question.title || questionShow.question.shortTitle"></div>
					<div v-if="questionShow.question.items">
						<div v-for="item in questionShow.question.items" :key="item.prefix">
							<b>{{ item.prefix }}：</b><span v-html="item.content"></span>
						</div>
					</div>
					<div>解析：<span v-html="questionShow.question.analyze"></span></div>
					<div>分数：{{ questionShow.question.score }}</div>
					<div>难度：{{ questionShow.question.difficult }}</div>
				</div>
			</div>
		</a-modal>
		<a-drawer
			:visible="drawerOpen"
			title="添加题目"
			placement="right"
			width="900"
			:destroyOnClose="true"
			@close="closeDrawer"
		>
			<component
				:is="currentComponent"
				v-if="currentComponent"
				:id="currentComponentId"
				@successful="onDrawerSuccess"
			/>
		</a-drawer>
	</div>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, defineAsyncComponent, shallowRef } from 'vue'
	import { useExamStore } from '@/store/exam'
	import tQuestionApi from '@/api/exam/question/tQuestionApi'
	import customPagination from '@/components/customPagination.vue'
	import { StarFilled, StarOutlined } from '@ant-design/icons-vue'
	import { Modal, message } from 'ant-design-vue'
	import { parseTime } from '@/utils/exam'
	const bankTypeEnum = computed(() => examStore.getBankTypeEnum)
	const examStore = useExamStore()

	const queryParam = reactive({
		id: null,
		questionType: null,
		// level: null,
		// subjectId: null,
		pageIndex: 1,
		pageSize: 10,
		bankType: null
	})

	const subjectFilter = ref([])
	const listLoading = ref(false)
	const tableData = ref([])
	const total = ref(0)
	const questionShow = reactive({
		qType: 0,
		dialog: false,
		question: null,
		loading: false
	})

	const levelEnum = computed(() => examStore.levelEnum)
	const questionTypeEnum = computed(() => examStore.questionTypeEnum)
	const editUrlEnum = computed(() => examStore.exam.question.editUrlEnum)
	const subjects = computed(() => examStore.subjects)
	const enumFormat = examStore.enumFormat
	const subjectEnumFormat = examStore.subjectEnumFormat
	const currentComponentId = ref(null)
	// 动态抽屉相关
	const drawerOpen = ref(false)
	const currentComponent = shallowRef(null)
	const openDrawer = (componentPath) => {
		currentComponentId.value = 0
		currentComponent.value = defineAsyncComponent(() => import(/* @vite-ignore */ componentPath))
		drawerOpen.value = true
	}
	const closeDrawer = () => {
		drawerOpen.value = false
		currentComponent.value = null
	}
	const onDrawerSuccess = () => {
		closeDrawer()
		search()
	}

	onMounted(async () => {
		await examStore.initSubject()
		subjectFilter.value = subjects.value
		search()
	})

	const submitForm = () => {
		queryParam.pageIndex = 1
		search()
	}
	const bankTypeFormatter = ({ text }) => {
		const key = Number(text)
		return enumFormat(bankTypeEnum.value, key)
	}

	const search = () => {
		listLoading.value = true
		const params = {
			...queryParam,
			current: queryParam.pageIndex,
			size: queryParam.pageSize
		}
		delete params.pageIndex
		delete params.pageSize
		tQuestionApi
			.pageList(params)
			.then((data) => {
				const re = data
				tableData.value = re.records
				total.value = re.total
				queryParam.pageIndex = re.current
				listLoading.value = false
			})
			.catch(() => {
				listLoading.value = false
			})
	}

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

	const showQuestion = (row) => {
		questionShow.dialog = true
		questionShow.loading = true
		tQuestionApi.select(row.id).then((re) => {
			questionShow.qType = re.questionType
			questionShow.question = re
			questionShow.loading = false
		})
	}

	const editQuestion = (row) => {
		const url = enumFormat(editUrlEnum.value, row.questionType)
		currentComponent.value = defineAsyncComponent(() => import(/* @vite-ignore */ url))
		drawerOpen.value = true
		currentComponentId.value = row.id
	}

	const deleteQuestion = (row) => {
		Modal.confirm({
			title: '确认删除该题目吗？',
			onOk: () => {
				tQuestionApi.deleteQuestion(row.id).then((re) => {
					search()
				})
			}
		})
	}

	const questionTypeFormatter = ({ text }) => {
		return enumFormat(questionTypeEnum.value, text)
	}
	const subjectFormatter = ({ text }) => {
		return subjectEnumFormat(text)
	}
	const onPageChange = (page) => {
		queryParam.pageIndex = page
		search()
	}
	const onPageSizeChange = (page, size) => {
		queryParam.pageIndex = page
		queryParam.pageSize = size
		search()
	}

	// 处理Excel导入
	const handleImportExcel = (options) => {
		const { file } = options
		const loading = message.loading('正在检查文件...', 0)

		// 先调用检查接口
		tQuestionApi
			.checkExcel(file)
			.then((checkRes) => {
				loading()
				// 检查通过后，再调用导入接口
				const importLoading = message.loading('正在导入中...', 0)

				return tQuestionApi
					.importExcel(file)
					.then((res) => {
						importLoading()
						message.success('导入成功')
						search() // 刷新列表
					})
					.catch((error) => {
						importLoading()
						message.error('导入失败，请检查Excel文件格式是否正确')
						console.error('导入失败:', error)
						throw error // 继续抛出错误以便外层catch捕获
					})
			})
			.catch((error) => {
				loading()
				message.error('文件检查失败，请确保Excel格式正确')
				console.error('检查失败:', error)
			})
	}
</script>

<style lang="less" scoped>
	.app-container {
		background: #fff;
		padding: 24px;
		border-radius: 8px;
	}
	.link-left {
		margin-left: 8px;
	}
</style>
<style>
	.ant-modal div[aria-hidden='true'] {
		display: none !important;
	}
</style>
