<template>
	<div class="container">
		<div class="search-area">
			<Form ref="formInline" inline :label-width="120" :model="formInline" :rules="ruleInline">
				<FormItem label="会员名称：" prop="name">
					<Input type="text" clearable v-model="formInline.name" placeholder="请输入会员名称" />
				</FormItem>
				<FormItem label="状态：" prop="status">
					<Select v-model="formInline.status" clearable placeholder="全部状态" style="width: 200px">
						<Option v-for="option in statusOptions" :key="`vip-status-${option.value}`" :value="option.value">
							{{ option.label }}
						</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit">搜索</Button>
					<Button style="margin-left: 8px" @click="handleReset">重置</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="tableLoading">
				<template #remarks="{ row }">
					<Tooltip v-if="row.remarks" transfer :content="row.remarks" placement="top">
						<span class="ellipsis">{{ row.remarks }}</span>
					</Tooltip>
					<span v-else>--</span>
				</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" :current="page" :page-size="pageSize" show-total show-sizer class="page"
				@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
		</div>

		<Modal v-model="show_modal" :title="formValidate.id ? '编辑会员' : '添加会员'" :mask-closable="false"
			:closable="false" width="600" @on-cancel="cancel">
			<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
				<FormItem label="会员名称" prop="name">
					<Input v-model="formValidate.name" placeholder="请输入会员名称" />
				</FormItem>
				<FormItem label="会员介绍" prop="remarks">
					<Input v-model="formValidate.remarks" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }"
						placeholder="请输入会员权益/说明" />
				</FormItem>
				<FormItem label="原价(元)" prop="original_price">
					<InputNumber v-model="formValidate.original_price" :min="0" :precision="2" :step="1"
						style="width: 240px" />
				</FormItem>
				<FormItem label="售价(元)" prop="selling_price">
					<InputNumber v-model="formValidate.selling_price" :min="0" :precision="2" :step="1"
						style="width: 240px" />
				</FormItem>
				<FormItem label="有效期(天)" prop="time">
					<InputNumber v-model="formValidate.time" :min="1" :step="1" style="width: 240px" />
				</FormItem>
				<FormItem label="状态" prop="status">
					<RadioGroup v-model="formValidate.status">
						<Radio v-for="option in statusOptions" :key="`vip-form-status-${option.value}`" :label="option.value">
							{{ option.label }}
						</Radio>
					</RadioGroup>
				</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 {
	getVipList,
	addVip,
	getVip,
	getVipUpdate,
	getVipDelete,
} from '@/api'

const createDefaultVipForm = () => ({
	id: '',
	name: '',
	remarks: '',
	original_price: 0,
	selling_price: 0,
	time: 1,
	status: 1,
})

export default {
	name: 'user_vip',
	data() {
		return {
			show_modal: false,
			tableHeight: 500,
			tableLoading: false,
			submitLoading: false,
			page: 1,
			pageSize: 10,
			total: 0,
			formInline: {
				name: '',
				status: '',
			},
			ruleInline: {},
			columns: [
				{ title: '会员名称', key: 'name', minWidth: 160 },
				{ title: '会员介绍', slot: 'remarks', minWidth: 200 },
				{ title: '原价(元)', key: 'originalPriceText', minWidth: 120 },
				{ title: '售价(元)', key: 'sellingPriceText', minWidth: 120 },
				{ title: '有效期(天)', key: 'timeText', minWidth: 120 },
				{ title: '状态', key: 'statusText', minWidth: 100 },
				{ title: '创建时间', key: 'createTimeText', minWidth: 170 },
				{ title: '操作', slot: 'action', width: 180, align: 'center' },
			],
			data: [],
			statusOptions: [
				{ label: '启用', value: 1 },
				{ label: '禁用', value: 0 },
			],
			formValidate: createDefaultVipForm(),
			ruleValidate: {
				name: [
					{ required: true, message: '请输入会员名称', trigger: 'blur' },
				],
				remarks: [
					{ required: false },
				],
				original_price: [
					{ required: true, type: 'number', message: '请输入原价', trigger: 'change' },
				],
				selling_price: [
					{ required: true, type: 'number', message: '请输入售价', trigger: 'change' },
				],
				time: [
					{ required: true, type: 'number', message: '请输入有效期', trigger: 'change' },
				],
				status: [
					{ required: true, type: 'number', message: '请选择状态', trigger: 'change' },
				],
			},
		}
	},
	async mounted() {
		await this.getList()
		this.$nextTick(this.calculateTableHeight)
		window.addEventListener('resize', this.calculateTableHeight)
	},
	beforeDestroy() {
		window.removeEventListener('resize', this.calculateTableHeight)
	},
	methods: {
		// 计算表格高度，保持与站点管理页面布局一致
		calculateTableHeight() {
			const searchArea = document.querySelector('.search-area')
			const actionArea = document.querySelector('.action-btn')
			const searchHeight = searchArea ? searchArea.offsetHeight : 0
			const actionHeight = actionArea ? actionArea.offsetHeight : 0
			const pageHeight = 32
			const margins = 40
			const availableHeight = window.innerHeight - actionHeight - searchHeight - pageHeight - margins - 130
			this.tableHeight = Math.max(320, availableHeight)
		},
		// 请求会员列表
		async getList() {
			const params = {
				page: this.page,
				pageSize: this.pageSize,
			}
			if (this.formInline.name) {
				params.name = this.formInline.name
			}
			if (this.formInline.status !== '' && this.formInline.status !== null && this.formInline.status !== undefined) {
				params.status = this.formInline.status
			}
			this.tableLoading = true
			try {
				const res = await getVipList(params)
				const list = res && res.data && Array.isArray(res.data.data) ? res.data.data : []
				this.total = (res && res.data && res.data.total) || 0
				this.data = list.map(item => this.normalizeVipRow(item))
			} catch (error) {
				this.$Message.error('获取会员列表失败，请稍后重试')
			} finally {
				this.tableLoading = false
			}
		},
		// 组装表格展示字段
		normalizeVipRow(item) {
			return {
				id: item.id,
				name: item.name || '--',
				remarks: item.remarks || '',
				originalPriceText: this.formatAmount(item.original_price),
				sellingPriceText: this.formatAmount(item.selling_price),
				timeText: this.formatDays(item.time),
				statusText: Number(item.status) === 1 ? '启用' : '禁用',
				createTimeText: this.formatTimestamp(item.createtime),
				updateTimeText: this.formatTimestamp(item.updatetime),
			}
		},
		// 金额格式化
		formatAmount(value) {
			if (value === undefined || value === null || value === '') {
				return '--'
			}
			const numberValue = Number(value)
			if (Number.isNaN(numberValue)) {
				return '--'
			}
			return numberValue.toFixed(2)
		},
		// 有效期格式化
		formatDays(value) {
			if (value === undefined || value === null || value === '') {
				return '--'
			}
			const numberValue = Number(value)
			if (Number.isNaN(numberValue)) {
				return '--'
			}
			return `${numberValue} 天`
		},
		// 时间戳转日期
		formatTimestamp(timestamp) {
			if (!timestamp) {
				return '--'
			}
			const value = Number(timestamp)
			if (Number.isNaN(value)) {
				return '--'
			}
			const date = `${value}`.length === 13 ? new Date(value) : new Date(value * 1000)
			if (Number.isNaN(date.getTime())) {
				return '--'
			}
			const Y = date.getFullYear()
			const M = `${date.getMonth() + 1}`.padStart(2, '0')
			const D = `${date.getDate()}`.padStart(2, '0')
			const h = `${date.getHours()}`.padStart(2, '0')
			const m = `${date.getMinutes()}`.padStart(2, '0')
			const s = `${date.getSeconds()}`.padStart(2, '0')
			return `${Y}-${M}-${D} ${h}:${m}:${s}`
		},
		// 搜索
		handleSubmit() {
			this.page = 1
			this.getList()
		},
		// 重置搜索
		handleReset() {
			this.formInline = {
				name: '',
				status: '',
			}
			this.handleSubmit()
		},
		// 分页
		onChangePage(page) {
			if (this.page !== page) {
				this.page = page
				this.getList()
			}
		},
		onChangePageSize(size) {
			if (this.pageSize !== size) {
				this.pageSize = size
				this.page = 1
				this.getList()
			}
		},
		// 打开新增弹窗
		add() {
			this.formValidate = createDefaultVipForm()
			this.show_modal = true
			this.$nextTick(() => {
				if (this.$refs.formValidate) {
					this.$refs.formValidate.clearValidate()
				}
			})
		},
		// 编辑详情
		async show(id) {
			if (!id) {
				return
			}
			try {
				const res = await getVip({ id })
				const detail = res && res.data ? res.data : {}
				this.formValidate = {
					...createDefaultVipForm(),
					id: detail.id,
					name: detail.name || '',
					remarks: detail.remarks || '',
					original_price: this.normalizeNumber(detail.original_price),
					selling_price: this.normalizeNumber(detail.selling_price),
					time: this.normalizeNumber(detail.time) || 1,
					status: detail.status !== undefined ? Number(detail.status) : 1,
				}
				this.show_modal = true
				this.$nextTick(() => {
					if (this.$refs.formValidate) {
						this.$refs.formValidate.clearValidate()
					}
				})
			} catch (error) {
				this.$Message.error('获取会员详情失败，请稍后重试')
			}
		},
		// 数字归一化
		normalizeNumber(value) {
			const numberValue = Number(value)
			return Number.isNaN(numberValue) ? 0 : numberValue
		},
		// 取消操作
		cancel() {
			this.show_modal = false
			this.formValidate = createDefaultVipForm()
			this.$nextTick(() => {
				if (this.$refs.formValidate) {
					this.$refs.formValidate.clearValidate()
				}
			})
		},
		// 确认提交
		async ok() {
			const valid = await new Promise(resolve => {
				if (!this.$refs.formValidate) {
					resolve(false)
					return
				}
				this.$refs.formValidate.validate(result => resolve(result))
			})
			if (!valid) {
				this.$Message.error('请完善表单后再提交')
				return
			}
			this.submitLoading = true
			const payload = this.buildSubmitPayload()
			try {
				if (payload.id) {
					const res = await getVipUpdate(payload)
					this.$Message.success(res.msg || '更新成功')
				} else {
					const res = await addVip(payload)
					this.$Message.success(res.msg || '新增成功')
				}
				this.cancel()
				this.getList()
			} catch (error) {
				this.$Message.error(error.msg || '提交失败，请稍后重试')
			} finally {
				this.submitLoading = false
			}
		},
		// 组装提交参数
		buildSubmitPayload() {
			const payload = { ...this.formValidate }
			payload.original_price = Number(payload.original_price)
			payload.selling_price = Number(payload.selling_price)
			payload.time = Number(payload.time)
			payload.status = Number(payload.status)
			return payload
		},
		// 删除会员配置
		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
			}
			try {
				const res = await getVipDelete({ id })
				this.$Message.success(res.msg || '删除成功')
				if (this.data.length === 1 && this.page > 1) {
					this.page -= 1
				}
				this.getList()
			} catch (error) {
				this.$Message.error(error.msg || '删除失败，请稍后重试')
			}
		},
	},
}
</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;

	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;
}

.ellipsis {
	display: inline-block;
	max-width: 160px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
</style>
