<template>
	<div>
		<div class="search-area">
			<Form ref="formInline" :model="formInline" inline :label-width="120">
				<FormItem prop="user" label="时间">
					<Select v-model="formInline.time_type" clearable style="width:100px">
						<Option :value="1">天</Option>
						<Option :value="4">周</Option>
						<Option :value="2">月</Option>
						<Option :value="3">年</Option>
						<Option :value="5">自定义</Option>
					</Select>
					<DatePicker v-if="formInline.time_type == 1" :value="formInline.time" type="date"
						placeholder="请选择日期" style="width: 200px" @on-change="chage" />
					<DatePicker v-if="formInline.time_type == 2" type="month" placeholder="请选择日期" style="width: 200px"
						@on-change="chage" />
					<DatePicker v-if="formInline.time_type == 3" type="year" placeholder="请选择日期" style="width: 200px"
						@on-change="chage" />
					<DatePicker v-if="formInline.time_type == 4" type="daterange" show-week-numbers
						placement="bottom-end" placeholder="请选择日期" style="width: 200px" @on-change="chage" />
					<DatePicker v-if="formInline.time_type == 5" type="daterange" placement="bottom-end"
						placeholder="请选择日期" style="width: 200px" @on-change="chage" />
				</FormItem>
				<FormItem prop="password" label="充电站">
					<Select v-model="formInline.charge_station_id" style="width:200px" clearable
						@on-change="changeStation">
						<Option v-for="item in stationList" :value="item.charge_station_id"
							:key="item.charge_station_id">{{ item.charge_station_name }}</Option>
					</Select>
				</FormItem>
				<FormItem prop="password" label="充电桩">
					<Select v-model="formInline.connectorID" style="width:200px" clearable>
						<Option v-for="item in pileList" :value="item.ConnectorID" :key="item.charge_pile_id">
							{{ item.ConnectorID }}
						</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit('formInline')">搜索</Button>
				</FormItem>
			</Form>
		</div>
		<div id="main" ref="chartContainer" style="width: 100%; height: 400px;"></div>
		<div class="table-container">
			<Table border :columns="columns" :height="tableHeight" :data="data">
				<template #action="{ row, index }">
					<!-- <Button type="primary" size="small" style="margin-right: 5px" @click="show(index)">详情</Button> -->
				</template>
			</Table>
			<Page :total="total" show-total show-sizer class="page" @on-change="onChangePage"
				@on-page-size-change="onChangePageSize" />
		</div>
	</div>
</template>

<script>
	import * as echarts from 'echarts'
	import {
		getChargePile,
		getStationList,
		getPileList,
	} from '@/api'

	export default {
		name: 'Total',
		data() {
			return {
				data: [],
				page: 1,
				pageSize: 10,
				total: 100,
				tableHeight: 500,
				chartInstance: null,
				formInline: {
					charge_station_id: '',
					time_type: 1,
					connectorID: '',
					time: '',
				},
				stationList: [],
				pileList: [],
				columns: [{
						title: '充电桩编号',
						key: 'ConnectorID',
					},
					{
						title: '充电站名称',
						key: 'charge_station_name',
					},
					{
						title: '总电量',
						key: 'totalPower',
					},
					{
						title: '总时间',
						key: 'totalTimeFormatted',
					},
					{
						title: '总费用',
						key: 'totalPrice',
					},
				],
			}
		},
		mounted() {
			this.initChart()
			this.getStationList()
			this.getPileList()
			this.calculateTableHeight()
			window.addEventListener('resize', this.calculateTableHeight)
		},
		beforeDestroy() {
			if (this.chartInstance) {
				this.chartInstance.dispose()
			}
			window.removeEventListener('resize', this.handleResize)
			window.removeEventListener('resize', this.calculateTableHeight)
		},
		methods: {
			async initChart() {
				if (!this.$refs.chartContainer) return

				// 销毁旧实例
				if (this.chartInstance) {
					this.chartInstance.dispose()
				}

				this.formInline.time = new Date().toLocaleDateString().replace('///g', '-')
				this.chartInstance = echarts.init(this.$refs.chartContainer)

				const xAxisData = []
				const powerData = []
				const priceData = []
				const timeData = []

				await getChargePile({
					...this.formInline,
				}).then((res) => {
					this.data = res
					this.$nextTick()
					res.forEach((i) => {
						xAxisData.push(i.no)
						powerData.push(parseFloat(i.totalPower))
						priceData.push(parseFloat(i.totalPrice))
						timeData.push(parseFloat(i.totalTimeFormatted))
					})
				})
				const option = {
					color: ['#409eff', '#67C23A', '#E6A23C'],
					grid: {
						left: 5,
						right: 15,
						top: 40,
						bottom: 5,
						containLabel: true,
					},
					title: {
						text: '充电量、费用及时长统计',
						left: 'center',
					},
					tooltip: {
						trigger: 'axis',
						formatter: (params) => {
							const [power, price, time] = params
							return `
						        ${power.axisValue}<br>
						        ${power.seriesName}：${power.data} KW<br>
						        ${price.seriesName}：${price.data} 元<br>
								${time.seriesName}：${time.data} 小时
						      `
						},
					},
					legend: {
						data: ['总电量', '总费用', '总时长'],
						right: 80, // 距离右侧 10px
						top: 10, // 垂直居中
					},
					xAxis: {
						type: 'category',
						data: xAxisData,
					},
					yAxis: [{
							type: 'value',
							name: '电量/KW',
							axisLabel: {
								formatter: '{value} KW',
							},
						},
						{
							type: 'value',
							name: '费用/元',
							axisLabel: {
								formatter: '{value} 元',
							},
							min: 0,
							max: (value) => Math.ceil(value.max / 100) * 100, // 自动调整为100的整数倍
							interval: 100, // 每100元一个刻度
							splitNumber: 5, // 建议5-7个刻度
							axisLine: {
								lineStyle: {
									color: '#EE6666', // 设置轴线颜色与对应系列一致
								},
							},
						},
					],
					series: [{
							name: '总电量',
							type: 'line',
							smooth: true,
							label: {
								show: true,
								position: 'top',
							},
							lineStyle: {
								width: 3,
							},
							data: powerData,
						},
						{
							name: '总费用',
							type: 'line',
							smooth: true,
							label: {
								show: true,
								position: 'top',
							},
							lineStyle: {
								width: 3,
							},
							data: priceData,
						},
						{
							name: '总时长',
							type: 'line',
							smooth: true,
							label: {
								show: true,
								position: 'top',
							},
							lineStyle: {
								width: 3,
							},
							yAxisIndex: 1,
							data: timeData,
						},
					],
				}

				this.chartInstance.setOption(option)

				// 响应式调整
				window.addEventListener('resize', this.handleResize)
			},
			calculateTableHeight() {
				// 计算表格高度 = 窗口高度 - 搜索区域高度 - 分页高度 - 其他间距
				const searchHeight = document.querySelector('.search-area').offsetHeight
				const pageHeight = 32 // 分页组件大约高度
				const margins = 40 // 上下边距总和
				this.tableHeight = window.innerHeight - searchHeight - pageHeight - margins - 230
			},
			handleResize() {
				if (this.chartInstance) {
					this.chartInstance.resize()
				}
			},
			async getStationList() {
				await getStationList({
					page: 1,
					pageSize: 999,
				}).then((res) => {
					this.stationList = res.data.data
				})
			},
			async getPileList() {
				await getPileList({
					page: 1,
					pageSize: 999,
					charge_station_id: this.formInline.charge_station_id,
				}).then((res) => {
					this.pileList = res.data.data
				})
			},
			chage(e) {
				this.formInline.time = ''
				this.formInline.start_time = ''
				this.formInline.end_time = ''
				if (this.formInline.time_type == 4 || this.formInline.time_type == 5) {
					this.formInline.start_time = e[0]
					this.formInline.end_time = e[1]
				} else {
					this.formInline.time = e
				}
			},
			handleSubmit() {
				this.initChart()
			},
			changeStation() {
				this.getPileList()
			},
		},
	}
</script>

<style scoped>
	#main {
		background: #fff;
		border-radius: 8px;
		padding: 20px;
		margin: 2px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.search-area {
		background-color: white;
		border: 1px solid #F3F7FD;
		padding-top: 2px;
		border-radius: 15px;
	}

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

	.page {
		margin-top: 10px;
		text-align: right;
	}
</style>