<template>
	<div class="container">
		<div class="search-area">
			<Form ref="formInline" inline :label-width="120" :model="formInline" :rules="ruleInline">
				<FormItem label="活动标题：" prop="title">
					<Input type="text" clearable v-model="formInline.title" placeholder="请输入活动标题" />
				</FormItem>
				<FormItem label="状态：" prop="status">
					<Select v-model="formInline.status" clearable placeholder="全部状态" style="width: 200px">
						<Option v-for="item in statusOptions" :key="item.value" :value="item.value">
							{{ item.label }}
						</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit">搜索</Button>
					<Button style="margin-left: 8px" @click="resetSearch">重置</Button>
				</FormItem>
			</Form>
		</div>
		<div class="action-btn">
			<Button type="primary" @click="add">添加</Button>
		</div>
		<div class="table-container">
			<Table border :columns="columns" stripe :height="tableHeight" :data="data" :loading="loading">
				<template #status="{ row }">
					{{ getStatusText(row.status) }}
				</template>
				<template #action="{ row }">
					<Button type="primary" size="small" style="margin-right: 5px" @click="show(row.id)">编辑</Button>
					<Button type="error" size="small" @click="remove(row.id)">删除</Button>
				</template>
			</Table>
			<Page :total="total" show-total show-sizer class="page" :current="page" :page-size="pageSize"
				@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
		</div>
		<Modal v-model="show_modal" :title="modalTitle" :mask-closable="false" :width="820" @on-cancel="cancel">
			<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
				<FormItem label="活动标题" prop="title">
					<Input v-model="formValidate.title" placeholder="请输入活动标题" />
				</FormItem>
				<FormItem label="活动状态" prop="status">
					<RadioGroup v-model="formValidate.status">
						<Radio label="1">已发布</Radio>
						<Radio label="0">未发布</Radio>
					</RadioGroup>
				</FormItem>
				<FormItem label="活动内容" prop="content">
					<RichEditor v-model="formValidate.content" placeholder="请输入活动内容，支持图片上传" :height="320"
						@change="handleContentChange" />
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="text" @click="cancel">取消</Button>
				<Button type="primary" :loading="submitLoading" @click="ok">确定</Button>
			</div>
		</Modal>
	</div>
</template>

<script>
	import {
		getEventList,
		addEvent,
		getEvent,
		getEventUpdate,
		getEventDelete,
	} from '@/api'
	import RichEditor from '@/components/RichEditor.vue'

	export default {
		name: 'activity',
		components: {
			RichEditor,
		},
		data() {
			return {
				loading: false, // 列表查询 loading 态
				show_modal: false, // 新增/编辑弹窗显隐
				modalTitle: '添加活动', // 弹窗标题
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				total: 0, // 数据总条数
				tableHeight: 500, // 表格高度，用于自适应
				formInline: {
					title: '',
					status: '',
				},
				ruleInline: {}, // 站点管理页面无搜索校验，此处保持空对象占位
				statusOptions: [{
						label: '全部状态',
						value: '', // 传空值表示不筛选状态
					},
					{
						label: '未发布',
						value: '0',
					},
					{
						label: '已发布',
						value: '1',
					},
				],
				statusMap: {
					0: '未发布',
					1: '已发布',
				},
				columns: [{ // 表格列配置，沿用站点管理页面 Table 风格
						title: '活动标题',
						key: 'title',
					},
					{
						title: '活动状态',
						slot: 'status',
					},
					{
						title: '创建时间',
						key: 'create_time',
					},
					{
						title: '操作',
						slot: 'action',
						width: 150,
						align: 'center',
					},
				],
				data: [], // 活动列表数据源
				formValidate: {
					id: '', // 活动主键，编辑时使用
					title: '', // 活动标题
					status: '1', // 活动状态：1 已发布，0 未发布
					content: '', // 富文本正文
				},
				ruleValidate: {
					title: [{
						required: true,
						message: '请输入活动标题',
						trigger: 'blur',
					}],
					status: [{
						required: true,
						message: '请选择活动状态',
						trigger: 'change',
					}],
					content: [{
						required: true,
						message: '请输入活动内容',
						trigger: 'change',
					}],
				},
				submitLoading: false,
			}
		},
		mounted() {
			this.getList()
			this.calculateTableHeight()
			window.addEventListener('resize', this.calculateTableHeight)
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.calculateTableHeight)
		},
		methods: {
			// 自适应计算表格高度，保持页面视觉与站点管理页面一致
			calculateTableHeight() {
				const search = document.querySelector('.search-area')
				const action = document.querySelector('.action-btn')
				const searchHeight = search ? search.offsetHeight : 0
				const actionHeight = action ? action.offsetHeight : 0
				const pageHeight = 32
				const margins = 40
				this.tableHeight = window.innerHeight - searchHeight - actionHeight - pageHeight - margins - 130
				if (this.tableHeight < 300) {
					this.tableHeight = 300
				}
			},
			// 获取活动列表数据
			async getList() {
				this.loading = true
				try {
					const params = {
						page: this.page,
						pageSize: this.pageSize,
						title: this.formInline.title,
						status: this.formInline.status,
					}
					if (params.status === '') {
						delete params.status
					}
					const res = await getEventList(params)
					// 兼容后端返回 { data: { list: [], total: 0 } } 或 { data: [], total: 0 } 的场景
					const responseData = res.data || res || {}
					let list = []
					if (Array.isArray(responseData)) {
						list = responseData
						this.total = responseData.length
					} else if (responseData && typeof responseData === 'object') {
						list = responseData.data || responseData.list || responseData.records || []
						const total = responseData.total || responseData.count || responseData.totalCount
						if (typeof total === 'number') {
							this.total = total
						} else if (Array.isArray(list)) {
							this.total = list.length
						} else {
							this.total = 0
						}
						if (responseData.current_page) {
							this.page = responseData.current_page
						}
					}
					this.data = Array.isArray(list) ? list : []
				} catch (error) {
					this.data = []
					this.total = 0
				} finally {
					this.loading = false
				}
			},
			// 点击搜索按钮，重置页码并刷新列表
			handleSubmit() {
				this.page = 1
				this.getList()
			},
			// 重置查询条件，保持行为与站点管理搜索一致
			resetSearch() {
				this.formInline.title = ''
				this.formInline.status = ''
				if (this.$refs.formInline) {
					this.$refs.formInline.resetFields()
				}
				this.handleSubmit()
			},
			// 新增活动
			add() {
				this.modalTitle = '添加活动'
				this.show_modal = true
				this.resetForm()
			},
			// 重置弹窗表单字段
			resetForm() {
				Object.assign(this.formValidate, {
					id: '',
					title: '',
					status: '1',
					content: '',
				})
				this.$nextTick(() => {
					if (this.$refs.formValidate) {
						this.$refs.formValidate.resetFields()
					}
				})
			},
			// 取消弹窗
			cancel() {
				this.show_modal = false
				if (this.$refs.formValidate) {
					this.$refs.formValidate.resetFields()
				}
			},
			// 点击编辑时加载活动详情
			async show(id) {
				if (!id) {
					return
				}
				try {
					const res = await getEvent({
						id,
					})
					const info = res.data || {}
					Object.assign(this.formValidate, {
						id: info.id,
						title: info.title || '',
						status: info.status != null ? String(info.status) : '0',
						content: info.content || '',
					})
					this.modalTitle = '编辑活动'
					this.show_modal = true
					this.$nextTick(() => {
						if (this.$refs.formValidate) {
							this.$refs.formValidate.clearValidate()
						}
					})
				} catch (error) {
					this.$Message.error('获取活动详情失败，请稍后重试')
				}
			},
			// 删除活动前二次确认
			async remove(id) {
				if (!id) {
					return
				}
				const confirm = await new Promise(resolve => {
					this.$Modal.confirm({
						title: '确认删除',
						content: '删除后不可恢复，确定继续吗？',
						onOk: () => resolve(true),
						onCancel: () => resolve(false),
					})
				})
				if (!confirm) {
					return
				}
				await getEventDelete({
					id,
				})
				this.$Message.success('删除成功')
				if (this.data.length === 1 && this.page > 1) {
					this.page -= 1
				}
				this.getList()
			},
			// 新增/编辑提交保存
			async ok() {
				const valid = await new Promise(resolve => this.$refs.formValidate.validate(resolve))
				if (!valid) {
					this.$Message.error('请完善活动信息')
					return
				}
				this.submitLoading = true
				const payload = {
					id: this.formValidate.id,
					title: this.formValidate.title.trim(),
					status: Number(this.formValidate.status),
					content: this.formValidate.content,
				}
				try {
					if (payload.id) {
						await getEventUpdate(payload)
						this.$Message.success('活动更新成功')
					} else {
						await addEvent(payload)
						this.$Message.success('活动创建成功')
					}
					this.cancel()
					this.getList()
				} catch (error) {
					this.$Message.error('保存失败，请稍后重试')
				} finally {
					this.submitLoading = false
				}
			},
			// 分页切换
			onChangePage(e) {
				if (this.page !== e) {
					this.page = e
					this.getList()
				}
			},
			// pageSize切换
			onChangePageSize(e) {
				if (this.pageSize !== e) {
					this.page = 1
					this.pageSize = e
					this.getList()
				}
			},
			// 状态文案
			getStatusText(status) {
				const key = Number(status)
				return this.statusMap[key] || '未发布'
			},
			// 状态颜色
			getStatusColor(status) {
				return Number(status) === 1 ? 'success' : 'default'
			},
			// 富文本内容变更时主动触发校验，防止用户未输入内容直接提交
			handleContentChange() {
				if (this.show_modal && this.$refs.formValidate) {
					this.$refs.formValidate.validateField('content')
				}
			},
		},
	}
</script>
<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 20px;
		box-sizing: border-box;
	}

	.action-btn {
		margin: 20px 0;
		background-color: white;
		padding: 20px;
		border: 1px solid #F3F7FD;
		border-radius: 15px;
		display: flex;
		align-items: center;
	}

	.action-btn button {
		margin-right: 20px;
	}

	.table-container {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.page {
		margin-top: 10px;
		text-align: right;
	}

	.search-area {
		background-color: white;
		padding-top: 20px;
		border: 1px solid #F3F7FD;
		border-radius: 15px;
	}
</style>