<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>测报系统</el-breadcrumb-item>
			<el-breadcrumb-item :to="{ path: '/index/cbd' }">虫情测报</el-breadcrumb-item>
			<el-breadcrumb-item>害虫统计</el-breadcrumb-item>
		</el-breadcrumb>
		<div class="equipInfo">
			<div class="equipMsg">
				<span>设备ID：{{id}}</span>
				<span>设备名称：{{equipname || '无'}}</span>
				<span>位置：{{equipaddress || '无'}}</span>
			</div>
			<div class="ctrl-check">
				<div class="time-check">
					<div>
						<el-button
							:type="btnSelected == '1'?'primary':'default'"
							size="mini"
							@click="timeBtnClick(1)"
						>24小时</el-button>
						<el-button
							:type="btnSelected == '2'?'primary':'default'"
							size="mini"
							@click="timeBtnClick(2)"
						>近一月</el-button>
						<el-button
							:type="btnSelected == '3'?'primary':'default'"
							size="mini"
							@click="timeBtnClick(3)"
						>近半年</el-button>
						<el-button
							:type="btnSelected == '4'?'primary':'default'"
							size="mini"
							@click="timeBtnClick(4)"
						>近一年</el-button>
						<el-date-picker
							size="mini"
							v-model="timeRange"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							@change="DateChange"
						></el-date-picker>
					</div>
				</div>
			</div>
		</div>
		<!-- 自动统计图 -->
		<div v-if="viewSwitch">
			<div>
				<el-row :gutter="10">
					<el-col :md="24" :lg="15">
						<el-card class="box-card">
							<template>
								<div class="chartsSelect">
									<el-select v-model="viewSwitch2" @change="screenInsect()" size="mini" placeholder="请选择">
										<el-option
											v-for="item in worms"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										></el-option>
									</el-select>
								</div>
							</template>
							<div class="charts">
								<highcharts :options="options" v-if="chartsShow"></highcharts>
								<div class="noDataClass" v-else>暂无数据</div>
							</div>
						</el-card>
					</el-col>
					<el-col :md="24" :lg="9">
						<el-card class="box-card">
							<div class="pie">
								<highcharts :options="options2" v-if="chartsShowA"></highcharts>
								<div class="noDataClass" v-else>暂无数据</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>
			<div class="dataTableSearch">
				<!-- <el-button type="primary" size="mini" @click.stop="dowonloadFile">导出</el-button> -->
			</div>
			<el-card class="box-card">
				<el-table :data="tableData" stripe style="width: 100%">
					<el-table-column
						v-for="(item,index) in tableHeadTxt"
						:key="index"
						:prop="item[1]"
						:label="item[0]"
					>
						<template slot-scope="scope">{{scope.row[scope.column.property]}}</template>
					</el-table-column>
				</el-table>
			</el-card>
		</div>
	</div>
</template>

<script>
import t from '../../../assets/ezuikit'
import PestList from './cbd_pest_library.js' //注意路径
export default {
	data() {
		return {
			id: this.$route.query.id,
			equipname: this.$route.query.name,
			equipaddress:this.$route.query.address,
			btnSelected: '2',
			allPest: PestList,
			currPests:[],
			options: {},
			options2: {},
			options3: {},
			options4: {},
			equip_name: '',
			worms: [
				// {
				// 	value: 1,
				// 	label: '蛾子'
				// },
				// {
				// 	value: 2,
				// 	label: '蚊子'
				// }
			],
			// 状态信息
			equipStatus: {},
			//总数据条数
			total: 0,
			// 自动统计动态表头
			tableHeadTxt: [
				['害虫名称', 'name'],
				['害虫数量', 'sum'],
				["统计时间", "time"]
			],
			// 表格数据
			tableData: [],
			tableDataA: [],
			timeRange: '',
			queryInfo: {
				begin: '',
				end: '',
				id: this.$route.query.id,
				page: 1
			},
			viewSwitch: 1,
			viewSwitch2: '',
			viewSwitch23:'',
			// 手动统计表头
			tableHeadTxtA: [
				['害虫名称', 'pest_name'],
				['害虫数量', 'pest_num'],
				['作物种类', 'crop_name'],
				['虫害阶段', 'pest_case'],
				['统计时间', 'add_time']
				// ["统计时间", "upl_time"]
			],
			chartsShow: true, //判断折线图是否为空
			chartsShowA: true, //判断统计图是否为空
			dropDown: [], //手动统计害虫名称下拉数据
			chartsLineShow: true, //判断折线图是否为空
			chartsPieShow: true //判断统计图是否为空
		}
	},
	watch: {
		viewSwitch(val) {
			this.btnSelected = '2'
		}
	},
	created() {
	},
	mounted() {
		this.timeBtnClick(2)
	},
	methods: {
		//筛选时间
		timeBtnClick(i) {
			this.btnSelected = i
			this.timeRange = ''
			if (i == 1) {
				this.queryInfo.begin = new Date(Date.now()- 24 * 3600000).toLocaleDateString().replace(/\//g,'-');
				this.queryInfo.end = new Date().toLocaleDateString().replace(/\//g,'-');
			} else if (i == 2) {
				this.queryInfo.begin = new Date(Date.now()- 24 * 3600000 * 30).toLocaleDateString().replace(/\//g,'-');
				this.queryInfo.end = new Date().toLocaleDateString().replace(/\//g,'-');
			} else if (i == 3) {
				this.queryInfo.begin = new Date(Date.now()- 24 * 3600000 * 30 * 6).toLocaleDateString().replace(/\//g,'-');
				this.queryInfo.end = new Date().toLocaleDateString().replace(/\//g,'-');
			} else if (i == 4) {
				this.queryInfo.begin = new Date(Date.now()- 24 * 3600000 * 30 * 12).toLocaleDateString().replace(/\//g,'-');
				this.queryInfo.end = new Date().toLocaleDateString().replace(/\//g,'-');
			}
			this.getPestChartLine()
		},

		//获取折线图数据
		getPestChartLine() {
			this.$axios({
				method: 'POST',
				url: '/api/pest_at_ah_1',
				data: this.qs.stringify({
					e_id: this.queryInfo.id,
					tbegin: this.queryInfo.begin,
					tend: this.queryInfo.end,
				})
			}).then((res) => {
				this.disposeData(res.data)
				this.getTableList(res.data)
			})
		},
		// 处理返回数据格式  害虫数据格式[[[23432456,34],[23432421,3]],[[23432456,35],[23432421,76]]]
		disposeData(data) {
			var kind = data.kind;
			var worm = [];
			var atData = [];
			var ahData = [];
			// 折线
			var wormsArr = [];
			var html = '';
			if (!kind.length) {
				this.worms = [];
				this.viewSwitch2 = ''
			}
			for (var z = 0; z < kind.length; z++) {
				wormsArr.push({
					value:z,
					label:this.allPest[kind[z]]
				})
				if (z == kind.length - 1) {
					this.worms = wormsArr;
				}
			}

			for (var i = 0; i < data.dat1.length; i++) {
				var arr1 = [],
					arr2 = [];
				arr1.push(this.returnTime(data.dat1[i].time));
				arr1.push(parseFloat((data.dat1[i].at / 10).toFixed(1)));
				arr2.push(this.returnTime(data.dat1[i].time));
				arr2.push(parseFloat((data.dat1[i].ah / 10).toFixed(1)));
				atData.unshift(arr1);
				ahData.unshift(arr2);
				if (i == data.dat1.length - 1) {
					if (data.dat.length) {
						for (var j = 0; j < data.dat.length; j++) {
							var secondArr = [];
							var currTime = this.returnTime(data.dat[j].time)
							var resultArr = data.dat[j].result.split('#');
							for (var z = 0; z < resultArr.length; z++) {
								var thirdlyArr = [];
								var wormNameNum = resultArr[z].split(',')[0];
								var wormValNum = parseInt(resultArr[z].split(',')[1]);
								thirdlyArr.push(currTime)
								thirdlyArr.push(wormValNum);
								var wormIndex = kind.indexOf(wormNameNum);
								if (worm[wormIndex]) {
									worm[wormIndex].unshift(thirdlyArr);
								} else {
									worm[wormIndex] = [thirdlyArr];
								}
							}
							if (j == data.dat.length - 1) {
								this.currPests = worm
								this.currAtData = atData
								this.currAhData = ahData
								this.currWorm = worm
								this.currKind = kind
								this.chartLineInit(atData,ahData,worm[0],this.allPest[kind[0]])
								this.viewSwitch2 = this.allPest[kind[0]]
								var drawPieChartData = [];
								// 饼状图
								for (var ss = 0; ss < worm.length; ss++) {
									var currWormTotal = 0;
									for (var sss = 0; sss < worm[ss].length; sss++) {
										currWormTotal += worm[ss][sss][1];
										if (sss == worm[ss].length - 1) {
											drawPieChartData.push({
												name: this.allPest[kind[ss]],
												key: ss,
												y: currWormTotal
											})
										}
									}
									if (ss == worm.length - 1) {
										this.chartPieInit(drawPieChartData)
									}
								}
							}
						}
					} else {
						this.chartLineInit([],[],[],'')
						this.chartPieInit([])
					}
				}
			}


			if (data.dat1.length == 0) {
				this.chartLineInit([],[],[],'')
				this.chartPieInit([])
			}
		},
		// 返回时间戳
		returnTime(time) {
			var thisTime = time.replace(/-/g, '/');
			var time = new Date(thisTime);
			var timestamp = time.getTime() + 8 * 3600000;
			return timestamp;
		},
		DateChange() {
			console.log(this.timeRange)
			this.btnSelected = null;
			this.queryInfo.page = 1;
			if(this.timeRange){
				this.queryInfo.begin = new Date(this.timeRange[0]).toLocaleDateString().replace(/\//g,'-');
				this.queryInfo.end = new Date(this.timeRange[1]).toLocaleDateString().replace(/\//g,'-');
			}else{
				this.queryInfo.begin = '';
				this.queryInfo.end = '';
			}

			this.getPestChartLine()
		},
		//折线图初始化
		chartLineInit(atData,ahData,worm,wormName){
			this.options = {
				chart: {
					zoomType: 'x'
				},
				title: {
					text: '害虫变化趋势',
					align: 'left'
				},
				subtitle: {
					text: ''
				},
				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: 'center',
					verticalAlign: 'top'
				},
				plotOptions: {
					series: {
						label: {
							connectorAllowed: false
						},
						pointStart: 2010
					}
				},
				series: [
					{
						name: '环境温度',
						data: atData
					},
					{
						name: '环境湿度',
						data: ahData
					},
					{
						name: wormName,
						data: worm
					}
				],
				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>'
				},
				responsive: {
					rules: [
						{
							condition: {
								maxWidth: 500
							},
							chartOptions: {
								legend: {
									layout: 'horizontal',
									align: 'center',
									verticalAlign: 'bottom'
								}
							}
						}
					]
				}
			}
		},
		//饼状图初始化
		chartPieInit(arr) {
			var _this = this
			this.options2 = {
				chart: {
					type: 'pie',
					options3d: {
						enabled: true,
						alpha: 60,
						beta: 0
					}
				},
				credits: {
					enabled: false
				},
				title: {
					text: '害虫比例',
					align: 'left'
				},
				tooltip: {
					headerFormat: '{series.name}<br>',
					pointFormat: '{point.name}: <b>{point.y}头</b>'
				},
				colors: ['#00e29d', '#6cbbff', '#ff3f3f'],
				plotOptions: {
					pie: {
						allowPointSelect: true,
						cursor: 'pointer',
						dataLabels: {
							enabled: true,
							format: '<b>{point.name}</b>: {point.percentage:.1f} %'
						},
						point: {
							events: {
								mouseOver: function (e) {
									// 鼠标滑过时动态更新标题
									// console.log(e)
									// console.log(this.setTitle())
									// 标题更新函数，API 地址：https://api.hcharts.cn/highcharts#Chart.setTitle
									// VueHighcharts.setTitle({
									//    text: e.target.name+ '\t'+ e.target.y + ' %'
									// });
								},
								click(e) {
									// 同样的可以在点击事件里处理
									_this.viewSwitch2 = e.point.key;
									_this.screenInsect()
								}
							}
						}
					}
				},
				series: [
					{
						type: 'pie',
						innerSize: '80%',
						name: '害虫比例',
						data: arr
					}
				    ]
			    },
				function (c) {
					// 图表初始化完毕后的会掉函数
					// 环形图圆心
					var centerY = c.series[0].center[1],
						titleHeight = parseInt(c.title.styles.fontSize)
					// 动态设置标题位置
					c.setTitle({
						y: centerY + titleHeight / 2
					})
				}
		},
		//获取表格历史数据
		getTableList(data) {
			console.log(data)
			var dat = data.dat;
			var arr = [];
			for(var i = 0;i<dat.length;i++){
				var result = dat[i].result.split('#');
				for(var j = 0;j<result.length;j++){
					var resultItem = result[j].split(',');
					arr.push({
						name:this.allPest[resultItem[1]],
						sum:resultItem[0],
						time:dat[i].time
					})
				}
			}

			this.tableData = arr
		},

		// 下拉框筛选害虫名称
		screenInsect() {
			this.chartLineInit(this.currAtData,this.currAhData,this.currWorm[this.viewSwitch2],this.allPest[this.currKind[this.viewSwitch2]])
		},
		// 下载
		dowonloadFile(){
			window.location.href = '/api/pest_export?id=' + this.id + ' &filename="pestFile"'
		},
	}
}
</script>

<style lang='less' scoped>
.box-card {
	position: relative;
}
.equipInfo {
	.equipMsg {
		font-size: 14px;
		color: #3d3d3d;
		i {
			font-size: 16px;
			color: #14a478;
		}
		span {
			margin-left: 5px;
		}
	}
	display: flex;
	justify-content: space-between;
	margin-bottom: 15px;
}

.time-check {
	display: flex;
	justify-content: space-between;
	.el-input__inner {
		margin-left: 10px;
		width: 222px;
	}
	.viewSwitch {
		margin-left: 10px;
	}
}

.chartsSelect {
	text-align: right;
	position: absolute;
	z-index: 31;
	left: 0;
	right: 21px;
}
.charts,
.pie {
	height: 423px;
}
.equipStatus {
	display: flex;
	justify-content: center;
	margin: 10px 0;
	.equipIcon {
		margin-right: 14%;
	}
	.equipParams {
		min-width: 80px;
		line-height: 27px;
		p {
			color: #a6a6a6;
		}
	}
}

.dataTableSearch {
	display: flex;
	justify-content: space-between;
	margin: 20px 0;
	.el-input__inner {
		width: 222px;
	}
}

// .check-btns{display:flex;justify-content: space-between;margin-bottom:20px}
.echarts {
	width: 100%;
	height: 300px;
}

// 暂无数据
.noDataClass {
	text-align: center;
	font-size: 25px;
	line-height: 450px;
	color: rgb(122, 115, 115);
}
</style>