<template>
	<view>
		<view class="">
			<view class="selecttimes" @click="tiemshow=!tiemshow">
				<view class="timesbox">
					<image
						:src="'https://www.hnyfwlw.com:8006/bigdata_app'+'/image/prevention/1acfe2751c01d3786cdc49b83d7e505.png'"
						mode=""></image>
					<p>{{timetab(oldtime)}}</p>
					<p class="or">~</p>
					<p>{{timetab(newtime)}}</p>
					<u-icon name="rili" custom-prefix="custom-icon" class="icon"></u-icon>
				</view>
				<u-calendar v-model="tiemshow" mode="range" @change="tiemchange"></u-calendar>
			</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" v-show="!tiemshow" 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>
			<view class="refresh" @click="refresh">
				刷 新
			</view>
			<view class="condition">
				<scroll-view scroll-top="0" scroll-x="true" class="scroll-X">
					<table class="table">
						<tr class="tr">
							<th class="th" v-for="(item,index) in thdata" :key="'a'+index">{{item}}</th>
						</tr>
						<tr class="tr" v-for="(items,indexs) in eqlistdata[0].length" :key="'b'+indexs">
							<td class="td" v-for="(item,index) in eqlistdata" :key="'c'+index">{{item[indexs]}}</td>
							<!-- |timeFormat() -->
						</tr>
						<tr class="tr" v-if="!forbidden">
							<td class="td" v-for="item in 12">暂无数据</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>
</template>
<style lang="scss">

</style>
<script>
	import uCharts from '../../components/js_sdk/u-charts/u-charts/u-charts.js';
	var canvaColumnA = null;
	var presenttime = null
	// var oldpresenttime = presenttime - 24*60*60*1000
	export default {
		data() {
			return {
				thdata: ["上报时间"],
				eqlistdata: [[]],
				cWidth: '400',
				cHeight: '400',
				pixelRatio: 1,
				oldtime: '',
				newtime: '',
				page: 1,
				forbidden: false, //暂无数据
				times: {
					d_id: null,
					start_time: null,
					end_time: null,
					device_id: null
				},
				canvastishiTF: false, //折线图暂无数据提示
				dataloadingtf: true, //加载中提示
				pagesum: 1,
				tiemshow: false, //日历选择器
			}
		},
		// 页面加载执行的函数
		onLoad(option) {
			this.times.device_id = option.device_id
			// this.times.imei = option.imei
			this.cWidth = uni.upx2px(650);
			this.cHeight = uni.upx2px(500);
			presenttime = +new Date();
			this.oldtime = parseInt((presenttime - 30 * 24 * 60 * 60 * 1000) / 1000)
			this.newtime = parseInt(presenttime / 1000)
			setTimeout(() => {
				this.getServerData(parseInt(presenttime / 1000), parseInt((presenttime - 30 * 24 * 60 * 60 *
					1000) /
					1000))
				this.historydata(parseInt(presenttime / 1000), parseInt((presenttime - 30 * 24 * 60 * 60 * 1000) /
					1000))
			}, 1000)
		},
		onShow() {

		},
		onPullDownRefresh() {
			console.log('refresh');
			this.getServerData(parseInt(presenttime / 1000), parseInt((presenttime - 24 * 60 * 60 * 1000) /
				1000))
			this.historydata(parseInt(presenttime / 1000), parseInt((presenttime - 24 * 60 * 60 * 1000) /
				1000))
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		methods: { // 
			//forecast.worm_lamp.device_polyline_data
			// 获取数据，发请求
			async getServerData(newtime, oldtimes) { //设备折线图
				this.dataloadingtf = true
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=weather.weather.sf_data_chart',
					data: {
						device_id: this.times.device_id,
						end: newtime,
						begin: oldtimes,
					}
				})
				this.dataloadingtf = false
				if (res.length == 0) {
					this.canvastishiTF = false
				} else {
					this.canvastishiTF = true
					var dataarr = res.conf.eleName.split("/")
					var elearr = res.conf.eleNum.split("/")
					var xtitle = []
					var arr = []
					var color = ['#F97000', '#00E29D', '#FF3F3F', '#6CBBFF', '#00E29D']
					for (var i = 0; i < dataarr.length; i++) {
						if (dataarr[i] != "-") {
							var valuearr = []
							for (var j = 0; j < res.dat.length; j++) {
								var numarr = JSON.stringify(res.dat[j].device_status).slice(2, -2)
								numarr = numarr.split(",")
								var numobj = {}
								for (var k = 0; k < numarr.length; k++) {
									numarr[k] = numarr[k].split(":")
									var index = numarr[k][0].indexOf("e") == -1 ? numarr[k][0].indexOf("j") : numarr[k]
										[0].indexOf("e")
									numobj[numarr[k][0].slice(index, -1)] = Number(numarr[k][1])
								}
								valuearr.unshift(numobj['e' + (i + 1)]) // + elelist[elearr[i]].unit
								var times = new Date(res.dat[j].uptime * 1000)
								xtitle.unshift(times.getMonth() + 1 + "/" + times.getDate() + "-" + times.getHours() +
									":" +
									times.getMinutes())
							}
							var obj = {
								name: dataarr[i],
								data: valuearr,
								color: color[i]
							}
							arr.push(obj)
						}
					}
					console.log(arr)
					this.showColumn("canvasColumnA", xtitle, arr)
				}
			},
			async historydata(newtime, oldtimes) { //设备表格数据
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=weather.weather.sf_data',
					data: {
						device_id: this.times.device_id,
						page: this.page,
						page_size: 10,
						begin: oldtimes,
						end: newtime,
					}
				})
				console.log(res)
				if (res.length == 0) {
					this.forbidden = false
				} else {
					this.pagesum = Math.floor(res.nums / 10) + 1
					this.forbidden = true
					this.eqlistdata = []
					var dataarr = res.conf.eleName.split("/")
					var elearr = res.conf.eleNum.split("/")
					this.thdata = ["上报时间"]
					var timearr = []
					for (var i = 0; i < dataarr.length; i++) {
						if (dataarr[i] != "-") {
							this.thdata.push(dataarr[i])
							var valuearr = []
							for (var j = 0; j < res.dat.length; j++) {
								var numarr = JSON.stringify(res.dat[j].device_status).slice(2, -2)
								numarr = numarr.split(",")
								var numobj = {}
								for (var k = 0; k < numarr.length; k++) {
									numarr[k] = numarr[k].split(":")
									var index = numarr[k][0].indexOf("e")
									numobj[numarr[k][0].slice(index, -1)] = Number(numarr[k][1])
								}
								valuearr.push(numobj['e' + (i + 1)]) // + elelist[elearr[i]].unit
							}
							console.log(valuearr)
							this.eqlistdata.push(valuearr)
							// console.log(valuearr)
						}
					}
					for (var j = 0; j < res.dat.length; j++) {
						// valuearr.unshift(numobj['e' + (i + 1)]) // + elelist[elearr[i]].unit
						timearr.push(this.tiemtag(res.dat[j].uptime))
					}
					this.eqlistdata.unshift(timearr)
					console.log(this.eqlistdata)
				}
			},
			prev() { //上一页
				if (this.page != 1) {
					this.page--
					this.historydata(this.newtime, this.oldtime)
				}
			},
			next() { //下一页
				if (this.page < this.pagesum) {
					this.page++
					this.historydata(this.newtime, this.oldtime)
				}
			},
			tiemchange(e) {
				console.log(e)
				this.oldtime = +new Date(e.startDate) / 1000
				this.newtime = +new Date(e.endDate) / 1000 + 16 * 60 * 60
				this.getServerData(this.newtime, this.oldtime)
				this.historydata(this.newtime, this.oldtime)
			},
			timetab(e) {
				e = new Date(e * 1000)
				var year = e.getFullYear()
				var month = e.getMonth() + 1 < 10 ? "0" + (e.getMonth() + 1) : e.getMonth() + 1
				var day = e.getDate() < 10 ? "0" + e.getDate() : e.getDate()
				var time = year + "/" + month + "/" + day
				return time
			},
			clickLeft() {
				uni.navigateBack({
					delta: 1
				})
			},
			showColumn(id, xtitle, xinfo) {
				var _self = this
				canvaColumnA = new uCharts({
					canvasId: id,
					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: {},
					width: _self.cWidth * 1,
					height: _self.cHeight * 1,
					extra: {
						line: {
							type: 'curve'
						}
					}
				});
			},
			showColumnb(id, xtitle, xinfo) {
				var _self = this
				canvaColumnB = new uCharts({
					canvasId: id,
					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: {},
					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 + ':' + Number(item.data).toFixed(3)
					}
				});
			},
			touchLineBb(e) {
				console.log(e)
				canvaColumnB.scrollStart(e);
			},
			moveLineBb(e) {
				canvaColumnB.scroll(e);
			},
			touchEndLineBb(e) {
				canvaColumnB.scrollEnd(e);
				//下面是toolTip事件，如果滚动后不需要显示，可不填写
				canvaColumnB.showToolTip(e, {
					format: function(item, category) {
						return category + ' ' + item.name + ':' + item.data
					}
				});
			},
			async newdata() {
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.send_control.get_device_config',
					data: {
						device_type_id: 2,
						d_id: this.times.d_id,
						control_type: "data"
					}
				})
				if (res) {
					uni.showToast({
						title: '刷新成功',
						duration: 2000,
						icon: "none"
					});
				} else {
					uni.showToast({
						title: '刷新失败',
						duration: 2000,
						icon: "none"
					});
				}
			},
			refresh() { //获取当前时间的数据
				this.newdata()
			},
			tiemtag(time) {
				var date = new Date(time * 1000)
				var year = date.getFullYear()
				var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
				var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
				var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours()
				var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()
				var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()
				return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
			}
		}
	}
</script>

<style lang="scss">
	/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
	.shuju_one {
		position: relative;
		width: 90%;
		box-shadow: 0 0 10rpx #bcb9ca;
		padding-top: 20rpx;
		height: 550rpx;
		margin: 30rpx auto;

		.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;
				}
			}
		}

		.shuju_one_title {
			width: 70%;
			margin: 0 auto;
			display: flex;

			.tltle_text {
				width: 25%;
				border: 2rpx solid #B2B2B2;
				color: #57c878;
				text-align: center;
				font-size: 24rpx;
				height: 50rpx;
				line-height: 50rpx;
			}

			.title_text_color {
				width: 25%;
				border: 2rpx solid #57c878;
				background-color: #57c878;
				color: #fff;
				text-align: center;
				font-size: 24rpx;
				height: 50rpx;
				line-height: 50rpx;
			}
		}

		.qiun-columns {
			.qiun-charts {
				width: 650upx;
				height: 400upx;
				background-color: #FFFFFF;
			}

			.charts {
				width: 650upx;
				height: 400upx;
				background-color: #FFFFFF;
			}
		}
	}

	.shuju_two {
		top: 790rpx;
	}

	.selecttimes {
		width: 90%;
		box-shadow: 0 0 10rpx #bcb9ca;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
		margin: 30rpx auto;

		.timesbox {
			display: flex;
			justify-content: space-around;

			image {
				width: 30rpx;
				height: 30rpx;
				margin-top: 6rpx;
			}

			.icon {
				color: #949494;
				text-align: right;
				margin-left: 30rpx;

			}
		}
	}

	.refresh {
		width: 160rpx;
		height: 50rpx;
		background-color: #57c878;
		color: #FFFFFF;
		line-height: 50rpx;
		text-align: center;
		box-shadow: 0 0 10rpx #bcb9ca;
		margin: 30rpx 5%;
	}

	.condition {
		display: flex;
		flex-wrap: wrap;
		width: 90%;
		box-shadow: 0 0 10rpx #bcb9ca;
		margin-bottom: 30rpx;
		margin: 30rpx auto;

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

			.tr {
				display: flex;
				overflow: hidden;

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

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

				.th:nth-last-child(1),
				.th:nth-last-child(2),
				.td:nth-last-child(1),
				.td:nth-last-child(2) {
					width: 200rpx;
				}
			}

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

			.tr:first-child {
				background-color: #57c878;
				color: #fff;
			}
		}

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

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

			.pagenumber_page {
				width: 150rpx;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 26rpx;
				text-align: center;
			}
		}
	}

	/deep/.u-calendar__action {
		display: flex;
		justify-content: space-around;

		.u-calendar__action__text {
			line-height: 25px;
		}
	}
</style>
