<template>
	<view style="background-color: #f7f7f7; height: 100vh;padding-top: 88rpx;">
		<!-- <view class="status_bar"></view> -->
		<view>
			<uni-nav-bar @clickLeft="clickLeft" left-icon="back" title="历史数据" backgroundColor="#f7f7f7"></uni-nav-bar>
		</view>
		<view style="padding: 0 48rpx; background-color: #f7f7f7;">
			<u-calendar v-model="dataShow" :mode="mode" @change="tiemchange" :maxDate="maxDate"></u-calendar>
			<view class="date" @click="dataShow = true">
				<span>选择日期 </span>
				<span style="color: #cccccc;">
					{{start_time}} <span style="margin: 0 10rpx;"> /</span> {{end_time}}
					<u-icon style="margin-left: 20rpx;" name="arrow-right" size="28"></u-icon>
				</span>
			</view>
			<view class="title">温湿度数据</view>
			<view class="shuju_one">

				<view class="canvastishi" v-if="!canvastishiTF && !dataloadingtf">
					暂无数据
				</view>
				<view class="canvastishi" v-if="dataloadingtf">
					<p class="dataloading">加载中</p>
				</view>
				<canvas v-if="canvastishiTF" canvas-id="canvasColumnA" id="canvasColumnA" class="charts"
					@touchstart="touchLineA($event)" @touchmove="moveLineA($event)" @touchend="touchEndLineA($event)"
					disable-scroll=true
					:style="{'width':cWidth*pixelRatio+'px','height':cHeight*pixelRatio+'px', 'transform': 'scale('+(1/pixelRatio)+')','margin-left':-cWidth*(pixelRatio-1)/2+'px','margin-top':-cHeight*(pixelRatio-1)/2+'px'}"></canvas>
			</view>
			<!-- 	<pest-line
			:device_type_id="device_type"
			:d_id="d_id"
			:start_time="start_time"
			:end_time="end_time"
			:notify="notify"
			></pest-line> -->
			<view class="title">监测数据

				<u-button size="mini" :loading='refreshLoading' class="refresh" throttle-time="500" @click="refresh"
					:customStyle="customStyle">刷 新</u-button>
			</view>

			<view class="condition">
				<scroll-view scroll-top="0" scroll-x="true" class="scroll-X">
					<table class="table" :style="tableStyle">
						<tr class="tr">
							<th style="background-color: #E6E8EB;" class="th" v-for="(value,key) in thdata" :key="key">
								{{value}}</th>
						</tr>
						<tr class="tr" v-for="(items,indexs) in historylistdata" :key="'b'+indexs" v-if="!forbidden">
							<td class="td" v-for="(value,key) in thdata">{{items[key]}}</td>
						</tr>
						<tr class="tr" v-if="forbidden">
							<td class="td" v-for="item in Object.keys(thdata)">暂无数据</td>
						</tr>
					</table>

				</scroll-view>
				<view class="pagenumber">
					<button @click="prev">上一页</button>
					<view class="pagenumber_page">
						第 {{page}} 页
					</view>
					<view class="pagenumber_page">
						共 {{pagesum}} 页
					</view>
					<button @click="next" :disabled="forbidden">下一页</button>
				</view>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	import uCharts from '../../../../components/js_sdk/u-charts/u-charts/u-charts.js';
	import pestLine from './pestLine.vue';
	var canvaColumnA = null;
	export default {
		data() {
			return {
				maxDate: '2050-12-31',
				styles: {
					// width: "650rpx",
					height: "400rpx"
				},
				d_id: '',
				start_time: "",
				end_time: "",
				historydatas: [],
				titletext: ["24小时", "近一个月", "近半年", "近一年"],
				titleidnex: 0,
				device_id: '',
				page: 1,
				historylistdata: [],
				thdata: {},

				forbidden: false,
				cWidth: '400',
				cHeight: '400',
				pixelRatio: 1,
				canvastishiTF: false, //暂无数据提示
				dataloadingtf: true, //加载中提示
				pagesum: 1,
				device_type: "",
				dataShow: false,
				mode: 'range',
				refreshLoading: false,
				notify: 0
			}
		},
		components: {
			pestLine
		},
		computed: {
			customStyle() {
				return {
					background: '#018B3F',
					fontSize: '12px',
					border: 'none',
					color: '#fff'
				}
			},
			tableStyle() {
				return {
					width: Object.keys(this.thdata).length * 150 + 'px'
				}
			}
		},
		methods: {
			tiemchange(e) {
				console.log(e)

				this.start_time = e.startDate
				this.end_time = e.endDate

				this.history()
				this.historylist()
				this.notify++

			},
			async history() { //历史数据列表折线图
				this.dataloadingtf = true
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=new_gateway.data_info.temp_hum',
					data: {
						device_type_id: this.device_type,
						id: this.d_id,
						start: +new Date(this.start_time + ' 00:00:00') / 1000,
						end: +new Date(this.end_time + ' 23:59:59') / 1000
					}
				})
				this.dataloadingtf = false
				let {
					data,
					title
				} = res
				if (!data) {
					this.canvastishiTF = false
				} else {
					this.canvastishiTF = true
					if (title.addtime) delete title.addtime

					let xtitle = []
					let chartData = []
					if (data.length > 0) {

						data.forEach(item => {
							// 处理时间戳
							xtitle.push(item.addtime.split(' ')[0])
						})
						Object.keys(title).forEach(key => {
							let obj = {
								name: title[key],
								index: key === 'lux' ? 1 : 0,
								data: []
							}
							for (var i = 0; i < data.length; i++) {
								if (key in data[i]) {
									// 判断data中是否值
									obj.data.push(data[i][key])
								}
							}
							chartData.push(obj)
						})

						console.log('温湿度数据：', chartData)
					}

					let yAxis = {
						data: [{
							position: 'left'
						}, {
							position: 'right'
						}]

					}
					// console.log('----温度:',obj)
					this.showColumn("canvasColumnA", xtitle, chartData, yAxis)
				}
			
			},

			//历史数据列表
			async historylist() {
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=new_gateway.data_info.history_data',
					data: {
						device_type_id: this.device_type,
						id: this.d_id,
						start: +new Date(this.start_time + ' 00:00:00') / 1000,
						end: +new Date(this.end_time + ' 23:59:59') / 1000,
						page: this.page
					}
				})
				this.refreshLoading = false
				// this.thdata = Object.values(res.title) 
				Object.keys(res.title).forEach(item => {
					this.$set(this.thdata, item, res.title[item])
				})

				this.historylistdata = res.data

				this.pagesum = Math.ceil(res.total / 10) || 1
				if (res.data.length == 0) {
					this.forbidden = true

				} else {
					this.forbidden = false

				}

				console.log(this.historylistdata, 'historylistdata')
			},
			// forecast.send_control.get_device_config 获取当前时间的数据
			async newdata() {
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.send_control.get_device_config',
					data: {
						device_type_id: 3,
						d_id: this.d_id,
						control_type: "data"
					}
				})
				if (res) {
					uni.showToast({
						title: '刷新成功',
						duration: 2000,
						icon: "none"
					});

					this.historylist()
				} else {
					uni.showToast({
						title: '刷新失败',
						duration: 2000,
						icon: "none"
					});
				}
			},
			refresh() { //获取当前时间的数据
				this.refreshLoading = true
				this.historylist()
			},

			prev() { //上一页
				if (this.page > 1) {
					this.page--
					this.historylist()
				}
			},
			next() { //下一页
				if (this.page < this.pagesum) {
					this.page++
					this.historylist()
				}
			},
			clickLeft() {
				uni.navigateBack({
					delta: 1
				})
			},
			showColumn(id, xtitle, xinfo, yAxis) {
				let _self = this
				const ctx = uni.createCanvasContext(id, this);
				canvaColumnA = new uCharts({
					context: ctx,
					type: 'line',
					legend: {
						position: "top"
					},
					fontSize: 11,
					background: '#FFFFFF',
					pixelRatio: 1,
					animation: true,
					dataLabel: false,
					categories: xtitle,
					series: xinfo,
					enableScroll: true, //开启图表拖拽功能
					xAxis: {
						disableGrid: true,
						type: 'grid',
						gridType: 'dash',
						itemCount: 4, //x轴单屏显示数据的数量，默认为5个
						scrollShow: true, //新增是否显示滚动条，默认false
						// scrollAlign: 'left', //滚动条初始位置
						scrollBackgroundColor: '#F7F7FF', //默认为 #EFEBEF
						scrollColor: '#DEE7F7', //默认为 #A6A6A6
					},
					yAxis: yAxis || {},
					width: _self.cWidth * 1,
					height: _self.cHeight * 1,
					extra: {
						line: {
							type: 'curve'
						}
					}
				});
			},
			touchLineA(e) {
				console.log(e)
				canvaColumnA.scrollStart(e);
			},
			moveLineA(e) {
				canvaColumnA.scroll(e);
			},
			touchEndLineA(e) {
				canvaColumnA.scrollEnd(e);
				//下面是toolTip事件，如果滚动后不需要显示，可不填写
				canvaColumnA.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},
		},
		onLoad(option) {
			this.d_id = option.d_id
			this.device_id = option.device_id
			this.device_type = option.device_type
			this.cWidth = uni.upx2px(650);
			this.cHeight = uni.upx2px(500);
			let endTime = +new Date() / 1000
			let startTime = endTime - 60 * 60 * 24

			this.end_time = this.formatTime(endTime * 1000, 'yyyy-MM-dd')
			console.log(this.end_time)
			this.start_time = this.formatTime(startTime * 1000, 'yyyy-MM-dd')
			setTimeout(() => {
				this.history()
				this.historylist()
			}, 1000)
		},
		onShow() {
			// this.end_time = +new  Date()/1000
			// this.start_time = this.end_time - 24 * 60 * 60
			// // this.formatTime(date, 'yyyy-MM-dd')
			// setTimeout(()=>{
			// 	this.history()
			// 	this.historylist()
			// },1000)
		},
		onPullDownRefresh() {
			this.history()
			this.historylist()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-calendar__action {
		display: flex;
		justify-content: space-around;

		.u-calendar__action__text {
			line-height: 25px;
		}
	}

	page {
		background: #f7f7f7;
	}

	.title {
		color: #999999;
		margin: 32rpx 0;
	}

	.date {
		height: 92rpx;
		line-height: 92rpx;
		border-radius: 92rpx;
		background: #fff;
		display: flex;
		justify-content: space-between;
		margin-top: 16rpx;
		padding: 0 48rpx;
		position: relative;

	}

	.shuju_one,
	.shuju_two {
		// position: absolute;
		// top: 54px;
		width: 100%;
		// left: 5%;
		// box-shadow: 0 0 10rpx #bcb9ca;
		padding-top: 20rpx;
		height: 550rpx;
		background-color: #fff;
		border-radius: 24rpx;

		.canvastishi {
			font-size: 32rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-left: -64rpx;
			margin-top: -21rpx;

			.dataloading:after {
				overflow: hidden;
				display: inline-block;
				vertical-align: bottom;
				animation: ellipsis 2s infinite;
				content: "\2026";
			}

			@keyframes ellipsis {
				from {
					width: 2px;
				}

				to {
					width: 15px;
				}
			}
		}


	}

	.refresh {
		// position: absolute;
		// top: 700rpx;
		// left: 5%;
		font-size: 12px;
		float: right;
		// padding: 0 10rpx;
		// height: 40rpx;
		// border-radius: 8rpx;
		// background-color: #018B3F;
		// color: #FFFFFF;
		// line-height: 40rpx;
		// text-align: center;
	}

	.condition {
		// position: absolute;
		// top: 770rpx;
		display: flex;
		flex-wrap: wrap;
		width: 100%;
		// left: 5%;
		// box-shadow: 0 0 10rpx #bcb9ca;
		margin-bottom: 30rpx;

		.scroll-X {
			width: 100%;
			margin: 20rpx auto;

			.table {
				width: 1620px;
			}

			.tr {
				display: flex;
				overflow: hidden;

				.th,
				.td {
					display: inline-block;
					padding: 4rpx;
					width: 286rpx;
					text-align: center;
					height: 52rpx;
					line-height: 52rpx;
					border: 2rpx solid #F1F1F1;
				}

				.th:first-child,
				.td:first-child {
					width: 300rpx;
				}
			}

			.tr:nth-child(2n-1) {
				// background-color: #f5fff8;
			}

			.tr:first-child {
				// background-color: #E6E8EB;
				color: #31373D;
			}
		}

		.pagenumber {
			display: flex;
			margin: 20rpx auto;

			button {
				width: 150rpx;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 26rpx;
				text-align: center;
				background-color: #17BB89;
				color: #FFFFFF;
			}

			.pagenumber_page {
				width: 100rpx;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 26rpx;
				text-align: center;
			}
		}
	}
</style>