<template>
	<div class="app-container">
		<el-row>
			<el-col :span="8">
				<div class="cell cell-row1" v-loading="showTotalMoney.loading">
					<div class="cell-title">账户余额</div>
					<div class="cell-time">截止时间为 {{ showTotalMoney.time }}</div>
					<div class="cell-bottom">
						<div class="cell-bottom-amount">{{ showTotalMoney.amount.toFixed(2) }}</div>
						<div class="rmb1">¥</div>
					</div>
				</div>
			</el-col>
			<el-col :span="8">
				<div class="cell cell-row1" v-loading="showThisMonthRecharge.loading">
					<div class="cell-title">本月充值</div>
					<div class="cell-time">截止时间为 {{ showThisMonthRecharge.time }}</div>
					<div class="cell-bottom">
						<div class="cell-footer">
							<div class="cell-bottom-amount">{{ showThisMonthRecharge.amount.toFixed(2) }}</div>
							<div class="cell-footer-amount">线上：{{ showThisMonthRecharge.online_amount.toFixed(2) }}
							</div>
							<div class="cell-footer-amount">线下：{{ showThisMonthRecharge.offline_amount.toFixed(2) }}
							</div>
						</div>
						<div class="rmb2">¥</div>
					</div>
				</div>
			</el-col>
			<el-col :span="8">
				<div class="cell cell-row1" v-loading="showThisMonthConsume.loading">
					<div class="cell-title">本月消费</div>
					<div class="cell-time">截止时间为 {{ showThisMonthConsume.time }}</div>
					<div class="cell-bottom">
						<div class="cell-bottom-amount">{{ showThisMonthConsume.amount.toFixed(2) }}</div>
						<div class="rmb3">¥</div>
					</div>
				</div>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="8">
				<div class="cell">
					<el-card class="box-card" style="position: relative; height: 465px;">
						<div slot="header" class="clearfix">
							<img src="../../icons/images/index/zoushi.png" alt="">
							<span>用电消费走势图</span>
						</div>
						<el-date-picker v-model="showEchartsDate" @change="echartsDate_change" class="select-year" type="year" :picker-options="pickerOptions"
							:clearable="false" :editable="false" value-format="yyyy" placeholder="年份">
						</el-date-picker>
						<div id="main-echart" class="line-echart"></div>
					</el-card>
				</div>
			</el-col>
			<el-col :span="16">
				<div class="cell">
					<el-card class="box-card">
						<div slot="header" class="clearfix">
							<img src="../../icons/images/index/yujing.png" alt="">
							<span class="title-btn" :style="time_out_warning ? 'background-color: #3965FF;color:#ffffff' : ''"
								@click="time_out_warning_handle">超时预警</span>
							<span class="title-btn" :style="off_line_warning ? 'background-color: #3965FF;color:#ffffff' : ''"
								@click="off_line_warning_handle">离线预警</span>
						</div>
						<el-table :data="yujing_tableData" height="350" stripe :cell-style="cell_style" v-loading="airTimeoutWarning_loading"
							:header-cell-style="header_cell_style" v-if="time_out_warning" style="width: 100%">
							<el-table-column prop="deviceId" label="设备号" align="center"> </el-table-column>
							<el-table-column prop="warningTime" label="告警时间" align="center"> </el-table-column>
							<el-table-column prop="durationUse" label="使用时长" align="center"> </el-table-column>
							<el-table-column prop="contact" label="联系方式" align="center"> </el-table-column>
							<el-table-column prop="operator" label="操作人" align="center"> </el-table-column>
						</el-table>
						<el-table :data="yujing_tableData" height="350" stripe :cell-style="cell_style" v-loading="airTimeoutWarning_loading"
							:header-cell-style="header_cell_style" v-if="off_line_warning" style="width: 100%">
							<el-table-column prop="deviceId" label="空调设备" align="center"> </el-table-column>
							<el-table-column prop="room" label="房间号" align="center"> </el-table-column>
							<el-table-column prop="floor" label="楼层" align="center"> </el-table-column>
							<el-table-column prop="drom" label="楼栋" align="center"> </el-table-column>
							<el-table-column prop="warningTime" label="告警时间" align="center"> </el-table-column>
						</el-table>
					</el-card>
				</div>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="8">
				<div class="cell">
					<el-card class="box-card">
						<div slot="header" class="clearfix">
							<div class="card-header-between">
								<div class="card-title-left">
									<img src="../../icons/images/index/yewu.png" alt="">
									<span>办公室能耗排名top10</span>
								</div>
								<span class="card-desc pointer" @click="dialogTableVisible = true">查看更多&gt;&gt;</span>
								<el-dialog title="办公室能耗排名" :visible.sync="dialogTableVisible" width="530px" :close-on-click-modal="false">
									<el-table :data="gridData" height="540">
										<el-table-column property="date" label="房间号" align="center"></el-table-column>
										<el-table-column property="name" label="能耗KWH" align="center"></el-table-column>
										<el-table-column property="address" label="排名" align="center"></el-table-column>
									</el-table>
									<el-pagination class="dialog-page" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage3"
										:page-size="10" layout="prev, pager, next, jumper" :total="1000">
									</el-pagination>
								</el-dialog>
							</div>
						</div>
						<el-table :data="yewu_tableData" height="490" stripe :cell-style="handle_cell_style" :header-cell-style="header_cell_style"
							v-loading="realTimeBusinessInformation_loading" style="width: 100%" :show-header="true">
							<el-table-column prop="desc" label="房间号" align="center"></el-table-column>
							<el-table-column prop="desc" label="能耗KWH" align="center"></el-table-column>
							<el-table-column prop="desc" label="排名" align="center"></el-table-column>
						</el-table>
					</el-card>
				</div>
			</el-col>
			<el-col :span="16">
				<div class="cell">
					<el-card class="box-card">
						<div slot="header" class="clearfix">
							<div class="card-header-between">
								<div class="card-title-left">
									<img src="../../icons/images/index/zhuangtai.png" alt="">
									<span>空调实时状态</span>
									<div class="card-desc">设备总计：{{air_total}} 台</div>
									<div class="card-desc">已开机：{{air_on_total}} 台</div>
								</div>
								<div class="card-desc">A/B=已开机/总设备</div>
							</div>
						</div>
						<el-table :data="zhuangtai_tableData" height="490" stripe :cell-style="cell_style" :header-cell-style="header_cell_style"
							style="width: 100%" v-loading="airRealTimeMonitor_loading">
							<el-table-column v-for="col in cols" :prop="col.prop" :label="col.label" :align="col.align" :width="col.width">
							</el-table-column>
						</el-table>
					</el-card>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import {
		totalMoney,
		thisMonthRecharge,
		thisMonthConsume,
		airTimeoutWarning,
		getChart,
		airRealTimeMonitor,
		realTimeBusinessInformation
	} from '@/api/index';

	import * as echarts from 'echarts/core';
	import {
		TitleComponent,
		ToolboxComponent,
		TooltipComponent,
		GridComponent,
		LegendComponent
	} from 'echarts/components';
	import {
		LineChart
	} from 'echarts/charts';
	import {
		CanvasRenderer
	} from 'echarts/renderers';

	import {
		getFormatDateTime
	} from '@/utils/common';

	echarts.use([
		TitleComponent, ToolboxComponent, TooltipComponent, GridComponent, LegendComponent, LineChart,
		CanvasRenderer
	]);
	var getAirRealTimeMonitor, getRealTimeBusinessInformation;
	export default {
		data() {
			return {
				// 弹出框表格
				dialogTableVisible: false,
				// 弹出框表格
				gridData: [{
					date: '2016-05-02',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-04',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-01',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-03',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-02',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-04',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-01',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-03',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-02',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-04',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-01',
					name: '王小虎',
					address: '1518'
				}, {
					date: '2016-05-03',
					name: '王小虎',
					address: '1518'
				}],
				// 账户总余额
				showTotalMoney: {
					time: '0000/00/00 00:00:00',
					amount: 0.00,
					loading: false
				},
				// 本月充值
				showThisMonthRecharge: {
					time: '0000/00/00 00:00:00', // 时间
					amount: 0.00, // 总
					online_amount: 0.00, // 线上
					offline_amount: 0.00, // 线下
					loading: false
				},
				// 本月消费
				showThisMonthConsume: {
					time: '0000/00/00 00:00:00',
					amount: 0.00,
					loading: false
				},
				// 空调超时预警loading
				airTimeoutWarning_loading: false,
				// 空调实时监控loading
				airRealTimeMonitor_loading: false,
				// 实时业务信息，获取充值记录loading
				realTimeBusinessInformation_loading: true,
				// 选择年份范围
				pickerOptions: {
					disabledDate(time) {
						return (
							time.getFullYear() < "2022" || time.getFullYear() > new Date().getFullYear()
						);
					}
				},
				showEchartsDate: new Date().getFullYear() + '',
				// 表格单元格样式
				cell_style: {
					color: '#1A202B',
					'font-size': '16px',
					'font-family': 'Microsoft YaHei-3970(82674968)'
				},
				// 表格头部样式
				header_cell_style: {
					background: '#E6ECFE',
					color: '#1A202B',
					'font-size': '16px',
					'font-family': 'Microsoft YaHei-3970(82674968)'
				},
				// 预警表格数据
				yujing_tableData: [],
				// 业务表格数据
				yewu_tableData: [],
				// 状态表格数据
				zhuangtai_tableData: [],
				air_on_total: 0,
				air_total: 0,
				// 列
				cols: [],
				// 折线图数据
				option: {
					tooltip: {
						trigger: 'axis'
					},
					legend: {
						y: 'bottom',
						x: 'center',
						data: []
					},
					grid: {
						top: '10%',
						left: '3%',
						right: '3%',
						bottom: '8%',
						containLabel: true
					},
					toolbox: {
						feature: {
							saveAsImage: {
								show: false,
								title: '下载'
							}
						}
					},
					xAxis: {
						type: 'category',
						boundaryGap: false,
						data: []
					},
					yAxis: {
						name: '元',
						type: 'value'
					},
					series: []
				},
				time_out_warning: true,
				off_line_warning: false
			}
		},
		created() {
			// 获取总金额
			this.getTotalMoney()
			// 本月充值
			this.getThisMonthRecharge()
			// 本月消费
			this.getThisMonthConsume()
			// 空调超时预警
			this.getAirTimeoutWarning()
			// 用电消费走势图
			this.getChart()
			// 空调实时监控
			this.getAirRealTimeMonitor()
			getAirRealTimeMonitor = setInterval(() => {
				this.getAirRealTimeMonitor()
			}, 1000 * 60);
			// 实时业务信息，获取充值记录
			this.getRealTimeBusinessInformation()
			getRealTimeBusinessInformation = setInterval(() => {
				this.getRealTimeBusinessInformation()
			}, 1000 * 10);
		},
		beforeDestroy() {
			clearInterval(getAirRealTimeMonitor);
			clearInterval(getRealTimeBusinessInformation);
		},
		methods: {
			time_out_warning_handle() {
				this.time_out_warning = true;
				this.off_line_warning = false;
			},
			off_line_warning_handle() {
				this.time_out_warning = false;
				this.off_line_warning = true;
			},
			/**
			 * 实时业务信息，获取充值记录
			 */
			getRealTimeBusinessInformation() {
				this.realTimeBusinessInformation_loading = true

				let data = {
					page: 1,
					rows: 7
				}
				realTimeBusinessInformation(data).then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！');
						return;
					}
					if (res.code == 200) {
						this.yewu_tableData = [];
						let tmp = []
						for (var i = 0; i < res.rows.length; i++) {
							tmp.push({
								desc: res.rows[i].user_name + ' 充值',
								dataTime: res.rows[i].time
							});
						}
						this.yewu_tableData = tmp;
					} else {
						// this.$message.error('空调实时监控返回的数据异常！');
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.realTimeBusinessInformation_loading = false
			},
			/**
			 * 空调实时监控
			 */
			getAirRealTimeMonitor() {
				this.airRealTimeMonitor_loading = true

				airRealTimeMonitor().then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！');
						return;
					}
					if (res.code == 200) {
						// console.log(res.monthT);
						this.air_total = res.air_total;
						this.air_on_total = res.air_on_total;
						let data = res.monthT;
						let tmpData = [];
						let rowData = {};
						let columns = [{
							prop: 'floor', // 数据显示对应的列名
							label: '楼层', // 显示的标签
							align: "center", // 文本对齐方式
							width: 40 // 列宽
						}];
						for (var i = 0; i < data.length; i++) {
							rowData = {
								floor: data[i][0].floors
							};
							for (var j = 1; j < data[i].length; j++) {
								rowData[`Build_${j}`] = data[i][j].per
								if (columns.length == data[i].length) {
									continue;
								} else {
									// 不给宽度,自适应
									columns.push({
										prop: `Build_${j}`,
										label: data[i][j].build,
										align: "center"
									});
								}
							}
							tmpData.push(rowData);
						}
						this.cols = columns;
						this.zhuangtai_tableData = tmpData;
					} else {
						// this.$message.error('空调实时监控返回的数据异常！');
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.airRealTimeMonitor_loading = false
			},
			/**
			 * 获取折线图数据
			 */
			getChart() {
				this.echart_loading = true

				getChart({
					year: this.showEchartsDate
				}).then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！');
						return;
					}

					if (res.code == 200) {
						// console.log(res.monthT);
						let tmp = res.monthT.sort((a, b) => a.month.localeCompare(b.month));
						let legend_data = []
						let xAxis_data = []
						let series = []
						for (var i = 0; i < tmp.length; i++) {
							if (legend_data.indexOf(tmp[i].air_config) == -1) {
								legend_data.push(tmp[i].air_config)

								series.push({
									name: tmp[i].air_config,
									type: 'line',
									// smooth: true,
									data: []
								});
							}

							if (xAxis_data.indexOf(tmp[i].month) == -1) {
								xAxis_data.push(tmp[i].month)
							}
						}
						// 一般方法，无法解决数据缺失
						// for (var i = 0; i < series.length; i++) {
						//     for (var j = 0; j < xAxis_data.length; j++) {
						//         for (var k = 0; k < tmp.length; k++) {
						//             if (series[i].name == tmp[k].air_config && xAxis_data[j] == tmp[k].month) {
						//                 series[i].data.push(tmp[k].num);
						//             }
						//         }
						//     }
						// }
						// 通用方法，可以解决数据缺失
						for (var i = 0; i < series.length; i++) {
							for (var j = 0; j < xAxis_data.length; j++) {
								let tf = false;
								for (var k = 0; k < tmp.length; k++) {
									if (series[i].name == tmp[k].air_config && xAxis_data[j] == tmp[k].month) {
										series[i].data.push(tmp[k].num);
										tf = true;
									}
								}
								if (tf == false) {
									series[i].data.push(0.00);
								}
							}
						}

						for (var i = 0; i < xAxis_data.length; i++) {
							xAxis_data[i] = xAxis_data[i].split('-')[1]
						}
						// 初始化图表数据
						this.option.legend.data = legend_data
						this.option.xAxis.data = xAxis_data
						this.option.series = series
						// console.log(this.option);
					} else {
						this.option.legend.data = []
						this.option.xAxis.data = []
						this.option.series = []
						this.$message.success('用电消费走势图 暂无数据！');
					}
					// 初始化图表
					this.initCharts();
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.echart_loading = false
			},
			/**
			 * 选择年份改变了
			 */
			echartsDate_change() {
				// console.log(this.showEchartsDate);
				this.getChart()
			},
			/**
			 * 空调超时预警
			 */
			getAirTimeoutWarning() {
				this.airTimeoutWarning_loading = true

				airTimeoutWarning().then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！');
						return;
					}
					if (res.code == 200) {
						this.yujing_tableData = [];
						for (var i = 0; i < res.monthT.length; i++) {
							this.yujing_tableData.push({
								deviceId: res.monthT[i].dom + ' ' + res.monthT[i].air_name + ' ' + res.monthT[i].air_config,
								warningTime: res.monthT[i].time,
								operator: res.monthT[i].user_name,
								durationUse: res.monthT[i].duration_use,
								contact: res.monthT[i].phone
							})
						}
					} else {
						// this.$message.error('空调超时预警返回的数据异常！');
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.airTimeoutWarning_loading = false
			},
			/**
			 * 本月消费
			 */
			getThisMonthConsume() {
				this.showThisMonthConsume.loading = true

				thisMonthConsume().then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！')
						return
					}

					if (res.code == 200) {
						this.showThisMonthConsume.time = res.time
						this.showThisMonthConsume.amount = res.zongCo.tong
					} else {
						this.$message.error(res.message)
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.showThisMonthConsume.loading = false
			},
			/**
			 * 本月充值
			 */
			getThisMonthRecharge() {
				this.showThisMonthRecharge.loading = true

				thisMonthRecharge().then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！')
						return
					}

					if (res.code == 200) {
						this.showThisMonthRecharge.time = res.time
						this.showThisMonthRecharge.online_amount = res.zongRe.tong // 线上充值
						this.showThisMonthRecharge.offline_amount = res.zongRo.tong // 线下充值
						this.showThisMonthRecharge.amount = res.zongRe.tong + res.zongRo.tong // 总充值
					} else if (res.code == 205) {
						this.showThisMonthRecharge.time = getFormatDateTime('datetime');
						this.$message.error('本月充值：' + res.message)
					} else {
						this.showThisMonthRecharge.time = getFormatDateTime('datetime');
						this.$message.error('本月充值：' + res.message)
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.showThisMonthRecharge.loading = false
			},
			/**
			 * 获取总金额
			 */
			getTotalMoney() {
				this.showTotalMoney.loading = true

				totalMoney().then((res) => {
					// console.log(res);
					if (typeof res.code == 'undefined' || res.code == '') {
						this.$message.error('返回数据格式问题，code未获取到！')
						return
					}

					if (res.code == 200) {
						this.showTotalMoney.time = res.time
						this.showTotalMoney.amount = res.zongYu.tong
					} else {
						this.$message.error(res.message)
					}
				}).catch((err) => {
					// console.log(err);
					this.$message.error(err.message)
				});

				this.showTotalMoney.loading = false
			},
			/**
			 * 初始化折线图
			 */
			initCharts() {
				// 基于准备好的dom，初始化echarts实例
				var myChart = echarts.init(document.getElementById('main-echart'));
				// 绘制图表
				myChart.setOption(this.option, true);
			},
			// 表格某些列样式改变
			handle_cell_style({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				if (columnIndex === 1 || columnIndex === 2) {
					// 指定列号
					return "font-size:18px; color:#808080"
				} else {
					return "font-size:18px; color:#292B34"
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.app-container {
		background-color: #EFF2F7;
		padding: 10px;

		.el-row {

			.el-col {
				padding: 10px;

				.cell {
					padding: 10px;
					border-radius: 10px;
					background-color: #FFFFFF;
					// box-shadow: 5px 5px 15px #979797;
					box-shadow: 0px 3px 21px 0px rgba(60, 108, 254, 0.16);

					.cell-title {
						font-size: 28px;
						font-family: Microsoft YaHei-3970(82674968);
						font-weight: 400;
						color: #292B34;
					}

					.cell-time {
						margin-top: 10px;
						font-size: 18px;
						font-family: Microsoft YaHei-3970(82674968);
						font-weight: 400;
						color: #979797;
					}

					.cell-bottom {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin: 20px 0 0;

						.cell-bottom-amount {
							font-size: 40px;
							font-family: Microsoft YaHei-3970(82674968);
							font-weight: bold;
							color: #292B34;
						}

						.cell-footer {
							display: flex;
							flex-direction: row;
							justify-content: space-between;
							align-items: flex-end;
							font-family: Microsoft YaHei-3970(82674968);
							font-weight: bold;
							color: #292B34;

							.cell-footer-amount {
								font-size: 16px;
								margin-left: 10px;
							}
						}

						.rmb1 {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 60px;
							height: 60px;
							border-radius: 30px;
							font-size: 50px;
							color: #FDFDFF;
							background: linear-gradient(-45deg, #3965FF, #3055FE);
							box-shadow: 0 0 8px #3660FF;
						}

						.rmb2 {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 60px;
							height: 60px;
							border-radius: 30px;
							font-size: 50px;
							color: #FDFDFF;
							background: linear-gradient(-45deg, #FFB977, #FF5C5C);
							box-shadow: 0 0 8px #3660FF;
						}

						.rmb3 {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 60px;
							height: 60px;
							border-radius: 30px;
							font-size: 50px;
							color: #FDFDFF;
							background: linear-gradient(-45deg, #9187F0, #7760F1);
							box-shadow: 0 0 8px #3660FF;
						}
					}

					.box-card {
						border: none;
						box-shadow: none;
						color: #292B34;

						.clearfix {
							display: flex;
							align-items: center;
							font-size: 20px;
							font-family: Microsoft YaHei-3970(82674968);

							img {
								width: 24px;
								height: 24px;
								margin-right: 8px;
							}

							.card-header-between {
								display: flex;
								justify-content: space-between;
								align-items: center;
								width: 100%;

								.card-title-left {
									display: flex;
									align-items: center;
								}

								.card-desc {
									font-family: Microsoft YaHei-3970(82674968);
									font-size: 16px;
									margin-left: 20px;
								}

								.pointer {
									cursor: pointer;
									color: #3965FF;
									padding: 3px 5px;
								}

								.pointer:hover {
									color: #FFFFFF;
									background-color: #3965FF;
								}
								
								.dialog-page {
									margin-top: 10px;
								}
							}

							.title-btn {
								display: inline-block;
								padding: 8px;
								color: #3965FF;
								cursor: pointer;
							}

							.title-btn:hover {
								color: #FFFFFF;
								background-color: #3965FF;
							}
						}

						.select-year {
							position: absolute;
							right: 20px;
							top: 68px;
							width: 100px;
							z-index: 1;
							cursor: pointer;
						}

						.line-echart {
							width: 450px;
							height: 370px;
						}
					}
				}

				.cell-row1 {
					padding: 30px;
				}
			}
		}
	}
</style>