<template>
	<view>
		<view class="status_bar"></view>
		<view class="" style="position: relative;top: 44px;">
			<view style="position: fixed;z-index: 100;">
				<uni-nav-bar @clickLeft="clickLeft" left-icon="back" title="害虫统计"></uni-nav-bar>
			</view>
			<view class="statistics">
				<view class="top_text">
					<view :class="topindex==index?'title_text_color':'tltle_text'" v-for="(item,index) in toptext" :key="index" @click="changeindex(index)">
						{{item}}
					</view>
				</view>
				<view class="shuju_one">
					<p class="shuju_one_title">害虫趋势统计</p>
					<view class="shuju_one_btn">
						<view class="schedule_box">
							<view class="schedule" @click="pickertfone=!pickertfone">
								<p class="schedule_value">{{titletext[indexone]}}</p>
								<p class="schedule_icon">
									<u-icon name="arrow-down"></u-icon>
								</p>
							</view>
							<u-picker v-model="pickertfone" mode="selector" @confirm="confirmFun" :default-selector="[indexone]" :range="titletext"></u-picker>
							<view class="schedule" @click="pickertftwo=!pickertftwo" v-if="tishitf">
								<p class="schedule_value">{{wormdata[indextwo]}}</p>
								<p class="schedule_icon">
									<u-icon name="arrow-down"></u-icon>
								</p>
								<u-picker v-model="pickertftwo" mode="selector" @confirm="confirmFun2" :default-selector="[indextwo]" :range="wormdata"></u-picker>
							</view>
						</view>
					</view>
					<view class="canvastishi" v-if="!canvastishiTF">
						暂无数据
					</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>
				<view class="shuju_two">
					<p class="shuju_one_title">害虫比例</p>
					<view class="canvastishi" v-if="!canvastishiTF">
						暂无数据
					</view> 
					<canvas v-if="canvastishiTF" canvas-id="canvasRing" id="canvasRing" class="charts" @touchstart="touchRing" :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="shuju_table" v-if="tableval.length">
					<table class="table">
						<tr class="tr">
							<th>害虫名称</th>
							<th>害虫数量</th>
							<th>害虫比例</th>
						</tr>
						<tr class="tr" v-for="(item,index) in tableval" :key="index">
							<td class="td">{{item.name}}</td>
							<td class="td">{{item.data}}</td>
							<td class="td">{{(item.prop*100).toFixed(2)+"%"}}</td>
						</tr>
					</table>
				</view>
			</view>
		</view>
	</view>
</template>
<style lang="scss">
	.top_text {
		width: 90%;
		position: absolute;
		top: 54px;
		display: flex;
		left: 5%;

		.tltle_text {
			width: 50%;
			border: 2rpx solid #F0F0F0;
			text-align: center;
		}

		.title_text_color {
			width: 50%;
			border: 2rpx solid #64CC82;
			text-align: center;
		}
	}

	.tishi {
		position: absolute;
		top: 250rpx;
		left: 40%;
		font-size: 32rpx;
		color: #7A7373;
	}

	.shuju_one_title {
		font-size: 32rpx;
		font-weight: 700;
		width: 100%;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.shuju_one_btn {
		width: 90%;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;

		.schedule_box {
			display: flex;
		}

		.schedule {
			display: flex;
			width: 280rpx;
			height: 50rpx;
			border: 2rpx solid #F0F0F0;
			margin-left: 20rpx;

			.schedule_value {
				width: 70%;
				text-align: center;
				line-height: 50rpx;
				font-size: 24rpx;
			}

			.schedule_icon {
				width: 30%;
				background-color: #F2F2F2;
				text-align: center;
				line-height: 50rpx;
			}
		}
	}
</style>
<script>
	import uCharts from '../../../../components/js_sdk/u-charts/u-charts/u-charts.js';
	var canvaColumnA = null;
	var canvasRing = null;
	export default {
		data() {
			return {
				cWidth: '400',
				cHeight: '400',
				pixelRatio: 1,
				canvastishiTF: false,
				d_id: '',
				start_time: +new Date() - 24 * 60 * 60 * 1000,
				end_time: +new Date(),
				titletext: ["24小时", "近一个月", "近半年", "近一年"],
				device_id: '',
				pest_name: '',
				wormdata: [],
				pickertfone: false,
				pickertftwo: false,
				indexone: 0,
				indextwo: 0,
				tishitf: false,
				tishi: false,
				toptext: ["自动统计", "手动统计"],
				topindex: 0,
				tableval:[]
			}
		},
		methods: {
			async historys() { //获取统计虫子 自动统计 初始化统计 没有传入害虫名称
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.worm_lamp.pest_statistics',
					data: {
						d_id: this.d_id,
						start_time: parseInt(this.start_time / 1000),
						end_time: parseInt(this.end_time / 1000),
						pest_name: ""
					}
				})

				this.historydatas = res
				console.log(this.historydatas)
				if (this.historydatas.date.length == 0) {
					this.canvastishiTF = false
					this.tishitf = false
				} else {
					this.canvastishiTF = true
					this.tishitf = true
					this.wormdata = []
					for (var i = 0; i < res.percentage.length; i++) {
						this.wormdata.unshift(res.percentage[i].name_num)
					}
					this.wormdata.unshift("全部")
					var arr1 = []
					var arr2 = []
					var arr3 = []
					var xtitle = []
					var ringarr = []
					for (var i = 0; i < res.date.length; i++) {
						var times = new Date(res.date[i].addtime * 1000)
						xtitle.unshift(times.getMonth() + 1 + "/" + times.getDate() + "-" + times.getHours() + ":" + times.getMinutes())
						arr1.unshift(res.date[i].temperature == "" ? "0" : res.date[i].temperature)
						arr2.unshift(res.date[i].humidity == "" ? "0" : res.date[i].humidity)
						arr3.unshift(res.date[i]._sums == "" ? "0" : res.date[i]._sums)
					}
					var maxnumarr = []
					for(var i = 0; i < res.percentage.length; i++){
						var obj = {}
						obj.name = res.percentage[i].name_num
						obj.data = Number(res.percentage[i].sum)
						maxnumarr.unshift(obj)
					}
					var temp;
					for(var i=0;i<maxnumarr.length-1;i++){
					    for(var j=0;j<maxnumarr.length-1;j++){
					        if(maxnumarr[j].data<maxnumarr[j+1].data){
					            temp=maxnumarr[j];
					            maxnumarr[j]=maxnumarr[j+1];
					            maxnumarr[j+1]=temp;
					        }
					    }
					}
					
					if(maxnumarr.length<20){
						ringarr = maxnumarr
					}else{
						ringarr = maxnumarr.splice(0,20)
						this.tableval = maxnumarr.splice(20)
					}
					var tablevalsum = 0
					for(var i = 0; i < maxnumarr.length; i++){
						tablevalsum += maxnumarr[i].data
					}
					for(var i = 0; i < this.tableval.length; i++){
						this.tableval[i].prop = this.tableval[i].data/tablevalsum
					}
					console.log(this.tableval)
					console.log(maxnumarr)
					var obj = [{
						name: '温度',
						data: arr1,
						color: '#00E29D'
					}, {
						name: '湿度',
						data: arr2,
						color: '#6CBBFF'
					}, {
						name: '害虫总数',
						data: arr3,
						color: '#FF3F3F'
					}]
					this.showColumn("canvasColumnA", xtitle, obj)
					this.showRing(ringarr)
				}
			},
			async history() { //获取统计虫子 //自动统计 传入害虫名称统计  在historys之后
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.worm_lamp.pest_statistics',
					data: {
						pest_name: this.pest_name,
						d_id: this.d_id,
						start_time: parseInt(this.start_time / 1000),
						end_time: parseInt(this.end_time / 1000)
					}
				})
				this.historydatas = res
				console.log(this.historydatas)
				if (this.historydatas.date.length == 0) {
					this.canvastishiTF = false
					this.tishitf = false
				} else {
					this.canvastishiTF = true
					this.tishitf = true
					var arr1 = []
					var arr2 = []
					var arr3 = []
					var xtitle = []
					for (var i = 0; i < res.date.length; i++) {
						var times = new Date(res.date[i].addtime * 1000)
						xtitle.unshift(times.getMonth() + 1 + "/" + times.getDate() + "-" + times.getHours() + ":" + times.getSeconds())
						arr1.unshift(res.date[i].temperature == "" ? "0" : res.date[i].temperature)
						arr2.unshift(res.date[i].humidity == "" ? "0" : res.date[i].humidity)
						arr3.unshift(res.date[i]._sums == "" ? "0" : res.date[i]._sums)
					}
					var obj = [{
						name: '温度',
						data: arr1,
						color: '#00E29D'
					}, {
						name: '湿度',
						data: arr2,
						color: '#6CBBFF'
					}, {
						name: '害虫总数',
						data: arr3,
						color: '#FF3F3F'
					}]
					this.showColumn("canvasColumnA", xtitle, obj)
				}
			},
			// forecast.worm_lamp.pest_manual_statistics手动统计
			async selfhistorys() { //获取统计虫子 手动统计 初始化统计 不传入害虫名称
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.worm_lamp.pest_manual_statistics',
					data: {
						device_id: this.d_id,
						start_time: parseInt(this.start_time / 1000),
						end_time: parseInt(this.end_time / 1000)
					}
				})
				console.log(res)
				if (res.date.length == 0) {
					this.tishitf = false
					this.canvastishiTF = false
				} else {
					this.tishitf = true
					this.canvastishiTF = true
					this.wormdata = []
					for (var i = 0; i < res.date.length; i++) {
						this.wormdata.unshift(res.date[i].pest_name)
					}
					this.wormdata.unshift("全部")
					var arr1 = []
					var xtitle = []
					var ringarr = []
					for (var i = 0; i < res.date.length; i++) {
						var times = new Date(res.date[i].add_time * 1000)
						xtitle.unshift(times.getMonth() + 1 + "/" + times.getDate() + "-" + times.getHours() + ":" + times.getSeconds())
						arr1.unshift(res.date[i].pest_num == "" ? "0" : res.date[i].pest_num)
						var obj ={}
						obj.name = res.date[i].pest_name
						obj.data = Number(res.date[i].pest_num)
						ringarr.unshift(obj)
					}
					
					var obj = [{
						name: '害虫总数',
						data: arr1,
						color: '#00E29D'
					}]
					this.showColumn("canvasColumnA", xtitle, obj)
					this.showRing(ringarr)
				}
			},
			async selfhistory() { //获取统计虫子 //手动统计  传入害虫名称
				const res = await this.$myRequest({
					url: '/api/api_gateway?method=forecast.worm_lamp.pest_manual_statistics',
					data: {
						pest_name: this.pest_name,
						device_id: this.d_id,
						start_time: parseInt(this.start_time / 1000),
						end_time: parseInt(this.end_time / 1000)
					}
				})
				this.historydatas = res
				console.log(this.historydatas)
				if (res.date.length == 0) {
					this.tishitf = false
					this.canvastishiTF = false
				} else {
					this.tishitf = true
					this.canvastishiTF = true
					var arr1 = []
					var xtitle = []
					for (var i = 0; i < res.pests.pest_list.length; i++) {
						var times = new Date(res.pests.pest_list[i].add_time * 1000)
						xtitle.unshift(times.getMonth() + 1 + "/" + times.getDate() + "-" + times.getHours() + ":" + times.getMinutes())
						arr1.unshift(res.pests.pest_list[i].pest_num == "" ? "0" : res.pests.pest_list[i].pest_num)
					}
					var obj = [{
						name: '害虫总数',
						data: arr1,
						color: '#00E29D'
					}]
					this.showColumn("canvasColumnA", xtitle, obj)
				}
			},
			clickLeft() {
				uni.navigateBack({
					delta: 1
				})
			},
			confirmFun(index) {
				this.indexone = index[0]
				var now = new Date()
				this.$forceUpdate()
				if (index[0] == 0) {
					this.start_time = strrttime
					if (this.topindex == 0) {
						if (this.pest_name == '') {
							this.historys()
						} else {
							this.history()
						}
					} else {
						if (this.pest_name == '') {
							this.selfhistorys()
						} else {
							this.selfhistory()
						}
					}
				} else if (index[0] == 1) {
					var oldtime = now.setMonth(now.getMonth() - 1)
					this.start_time = parseInt(oldtime)
					if (this.topindex == 0) {
						if (this.pest_name == '') {
							this.historys()
						} else {
							this.history()
						}
					} else {
						if (this.pest_name == '') {
							this.selfhistorys()
						} else {
							this.selfhistory()
						}
					}
				} else if (index[0] == 2) {
					var oldtime = now.setMonth(now.getMonth() - 6)
					this.start_time = parseInt(oldtime)
					if (this.topindex == 0) {
						if (this.pest_name == '') {
							this.historys()
						} else {
							this.history()
						}
					} else {
						if (this.pest_name == '') {
							this.selfhistorys()
						} else {
							this.selfhistory()
						}
					}
				} else if (index[0] == 3) {
					var oldtime = now.setFullYear(now.getFullYear() - 1)
					this.start_time = parseInt(oldtime)
					if (this.topindex == 0) {
						if (this.pest_name == '') {
							this.historys()
						} else {
							this.history()
						}
					} else {
						if (this.pest_name == '') {
							this.selfhistorys()
						} else {
							this.selfhistory()
						}
					}
				}
			},
			confirmFun2(index) {
				console.log(index)
				console.log(this.wormdata)
				this.indextwo = index[0]
				if(this.indextwo==0){
					this.pest_name = ""
				}else{
					this.pest_name = this.wormdata[this.indextwo]
				}
				
				if (this.topindex == 0) {
					this.history()
				} else {
					this.selfhistory()
				}
			},
			changeindex(index) {
				this.tableval = []
				this.topindex = index
				if (this.topindex == 0) {
					this.pest_name = ''
					this.tishitf = false
					this.historys()
				} else {
					this.pest_name = ''
					this.tishitf = false
					this.selfhistorys()
				}
			},
			showColumn(id, xtitle, xinfo) {
				var _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: 5, //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 + ':' + item.data
					}
				});
			},
			showRing(data) {
				var _self = this
				const ctx = uni.createCanvasContext("canvasRing", this);
				canvasRing = new uCharts({
					
					context: ctx,
					type: 'ring',
					fontSize: 11,
					legend: {
						show:true,
					},
					extra: {
						ring: {
							offsetAngle: -45,
							ringWidth: 40 * _self.pixelRatio,
							labelWidth: 15
						}
					},
					background: '#FFFFFF',
					pixelRatio: _self.pixelRatio,
					series: data,
					animation: true,
					width: _self.cWidth * _self.pixelRatio,
					height: _self.cHeight * _self.pixelRatio,
					disablePieStroke: true,
					dataLabel: true,
				});
			},
			touchRing(e) {
				canvasRing.showToolTip(e, {
					format: function(item) {
						return item.name + ':' + item.data
					}
				});
			},
		},
		onLoad(option) {
			this.d_id = option.d_id
			this.device_id = option.device_id
			this.cWidth = uni.upx2px(650);
			this.cHeight = uni.upx2px(500);
			this.historys()
		}
	}
</script>

<style lang="scss">
	.shuju_one{
		position: absolute;
		top: 84px;
		width: 90%;
		left: 5%;
		box-shadow: 0 0 10rpx #bcb9ca;
		padding-top: 20rpx;
		box-sizing: border-box;
		height: 650rpx;

		.canvastishi {
			font-size: 32rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-left: -64rpx;
			margin-top: -21rpx;
		}
	}
	.shuju_two{
		position: absolute;
		top: 840rpx;
		width: 90%;
		left: 5%;
		box-shadow: 0 0 10rpx #bcb9ca;
		padding-top: 20rpx;
		box-sizing: border-box;
		height: 650rpx;
		margin-bottom: 40rpx;
		.canvastishi {
			font-size: 32rpx;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-left: -64rpx;
			margin-top: -21rpx;
		}
	} 
	.shuju_table{
		position: absolute;
		top: 1510rpx;
		width: 90%;
		left: 5%;
		box-shadow: 0 0 10rpx #bcb9ca;
		padding-top: 20rpx;
		box-sizing: border-box;
		margin-bottom: 40rpx;
		.table{
			.th,
			.td {
				padding: 5rpx;
				width: 240rpx;
				text-align: center;
				height: 52rpx;
				line-height: 52rpx;
				font-size: 28rpx !important;
			}
		}
	}
	.condition {
		position: absolute;
		top: 600rpx;
		display: flex;
		flex-wrap: wrap;
		width: 90%;
		left: 5%;
		box-shadow: 0 0 10rpx #bcb9ca;
		margin-bottom: 30rpx;

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

			.tr {
				display: flex;
				overflow: hidden;

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

		.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: 150rpx;
				height: 50rpx;
				line-height: 50rpx;
				font-size: 26rpx;
				text-align: center;
			}
		}
	}
</style>
