<template>
	<div style="display: flex; justify-content: center" class="main-content-wrapper">
		<a-card :bordered="false" style="width: 1200px" class="formMount">
			<a-space>
				<a-input-search
					v-model:value="searchFormState.postTitle"
					placeholder="请输入名称关键词"
					enter-button
					allowClear
					@search="onSearch"
				/>
				<a-select
					v-model:value="typeValue"
					show-search
					placeholder="所有分类"
					style="width: 200px"
					:options="typeOptions"
					:filter-option="filterOption"
					@change="handleChange"
				></a-select>
				<a-radio-group v-model:value="searchFormState.sortOrder" button-style="solid">
					<a-radio-button
						v-for="module in moduleTypeList"
						:key="module.id"
						:value="module.id"
						@click="moduleClock(module.id, module.type)"
					>
						{{ module.title }}
					</a-radio-button>
				</a-radio-group>
				<a-button type="primary" @click="formRef.onOpen(undefined, searchFormState.sortOrder)">
					<template #icon><plus-outlined /></template>
					创建新主题
				</a-button>
			</a-space>
			<a-table
				ref="table"
				class="mt-2"
				:columns="columns"
				:dataSource="tableData"
				:row-key="(record) => record.id"
				:custom-row="customRow"
				:pagination="false"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'postTitle'">
						<div class="forum-list-title">{{ record.postTitle }}</div>
						<div class="forum-list-type">{{ record.typeName }}</div>
						<div class="forum-list-content one-line" v-html="record.postContent"></div>
					</template>
					<template v-if="column.dataIndex === 'lastReplyUserAvatar'">
						<a-tooltip :title="record.lastReplyUserNickName" placement="top">
							<a-avatar :src="record.lastReplyUserAvatar"></a-avatar>
						</a-tooltip>
					</template>
					<template v-if="column.dataIndex === 'lastReplyTime'">
						<div>{{ formatDateTime(record.lastReplyTime) }}</div>
					</template>
				</template>
			</a-table>
			<div style="text-align: center; cursor: pointer" class="mt-2" @click="moreList">{{ moreText }}</div>
			<Form ref="formRef" @successful="loadData(pagination.value)" />
		</a-card>
	</div>
</template>

<script setup name="forumList">
	import forumApi from '@/api/forum/forumApi'
	import Form from './form.vue'
	import { parseTime } from '@/utils/exam'
	import { useRoute, useRouter } from 'vue-router'
	const route = useRoute()
	const router = useRouter()
	const formRef = ref()
	let searchFormState = reactive({
		sortOrder: 0,
		postTitle: '',
		postType: route.query.postType ?? null
	})
	const table = ref(null)
	const moduleTypeList = ref([
		{
			title: '最新',
			id: 0,
			type: 1,
			state: 0
		},
		{
			title: '热门',
			id: 1,
			type: 1,
			state: 1
		},
		{
			title: '我发布的',
			id: 2,
			type: 2,
			state: 1
		},
		{
			title: '我回复的',
			id: 3,
			type: 2,
			state: 2
		},
		{
			title: '关于我的',
			id: 4,
			type: 2,
			state: 3
		},
		{
			title: '我点赞的',
			id: 5,
			type: 2,
			state: 4
		}
	])
	const columns = [
		{
			title: '主题',
			dataIndex: 'postTitle'
		},
		{
			title: '最后回复人',
			dataIndex: 'lastReplyUserAvatar',
			align: 'center',
			width: 120
		},
		{
			title: '回复量',
			dataIndex: 'replyCount',
			align: 'center',
			width: 100
		},
		{
			title: '浏览量',
			dataIndex: 'viewCount',
			align: 'center',
			width: 100
		},
		{
			title: '最后回复时间',
			dataIndex: 'lastReplyTime',
			align: 'center',
			width: 120
		}
	]
	const typeValue = ref('所有分类')
	const typeOptions = ref([])
	const handleChange = (value) => {
		exType.value = false
		searchFormState.typeId = value
		if(searchFormState.sortOrder > 1){
			searchFormState.sortOrder = 0
		}
		loadData(pagination.value)
	}
	const filterOption = (input, option) => {
		return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
	}
	function formatDateTime(val) {
		if (!val) return ''
		return parseTime(val, '{y}-{m}-{d} {h}:{i}:{s}')
	}
	// 查询
	const onSearch = () => {
		exType.value = false
		loadData(pagination.value)
	}
	function customRow(record) {
		return {
			onClick: () => itemSelect(record)
		}
	}
	function itemSelect(record) {
		router.push({
			path: '/forum/detail',
			query: {
				postId: record.postId,
				postType: route.query.postType ?? ''
			}
		})
	}
	function getTypeList() {
		forumApi.forumTypeList().then((data) => {
			typeOptions.value = data.map((r) => {
				return {
					label: r.typeName,
					value: r.typeId,
					...r
				}
			})
		})
	}
	

	const exType = ref(false)
	const tableData = ref([])
	const tableTotal = ref(0)
	const loadData = (parameter, a) => {
		if (exType.value) {
			let postExtend = moduleTypeList.value.filter((r) => r.id == searchFormState.sortOrder)[0]?.state
			return forumApi.moreList(Object.assign(parameter, { postExtend: postExtend })).then((data) => {
				tableTotal.value = data.total
				if (a) {
					tableData.value = Object.assign(tableData.value, data.records)
				} else {
					if (data) {
						tableData.value = data.records
					} else {
						tableData.value = []
					}
				}
			})
		} else {
			return forumApi.forumList(Object.assign(parameter, searchFormState)).then((data) => {
				tableTotal.value = data.total
				if (a) {
					tableData.value = tableData.value.concat(data.records)
				} else {
					if (data) {
						tableData.value = data.records
					} else {
						tableData.value = []
					}
				}
			})
		}
	}
	const pagination = ref({
		current: 1,
		size: 10
	})
	
	// 切换应用标签查询菜单列表
	const moduleClock = (value, t) => {
		exType.value = false
		searchFormState.sortOrder = value
		pagination.value.current = 1
		moreText.value = '加载更多'
		if (t == 2) {
			exType.value = true
			typeValue.value = '所有分类'
		}
		loadData(pagination.value)
	}
	const moreText = ref()

	const moreList = () => {
		if (tableTotal.value > pagination.value.current * pagination.value.size) {
			pagination.value.current += 1
			loadData(pagination.value, 1)
			moreText.value = '加载更多'
		} else {
			moreText.value = '全部加载完成'
		}
	}
	// 定义滚动函数
	const handleScroll = () => {
		const tableContainer = window.document.querySelector('.main-content-wrapper')
		const scrollPosition = tableContainer.scrollTop
		const isBottom = tableContainer.scrollHeight - scrollPosition - 20 < tableContainer.clientHeight
		if (isBottom) {
			if (tableTotal.value > pagination.value.current * pagination.value.size) {
				pagination.value.current += 1
				loadData(pagination.value, 1)
				moreText.value = '加载更多'
			} else {
				moreText.value = '全部加载完成'
			}
			console.log('加载更多')
		}
	}

	// 添加scroll监听
	onMounted(() => {
		getTypeList()
		loadData(pagination.value)
		nextTick(() => {
			if (table.value) {
				const tableContainer = window.document.querySelector('.main-content-wrapper')
				tableContainer.addEventListener('scroll', handleScroll)
			}
		})
	})

	// 移除scroll监听
	onBeforeUnmount(() => {
		nextTick(() => {
			if (table.value) {
				const tableContainer = window.document.querySelector('.main-content-wrapper')
				tableContainer.removeEventListener('scroll', handleScroll)
			}
		})
	})
</script>
<style scoped>
	.forum-list-title {
		font-size: 16px;
		font-weight: bold;
	}

	.forum-list-type {
		font-size: 12px;
	}

	.forum-list-content {
		font-size: 14px;
		color: #696969;
	}

	.one-line {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
	}
</style>
