<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="`search-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 #station="{ row }">
					<span>{{ row.stationLabel }}</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" @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="station_id">
					<Select v-model="formValidate.station_id" placeholder="请选择关联站点" filterable style="width: 240px">
						<Option v-for="station in stationOptions" :key="station.charge_station_id"
							:value="station.charge_station_id">
							{{ station.charge_station_name }}
						</Option>
					</Select>
				</FormItem>
				<FormItem label="用户类型" prop="user_type">
					<RadioGroup v-model="formValidate.user_type">
						<Radio v-for="option in userTypeOptions" :key="`user-${option.value}`" :label="option.value">
							{{ option.label }}
						</Radio>
					</RadioGroup>
				</FormItem>
				<FormItem label="使用门槛(元)" prop="threshold">
					<InputNumber v-model="formValidate.threshold" :min="0" :precision="2" :step="1" style="width: 240px" />
				</FormItem>
				<FormItem label="优惠金额(元)" prop="value">
					<InputNumber v-model="formValidate.value" :min="0" :precision="2" :step="1" style="width: 240px" />
				</FormItem>
				<FormItem label="过期时间" prop="expiration_time">
					<DatePicker type="datetime" format="yyyy-MM-dd HH:mm" v-model="formValidate.expiration_time"
						placeholder="请选择过期时间" style="width: 240px" />
				</FormItem>
				<FormItem label="状态" prop="status">
					<RadioGroup v-model="formValidate.status">
						<Radio v-for="option in statusOptions" :key="`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 {
	getCouponList,
	addCoupon,
	getCoupon,
	getCouponUpdate,
	getCouponDelete,
	getStationList,
} from '@/api'

const createDefaultCouponForm = () => ({
	id: '',
	name: '',
	station_id: '',
	user_type: 1,
	threshold: 0,
	value: 0,
	expiration_time: '',
	status: 1,
})

export default {
	name: 'coupon_manage',
	data() {
		return {
			show_modal: false,
			tableHeight: 500,
			page: 1,
			pageSize: 10,
			total: 0,
			tableLoading: false,
			submitLoading: false,
			formInline: {
				name: '',
				status: '',
			},
			ruleInline: {},
			columns: [
				{
					title: '优惠券名称',
					key: 'name',
					minWidth: 160,
				},
				{
					title: '所属站点',
					slot: 'station',
					minWidth: 160,
				},
				{
					title: '用户类型',
					key: 'userTypeText',
					minWidth: 120,
				},
				{
					title: '使用门槛(元)',
					key: 'thresholdText',
					minWidth: 140,
				},
				{
					title: '优惠金额(元)',
					key: 'valueText',
					minWidth: 140,
				},
				{
					title: '过期时间',
					key: 'expirationTimeText',
					minWidth: 170,
				},
				{
					title: '状态',
					key: 'statusText',
					minWidth: 100,
				},
				{
					title: '创建时间',
					key: 'createTimeText',
					minWidth: 170,
				},
				{
					title: '操作',
					slot: 'action',
					width: 180,
					align: 'center',
				},
			],
			data: [],
			stationOptions: [],
			userTypeOptions: [
				{ label: '所有用户', value: 1 },
				{ label: '会员用户', value: 2 },
			],
			statusOptions: [
				{ label: '开启', value: 1 },
				{ label: '关闭', value: 0 },
			],
			formValidate: createDefaultCouponForm(),
			ruleValidate: {
				name: [
					{
						required: true,
						message: '请输入优惠券名称',
						trigger: 'blur',
					},
				],
				station_id: [
					{
						required: true,
						message: '请选择适用站点',
						trigger: 'change',
					},
				],
				user_type: [
					{
						required: true,
						type: 'number',
						message: '请选择用户类型',
						trigger: 'change',
					},
				],
				threshold: [
					{
						required: true,
						type: 'number',
						message: '请输入使用门槛',
						trigger: 'change',
					},
				],
				value: [
					{
						required: true,
						type: 'number',
						message: '请输入优惠金额',
						trigger: 'change',
					},
				],
				expiration_time: [
					{
						required: true,
						type: 'date',
						message: '请选择过期时间',
						trigger: 'change',
					},
				],
				status: [
					{
						required: true,
						type: 'number',
						message: '请选择状态',
						trigger: 'change',
					},
				],
			},
		}
	},
	async mounted() {
		await this.fetchStationOptions()
		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 fetchStationOptions() {
			try {
				const res = await getStationList({
					page: 1,
					pageSize: 9999,
				})
				const list = res && res.data && Array.isArray(res.data.data) ? res.data.data : []
				this.stationOptions = list
					.map(item => ({
						charge_station_id: this.extractStationId(item),
						charge_station_name: this.extractStationName(item),
					}))
					.filter(option => option.charge_station_id)
			} catch (error) {
				this.$Message.error('获取站点列表失败，请稍后重试')
			}
		},
		// 搜索优惠券列表
		handleSubmit() {
			this.page = 1
			this.getList()
		},
		// 重置搜索条件
		handleReset() {
			this.formInline = {
				name: '',
				status: '',
			}
			this.handleSubmit()
		},
		// 查询优惠券列表数据
		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 getCouponList(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.normalizeCouponRow(item))
			} catch (error) {
				this.$Message.error('获取优惠券列表失败，请稍后重试')
			} finally {
				this.tableLoading = false
			}
		},
		// 正常化表格显示字段，保证列表列与站点管理页面风格统一
		normalizeCouponRow(item) {
			const stationLabel = this.resolveStationLabel(item)
			return {
				id: item.id,
				name: item.name || '--',
				stationLabel,
				userTypeText: Number(item.user_type) === 2 ? '会员用户' : '所有用户',
				thresholdText: this.formatAmount(item.threshold),
				valueText: this.formatAmount(item.value),
				expirationTimeText: this.formatTimestamp(item.expiration_time),
				statusText: Number(item.status) === 1 ? '开启' : '关闭',
				createTimeText: this.formatTimestamp(item.create_time),
			}
		},
		// 格式化金额，两位小数展示
		formatAmount(value) {
			if (value === undefined || value === null || value === '') {
				return '--'
			}
			const numberValue = Number(value)
			if (Number.isNaN(numberValue)) {
				return '--'
			}
			return numberValue.toFixed(2)
		},
		// 将时间戳转换为标准日期文案
		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}`
		},
		// 抽取站点 ID，兼容不同接口字段
		extractStationId(item) {
			const candidateKeys = ['charge_station_id', 'station_id', 'id']
			for (let i = 0; i < candidateKeys.length; i += 1) {
				const key = candidateKeys[i]
				const value = item && item[key]
				if (value !== undefined && value !== null && `${value}` !== '') {
					return String(value)
				}
			}
			return ''
		},
		// 抽取站点显示名，若接口只返回 ID 则兜底
		extractStationName(item) {
			if (!item) {
				return ''
			}
			return item.charge_station_name || item.station_name || item.name || ''
		},
		// 根据列表数据推断站点名称
		resolveStationLabel(item) {
			if (!item) {
				return '--'
			}
			if (item.station_name) {
				return item.station_name
			}
			if (item.station && item.station.charge_station_name) {
				return item.station.charge_station_name
			}
			const targetId = item.station_id ? String(item.station_id) : ''
			if (targetId) {
				const matched = this.stationOptions.find(option => option.charge_station_id === targetId)
				if (matched) {
					return matched.charge_station_name
				}
				return `站点-${targetId}`
			}
			return '--'
		},
		// 切换分页
		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 = createDefaultCouponForm()
			this.show_modal = true
			this.$nextTick(() => {
				if (this.$refs.formValidate) {
					this.$refs.formValidate.clearValidate()
				}
			})
		},
		// 查看并编辑任务
		async show(id) {
			if (!id) {
				return
			}
			try {
				const res = await getCoupon({ id })
				const detail = res && res.data ? res.data : {}
				this.formValidate = {
					...createDefaultCouponForm(),
					id: detail.id,
					name: detail.name || '',
					station_id: detail.station_id ? String(detail.station_id) : '',
					user_type: detail.user_type !== undefined ? Number(detail.user_type) : 1,
					threshold: this.normalizeNumber(detail.threshold),
					value: this.normalizeNumber(detail.value),
					expiration_time: this.transformTimestampToDate(detail.expiration_time),
					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
		},
		// 将时间戳转为 DatePicker 可识别的 Date 对象
		transformTimestampToDate(ts) {
			if (!ts) {
				return ''
			}
			const value = Number(ts)
			if (Number.isNaN(value)) {
				return ''
			}
			const date = `${value}`.length === 13 ? new Date(value) : new Date(value * 1000)
			return Number.isNaN(date.getTime()) ? '' : date
		},
		// 点击取消按钮
		cancel() {
			this.show_modal = false
			this.formValidate = createDefaultCouponForm()
			this.$nextTick(() => {
				if (this.$refs.formValidate) {
					this.$refs.formValidate.clearValidate()
				}
			})
		},
		// 提交新增/编辑
		async ok() {
			const valid = await new Promise(resolve => {
				this.$refs.formValidate.validate(validRes => {
					resolve(validRes)
				})
			})
			if (!valid) {
				this.$Message.error('请完善表单信息后再提交')
				return
			}
			this.submitLoading = true
			const payload = this.buildSubmitPayload()
			try {
				if (payload.id) {
					const res = await getCouponUpdate(payload)
					this.$Message.success(res.msg || '更新成功')
				} else {
					const res = await addCoupon(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.station_id = payload.station_id ? Number(payload.station_id) : ''
			payload.user_type = Number(payload.user_type)
			payload.threshold = Number(payload.threshold)
			payload.value = Number(payload.value)
			payload.status = Number(payload.status)
			payload.expiration_time = this.transformDateToTimestamp(payload.expiration_time)
			return payload
		},
		// DatePicker 值转时间戳（秒）
		transformDateToTimestamp(value) {
			if (!value) {
				return ''
			}
			if (typeof value === 'number') {
				return `${value}`.length === 10 ? value : Math.floor(value / 1000)
			}
			const date = value instanceof Date ? value : new Date(value)
			if (Number.isNaN(date.getTime())) {
				return ''
			}
			return Math.floor(date.getTime() / 1000)
		},
		// 删除优惠券
		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 getCouponDelete({ 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;
}
</style>
