<template>
	<div class="container">
		<div class="search-area">
			<Form ref="formInline" inline :label-width="120" :model="formInline" :rules="ruleInline">
				<FormItem prop="user" label="充电站名称：">
					<Input type="text" clearable v-model="formInline.charge_station_name" placeholder="" />
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit('formInline')">搜索</Button>
				</FormItem>
			</Form>
		</div>
		<div class="action-btn">
			<Button type="primary" @click="add">添加</Button>
			<!-- <Button type="error">删除</Button> -->
		</div>
		<div class="table-container">
			<Table border :columns="columns" stripe :height="tableHeight" :data="data">
				<template #action="{ row, index }">
					<Button type="primary" size="small" style="margin-right: 5px" @click="show(row.charge_pile_id)">编辑</Button>
					<Button type="error" size="small" @click="remove(row.charge_pile_id)">删除</Button>
				</template>
			</Table>
			<Page :total="total" show-total show-sizer class="page" @on-change="onChangePage"
				@on-page-size-change="onChangePageSize" />
		</div>

<!-- charge_station_id 所属充电站 -->
<!-- ConnectorID 充电桩编号 -->
<!-- no 位号 -->

		<!-- 添加、编辑 -->
		<Modal v-model="show_modal" :title="formValidate.charge_pile_id ? '编辑充电桩' : '添加充电桩'" :mask-closable="false"
			@on-ok="ok" @on-cancel="cancel">
			<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
				<FormItem label="所属充电站" prop="charge_station_id">
					<Select v-model="formValidate.charge_station_id" placeholder="请选择充电站" style="width: 240px"
						filterable>
						<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="ConnectorID">
					<Input v-model="formValidate.ConnectorID" placeholder="请输入充电桩编号" style="width: 240px" />
				</FormItem>
				<FormItem label="位号" prop="no">
					<Input v-model="formValidate.no" placeholder="请输入充电枪位号" style="width: 240px" />
				</FormItem>
			</Form>
		</Modal>
	</div>
</template>

<script>
	import {
		getPileList,
		addPile,
		getPileRead,
		getPileUpdate,
		getPileDelete,
		getStationList,
	} from '@/api'

	export default {
		name: 'charging_station',
		data() {
			return {
				page: 1,
				pageSize: 10,
				show_modal: false,
				total: 100,
				tableHeight: 500,
				formInline: {
					user: '',
					password: '',
				},
				ruleInline: {},
				columns: [{
							title: '站点名称',
							key: 'charge_station_name',
						},
						{
							title: '充电桩编号',
							key: 'ConnectorID',
						},
						{
							title: '充电桩状态',
							key: 'status_text',
						},
						{
							title: '位号',
							key: 'no',
						},
						{
							title: '操作',
							slot: 'action',
							width: 150,
							align: 'center',
						},
				],
				data: [],
				stationOptions: [], // 站点下拉缓存，避免重复请求
				formValidate: {
					// charge_pile_id 仅用于编辑态，后端凭此判断更新目标
					charge_pile_id: '',
					// charge_station_id 对应所属充电站主键
					charge_station_id: '',
					// ConnectorID 平台内唯一充电桩编号
					ConnectorID: '',
					// no 充电枪位号，方便现场定位
					no: '',
				},
				ruleValidate: {
					charge_station_id: [{
						required: true,
						message: '请选择所属充电站',
						trigger: 'change',
					}],
					ConnectorID: [{
						required: true,
						message: '请输入充电桩编号',
						trigger: 'blur',
					}],
					no: [{
						required: true,
						message: '请输入位号',
						trigger: 'blur',
					}],
				},
			}
		},
		mounted() {
			this.getList()
			this.fetchStationOptions()
			this.calculateTableHeight()
			window.addEventListener('resize', this.calculateTableHeight)
		},
		beforeDestroy() {
			window.removeEventListener('resize', this.calculateTableHeight)
		},
		methods: {
			// 提取站点 ID，兼容不同接口字段
			getStationId(source) {
				if (!source || typeof source !== 'object') {
					return ''
				}
				const idKeys = ['charge_station_id', 'id', 'station_id']
				for (let i = 0; i < idKeys.length; i += 1) {
					const key = idKeys[i]
					const candidate = source[key]
					if (candidate !== undefined && candidate !== null && `${candidate}` !== '') {
						return String(candidate)
					}
				}
				return ''
			},
			// 提取显示名称，保持兜底描述
			getStationLabel(source, fallbackValue = '') {
				if (!source || typeof source !== 'object') {
					return fallbackValue ? `站点-${fallbackValue}` : ''
				}
				const label = source.charge_station_name
					|| source.station_name
					|| source.name
				if (label) {
					return label
				}
				return fallbackValue ? `站点-${fallbackValue}` : ''
			},
			calculateTableHeight() {
				// 计算表格高度 = 窗口高度 - 搜索区域高度 - 分页高度 - 其他间距
				const searchHeight = document.querySelector('.search-area').offsetHeight
				const actionBtnHeight = document.querySelector('.action-btn').offsetHeight
				const pageHeight = 32 // 分页组件大约高度
				const margins = 40 // 上下边距总和
				this.tableHeight = window.innerHeight - actionBtnHeight - searchHeight - pageHeight - margins - 130
			},
			// 获取充电站列表，保持与电价管理页面一致的下拉选项
			async fetchStationOptions() {
				try {
					const res = await getStationList({
						page: 1,
						pageSize: 9999,
					})
					const list = res && res.data && Array.isArray(res.data.data) ? res.data.data : []
					const normalizedList = list.map((item) => {
						const id = this.getStationId(item)
						if (!id) {
							return null
						}
						return {
							charge_station_id: id,
							charge_station_name: this.getStationLabel(item, id),
						}
					}).filter(option => option)
					this.stationOptions = normalizedList
					return normalizedList
				} catch (error) {
					this.$Message.error('获取充电站列表失败，请稍后重试')
					return []
				}
			},
			async getList() {
				await getPileList({
					page: this.page,
					pageSize: this.pageSize,
					...this.formInline,
				}).then((res) => {
					this.total = res.data.total
					this.data = res.data.data
				})
			},
			handleSubmit() {
				this.getList()
			},
			async add() {
				if (!this.stationOptions.length) {
					await this.fetchStationOptions()
				}
				Object.assign(this.formValidate, {
					charge_pile_id: '',
					charge_station_id: '',
					ConnectorID: '',
					no: '',
				})
				this.show_modal = true
				this.$nextTick(() => {
					if (this.$refs.formValidate) {
						this.$refs.formValidate.resetFields()
					}
				})
			},
			cancel() {
				if (this.$refs.formValidate) {
					this.$refs.formValidate.resetFields()
				}
				this.show_modal = false
			},
			async show(id) {
				if (!this.stationOptions.length) {
					await this.fetchStationOptions()
				}
				await getPileRead({ id }).then(res => {
					const detail = (res && res.data) || {}
					const stationId = this.getStationId(detail)
					Object.assign(this.formValidate, {
						charge_pile_id: detail.charge_pile_id || '',
						charge_station_id: stationId || '',
						ConnectorID: detail.ConnectorID || '',
						no: detail.no || '',
					})
					this.show_modal = true
				})
			},
			async remove(id) {
				const confirm = await new Promise(resolve => {
					this.$Modal.confirm({
						title: '确认删除',
						content: '您确定要删除此项吗？',
						onOk: () => resolve(true),
						onCancel: () => resolve(false),
					})
				})
				if (!confirm) {
					this.$Message.info('已取消删除')
					return
				}
				await getPileDelete({ id }).then(res => {
					this.$Message.success(res.msg)
					this.getList()
				})
			},
			async ok() {
				const valid = await new Promise(resolve => this.$refs.formValidate.validate(resolve))
				if (!valid) {
					this.$Message.error('请正确填写表单')
					return
				}
				const payload = { ...this.formValidate }
				if (payload.charge_pile_id) {
					await getPileUpdate(payload).then(res => {
						this.$Message.success(res.msg)
						this.getList()
						this.cancel()
					})
				} else {
					await addPile(payload).then((res) => {
						this.$Message.success(res.msg)
						this.cancel()
						this.getList()
					})
				}
			},
			onChangePage(e) {
				if (this.page != e) {
					this.page = e
					this.getList()
				}
			},
			onChangePageSize(e) {
				if (this.pageSize != e) {
					this.page = 1
					this.pageSize = e
					this.getList()
				}
			},
		},
	}
</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>
