<template>
	<div style="cursor: default">
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>环境监测系统</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/index/envi' }"
				>环境监测</el-breadcrumb-item
			>
			<el-breadcrumb-item>历史数据</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="check-btns">
			<div class="type-check">
				<el-button
					:type="0 == display ? 'primary' : 'default'"
					size="mini"
					@click="displayCheck(0)"
					>表格</el-button
				>
				<el-button
					:type="1 == display ? 'primary' : 'default'"
					size="mini"
					@click="displayCheck(1)"
					>图表</el-button
				>
			</div>
			<DateSearch @dateChange="dateChange"></DateSearch>
		</div>
		<el-card class="box-card" v-if="showControl">
			<el-table :data="hisData" stripe style="width: 100%">
				<el-table-column
					v-for="(item, index) in tableHead"
					:key="index"
					:width="item.property == 'date' ? '160px' : ''"
					:label="item.label"
					:prop="item.property"
				>
					<template slot-scope="scope">{{
						scope.row[scope.column.property]
					}}</template>
				</el-table-column>
			</el-table>
			<el-pagination
				background
				layout="prev, pager, next"
				:total="total"
				:current-page="queryInfo.page"
				@current-change="changePage"
			></el-pagination>
		</el-card>
		<div v-if="!showControl">
			<div v-if="isEchartData">
				<el-row :gutter="10">
					<el-col
						:xs="24"
						:sm="24"
						:md="12"
						:lg="8"
						:xl="6"
						v-for="(item, index) in echartOptions"
						:key="index"
					>
						<el-card class="box-card">
							<highcharts :options="item"></highcharts>
						</el-card>
					</el-col>
				</el-row>
			</div>
			<div v-else>
				<el-card class="box-card">
					<p style="text-align: center">暂无数据！</p>
				</el-card>
			</div>
		</div>
	</div>
</template>

<script>
import DateSearch from '@/components/DateSearch'
import Highcharts from 'highcharts'
import HighchartsNoData from 'highcharts/modules/no-data-to-display'
HighchartsNoData(Highcharts)
export default {
	data() {
		return {
			//总数据条数
			total: 0,
			queryInfo: {
				begin: '',
				end: '',
				device_id: this.$route.params.id,
				page: 1
			},
			//图表实时否有数据
			isEchartData: true,
			//表格和图表按钮样式切换参数
			display: '0', //0代表表格、1代表图表
			// 表格和图表显示切换控制
			showControl: true,
			//echarts图表参数
			echartOptions: [],
			// 动态表头
			tableHead: [],
			// 表格数据
			hisData: []
		}
	},
	methods: {
		//获取历史数据
		getHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=weather.weather.qxz_detail',
				data: this.qs.stringify({
					start_time: this.queryInfo.begin,
					end_time: this.queryInfo.end,
					page: this.queryInfo.page,
					device_id: this.queryInfo.device_id
				})
			}).then((res) => {
				this.total = Number(res.data.data.nums)
				if (res.data.data.nums > 0) {
					let arr1 = [{ label: '日期', property: 'date' }]
					let arr2 = []
					let conf = res.data.data.conf
					let data = res.data.data.data
					for (let i in conf) {
						let obj = {}
						if (conf[i]) {
							let arr = conf[i].split('#')
							obj.label = `${arr[0]}(${arr[1]})`
							obj.property = i
							arr1.push(obj)
						}
					}
					this.tableHead = arr1
					for (let item of data) {
						let obj = {}
						obj.date = this.formatTime(item.time * 1000)
						for (let i1 in item.dat) {
							if (item.dat[i1]) {
								obj[i1] =
									item.dat[i1].split('#')[0] == '-99.99'
										? 'N/A'
										: item.dat[i1].split('#')[0]
							}
						}
						arr2.push(obj)
					}
					this.hisData = arr2
				} else {
					this.hisData = []
				}
			})
		},
		//获取图表历史数据
		getEchartsHisDataList() {
			this.$axios({
				method: 'POST',
				url: '/api/api_gateway?method=weather.weather.qxz_data_chart',
				data: this.qs.stringify({
					begin: this.queryInfo.begin,
					end: this.queryInfo.end,
					device_id: this.queryInfo.device_id
				})
			})
				.then((res) => {
					this.echartsFn(res.data.data)
				})
				.catch((err) => {
					console.log(err)
				})
		},
		echartsFn(data) {
			let conf = data.conf
			let eData = data.data
			let ChartData = []
			if (conf && eData && eData.length > 0) {
				this.isEchartData = true
				for (let i in conf) {
					if (conf[i]) {
						//判断是否有值
						ChartData.push({
							name: i,
							tit: conf[i].split('#')[0],
							unit: conf[i].split('#')[1],
							dat: []
						})
					}
				}
				for (let m of eData) {
					//m是对象
					for (let n in m.dat) {
						//dat是对象 n是key
						for (let j of ChartData) {
							//j是对象
							if (j.name == n && m.dat[n].split('#')[0] != '-99.99') {
								j.dat.push([
									m.time * 1000 + 8 * 3600000,
									Number(m.dat[n].split('#')[0])
								])
							}
						}
					}
				}
			} else {
				this.isEchartData = false
			}
			console.log(ChartData)
			this.echartOptions = ChartData.map((item) => {
				return this.OptionFn(item)
			})
		},
		OptionFn(item) {
			return {
				title: {
					text: item.tit,
					align: 'left'
				},
				lang: {
					noData: '暂无数据'
				},
				noData: {
					style: {
						fontWeight: 'bold',
						fontSize: '15px',
						color: '#303030'
					}
				},
				xAxis: {
					crosshair: true, //十字基准线
					type: 'datetime',
					dateTimeLabelFormats: {
						//根据时间间距X轴自动显示哪种格式
						millisecond: '%H:%M:%S.%L',
						second: '%H:%M:%S',
						minute: '%H:%M',
						hour: '%H:%M',
						day: '%m-%d',
						week: '%m-%d',
						month: '%Y-%m',
						year: '%Y'
					}
				},
				yAxis: {
					title: { text: '' }
				},
				legend: {
					// layout: 'vertical',
					align: 'right',
					verticalAlign: 'top'
				},
				plotOptions: {
					series: {
						label: {
							connectorAllowed: false
						},
						pointStart: 2010 //该参数定义了数据点的起点
					}
				},
				series: [
					{
						name: item.name,
						data: item.dat
					}
				],
				colors: ['#00e29d', '#6cbbff', '#ff3f3f'],
				credits: {
					//去掉默认的highcharts.com
					enabled: false
				},
				tooltip: {
					// crosshairs: true,
					shared: true, //折线共享
					headerFormat: '<b>{point.x:%Y-%m-%e %H:%M:%S}</b><br>',
					pointFormatter: function () {
						return item.tit + '：' + this.y + item.unit
					}
				},
				responsive: {
					rules: [
						{
							condition: {
								maxWidth: 500
							},
							chartOptions: {
								legend: {
									layout: 'horizontal',
									align: 'center',
									verticalAlign: 'bottom'
								}
							}
						}
					]
				}
			}
		},
		//表格和图表切换
		displayCheck(a) {
			this.display = a
			if (a == 0) {
				this.showControl = true
				this.getHisDataList()
			} else if (a == 1) {
				this.showControl = false
				this.getEchartsHisDataList() //渲染echarts
			}
		},
		//改变page
		changePage(val) {
			this.queryInfo.page = val
			this.getHisDataList()
		},
		dateChange(data) {
			this.queryInfo.page = 1
			this.queryInfo.begin = data.begin
			this.queryInfo.end = data.end
			if (this.display == 0) {
				this.getHisDataList()
			} else if (this.display == 1) {
				this.getEchartsHisDataList()
			}
		}
	},
	components: {
		DateSearch
	}
}
</script>

<style lang='less' scoped>
.check-btns {
	display: flex;
	justify-content: space-between;
	margin-bottom: 15px;
}
.echarts {
	width: 100%;
	height: 300px;
}
//时间段选择框的宽度
.el-date-editor--daterange.el-input__inner {
	width: 220px;
}
</style>