<!-- 全厂水量统计 -->
<template>
	<div class="app-container" id="app-container" style="height: 50%">
		<el-header id="app-header">
			<div class="left-panel">
				<el-select
                    v-model="query.type"
                    placeholder="查询类型"
                    clearable
                    class="headerSearch"
                    @change="typeCange"
                >
				<el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    ></el-option>
				</el-select>
				<el-date-picker 
					v-model="daterange" 
					type="datetimerange" 
					value-format="YYYY-MM-DD HH:mm:ss" 
					range-separator="至"
					start-placeholder="开始时间" 
					end-placeholder="结束时间"
					format="YYYY-MM-DD HH"
                    popper-class="tpc"
					v-if="query.type==3"
					@change="changeDate"/>
					
				<el-date-picker
					v-model="query.day"
					type="date"
					value-format="YYYY-MM-DD"
					format="YYYY-MM-DD"
					placeholder="天"
					v-if="query.type==0"
					style="margin-right: 6px"
				/>
				<el-date-picker
                    v-model="query.month"
                    type="month"
                    value-format="YYYY-MM"
                    format="YYYY-MM"
                    placeholder="查询月份"
                    v-if="query.type==1"
                    class="headerSearch"
                />
				<el-date-picker
				v-model="query.year"
                    type="year"
                    value-format="YYYY"
                    format="YYYY"
                    placeholder="查询年份"
                    v-if="query.type==2"
                    class="headerSearch"
					/>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="dateChange"
				></el-button>
				<el-button
					type="primary"
					@click="exportExcel()"
					:loading="exportLoading"
					v-auth="'export_excel'"
					>导出xlsx
				</el-button>
				<el-button type="primary" @click="handlePrint">打印 </el-button>
			</div>
		</el-header>
		<el-main>
			<el-card>
				<div>
					<div ref="print" id="myReport" class="printContainer">
						<el-table
							v-if="query.type==0"
							id="hourBaseTable"
							:data="tableDatas2"
							style="width: 100%"
							border
							:height="tableHeight"
							@cell-click="handleCellClick"
						>
							<el-table-column
								label="分类"
								prop="nickname"
								width="110"
								fixed
							>
							</el-table-column>
							<el-table-column label="单位" prop="unit" fixed>
							</el-table-column>
							<el-table-column
								v-for="(item, index) in 24"
								:key="item"
								:label="index + '时'"
								:prop="index + '时'"
								width="120"
							>
							</el-table-column>
							<el-table-column
								label="合计"
								prop="sum"
								width="130"
								fixed="right"
							>
							</el-table-column>
						</el-table>
						<el-table
							v-if="query.type==1"
							id="hourBaseTable"
							:data="tableDatas_day"
							style="width: 100%"
							border
							:height="tableHeight"
							@cell-click="handleCellClick1"
						>
							<el-table-column
								label="分类"
								prop="nickname"
								width="110"
								fixed
							>
							</el-table-column>
							<el-table-column label="单位" prop="unit" fixed>
							</el-table-column>
							<el-table-column
								v-for="item in xAxisData_day"
								:key="item"
								:label="item"
								:prop="item"
								width="120"
							>
							</el-table-column>
							<el-table-column
								label="合计"
								prop="sum"
								width="130"
								fixed="right"
							>
							</el-table-column>
						</el-table>
						<el-table
							v-if="query.type==2"
							id="hourBaseTable"
							:data="tableDatas_month"
							style="width: 100%"
							border
							:height="tableHeight"
							@cell-click="handleCellClick_month"
						>
							<el-table-column
								label="分类"
								prop="nickname"
								width="110"
								fixed
							>
							</el-table-column>
							<el-table-column label="单位" prop="unit" fixed>
							</el-table-column>
							<el-table-column
								v-for="item in months"
								:key="item"
								:label="item + '月'"
								:prop="item + '月'"
								width="120"
							>
							</el-table-column>
							<el-table-column
								label="合计"
								prop="sum"
								width="130"
								fixed="right"
							>
							</el-table-column>
						</el-table>
						<el-table
							v-if="query.type==3"
							id="hourBaseTable"
							:data="tableDatas_range"
							style="width: 100%"
							border
							:height="tableHeight"
							@cell-click="handleCellClick_range"
						>
							<el-table-column
								label="分类"
								prop="mpoint__nickname"
								fixed
								align="center"
							>
							</el-table-column>
							<el-table-column label="单位" prop="mpoint__unit" fixed align="center">
							</el-table-column>
							<el-table-column
								label = "总用水量" prop="total_val" fixed align="center">
							</el-table-column>
						</el-table>
					</div>
				</div>
				<div class="chartWrap" v-show="query.type==0">
						<div class="chartTitle">本日生产参数统计图</div>
						<scEcharts
							height="400px"
							width="1500px"
							:option="optionHour"
						></scEcharts>
					</div>
					<div class="chartWrap" v-show="query.type==1">
						<div class="chartTitle">本月生产参数统计图</div>
						<scEcharts
							height="400px"
							width="1500px"
							:option="optionDay"
						></scEcharts>
					</div>
					<div class="chartWrap" v-show="query.type==2">
						<div class="chartTitle">本年生产参数统计图</div>
						<scEcharts
							height="400px"
							width="1500px"
							:option="optionMonth"
						></scEcharts>
					</div>
			</el-card>
		</el-main>
		<el-dialog v-model="itemVisible" :title="itemChartTitle" width="1100px">
			<scEcharts
				height="400px"
				width="1033px"
				:option="option"
			></scEcharts>
			<template #footer>
				<slot name="footer"></slot>
			</template>
		</el-dialog>
	</div>
</template>
<script>
import scEcharts from "@/components/scEcharts";
export default {
	components: {
		scEcharts,
	},
	data() {
		return {
			days: 30,
			day: "",
			year: "",
			month: "",
			daterange:[],
			search_date: "",
			query:{
                    type:0,
					day:'',
                    year:'',
                    month:'',
                    yearStart:'',
					start_time:'',
					end_time:'',
                },
			mgroupObj: {},
			indexList: [],
			mpointList: [],
			tableDatas: [],
			options: [
				{id:0,name:'日统计'},
				{id:1,name:'月统计'},
				{id:2,name:'年统计'},
				{id:3,name:'时间段'},
			],
			tableDatas2: [],
			tableDatas_day:[],
			tableDatas_range:[],
			tableDatas_month:[],
			months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
			hours: [
				1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
				19, 20, 21, 22, 23, 24,
			],
			tableHeight: 600,
			itemChartTitle: "",
			itemChartData: [],
			itemChartXData: [],
			itemChartYData: [],
			itemChartLegend: [],
			itemChartSeries: [],
			gyhourlyData : [], 
			lvhourlyData : [],
			shhourlyData : [], // 用于存储每小时的数据
			gyhourlyData_month : [], 
			lvhourlyData_month : [],
			shhourlyData_month : [], // 用于存储每天的数据
			gyhourlyData_year : [], 
			lvhourlyData_year : [],
			shhourlyData_year : [], // 用于存储每月的数据
			timeStamp: null,
			itemVisible: false,
			exportLoading: false,
			xAxisData: [],
			optionDay:[],
			optionMonth:[],
			optionHour:[],
			xAxisData_day: [],
			xAxisData_month: [],
			xTtimeRange: [],
			tableName: "全厂电量小时统计",
			sourceData: {},
			option: {
				title: {
					// text: "全厂电量小时统计",
					x: "center",
				},
				grid: {
					top: "20%",
					left: "3%",
					right: "10%",
					bottom: "5%",
					containLabel: true,
				},
				legend: {
					orient: "horizontal",
					x: "right",
					y: "10",
					data: [],
				},
				xAxis: {
					type: "category",
					data: [],
					name: "时间",

					nameTextStyle: {
						fontWeight: 600,
						fontSize: 14,
					},
					axisLine: {
						lineStyle: {
							color: "#3366CC",
						},
					},
					axisLabel: {
						rotate: 45,
						interval: 0,
					},
					boundaryGap: false,
				},
				yAxis: {
					type: "value",
					name: "对象值",
					nameTextStyle: {
						fontWeight: 500,
						fontSize: 14,
					},
					axisLine: {
						lineStyle: {
							color: "#3366CC",
						},
					},
				},
				tooltip: {
					show: true,
					trigger: "axis",
					axisPointer: {
						type: "cross",
						axis: "auto",
						snap: true,
					},
					showContent: true,
				},
				series: [
					{
						name: "",
						data: [],
						type: "line",
						symbolSize: 8,
						symbol: "circle",
						smooth: 0.5,
						itemStyle: {
							normal: {
								label: {
									show: true,
								},
								lineStyle: {
									width: 1,
									type: "dotted",
									color: "#3366CC",
								},
							},
						},
					},
				],
			},
			bar_option: {
			legend: {
					top: "2%",
					data: ["烧成车间压缩空气(m3)", "原料车间压缩空气(m3)", "水泥磨压缩空气(m3)"]
				},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			xAxis: {
				type: 'category',
				data: [],
			},
			yAxis: {
				type: 'value',
				name: ''
			},
			series: [
				{
				name: '烧成车间压缩空气(m3)', // 此处修改为对应分类的名称
				type: 'bar',
				data: [], 
				itemStyle: {
					color: '#a9b6fe',
				},
				
			},
			{
				name: '原料车间压缩空气(m3)', // 此处修改为对应分类的名称
				type: 'bar',
				data: [], 
				itemStyle: {
					color: '#3398DB',
				},
				
			},
			{
				name: '水泥磨压缩空气(m3)', // 此处修改为对应分类的名称
				type: 'bar',
				data: [], 
				itemStyle: {
					color: '#EE6666',
				},
				
			},
			],
		},
		}
	},
	mounted() {
		let that = this;
		var nowDate = new Date();
		let year = nowDate.getFullYear();
		let month = nowDate.getMonth() + 1;
		let day = nowDate.getDate();
		that.timeStamp = nowDate.getTime();
		that.days = new Date(year, month, 0).getDate();
		that.day = day;
		that.year = year;
		that.month = month;
		for (let n = 0; n < 24; n++) {
			that.xAxisData.push(n + "时");
		}
		that.timeStamp = nowDate.getTime();
		that.headerLength = that.days + 4;
		that.tableWidth = that.headerLength * 100 + "";
		for (let n = 1; n < 13; n++) {
			that.xAxisData_month.push(n + "月");
		}
		for (let n = 1; n <= that.days; n++) {
			that.xAxisData_day.push(n + "日");
		}
		this.getMPoints();
		let heightContainer =
			document.getElementById("app-container").clientHeight;
		let heightHeader = document.getElementById("app-header").clientHeight;
		let heightTable = heightContainer - heightHeader - 35;
		that.tableHeight = heightTable;
	},
	methods: {
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			let that = this;
			if (columnIndex == 0) {
				if (that.indexList.indexOf(rowIndex) > -1) {
					let rowspans = that.mgroupObj[row.mgroupName];
					return {
						rowspan: rowspans,
						colspan: 1,
					};
				} else {
					return {
						rowspan: 1,
						colspan: 0,
					};
				}
			}
		},
		changeDate(){
			let obj = {};
			obj.type = "hour";
			obj.start_time = this.daterange[0];
			obj.end_time = this.daterange[1];
			obj.mpoint__in = "3632058107481669632,3632060127232065536,3658802207585144832";
			obj.page = 0;
			this.$API.enm.mpointstat.groupValues.req(obj).then((res) => {
				//处理res数组中的 total_val 字段 保留两位
				res.forEach(item => {
					item.total_val = Number(item.total_val).toFixed(2);
				});
				this.tableDatas_range = res;
			});
		},
		dateChange() {
			let that = this;
			that.tableDatas = [];
			let arr = [];
			if(that.query.type==0){//日
				arr = that.query.day.split('-');
				that.year = Number(arr[0]);
				that.month = Number(arr[1]);
				that.day = Number(arr[2]);
				that.dataLoop();
			}else if(that.query.type==1){//月
				let arr = that.query.month.split('-');
				that.year = Number(arr[0]);
				that.month = Number(arr[1]);
                that.days = new Date(that.year, that.month, 0).getDate();
                that.xAxisData_day = [];
                for (let n = 1; n <= that.days; n++) {
                    that.xAxisData_day.push(n + "日");
                }
				that.dataLoop1();
			}else if (that.query.type==2){
				that.year = that.query.year;
				that.dataLoop_month();
			}else if(that.query.type==3){//时间段
				that.xTtimeRange.push("总计")
			}
			let nowDate = new Date();
			that.timeStamp = nowDate.getTime();
			// that.getLengthData();
		},
		getMPoints() {
			let that = this;
			that.$API.enm.mpoint.list
				.req({
					page: 0,
					// enabled: 1,
					// need_display: 1,
					ordering: "report_sortstr",
					code__in: "20240613_13536,ylcjyskq,20240613_13590",
					query: "{ id, name, nickname, mgroup_name, unit, report_sortstr }",
				})
				.then((res) => {
					// that.mpointList = that.mockDatas.filter((item) => {
					that.mpointList = res
					that.dataLoop();
				});
		},
		dataLoop() {
			let that = this;
			that.tableDatas = [];
			that.tableDatas2 = [];
			let _mgroup = [],
				_nameLength = [],
				indexList = [];
			let mgroupObj = {};
			that.mpointList.forEach((item, index) => {
				let indexs = _mgroup.indexOf(item.mgroup_name);
				if (indexs > -1) {
					_nameLength[indexs] += 1;
				} else {
					_mgroup.push(item.mgroup_name);
					_nameLength.push(1);
					indexList.push(index);
				}

				for (let i = 0; i < _mgroup.length; i++) {
					mgroupObj[_mgroup[i]] = _nameLength[i];
				}
				let arr = [];
				arr[0] =
					item.mgroup_name != null ? item.mgroup_name : item.name;
				arr[1] = item.nickname != null ? item.nickname : item.name;
				arr[2] = item.unit;
				for (let i = 0; i < 24; i++) {
					arr[i + 3] = 0;
				}
				that.tableDatas.push(arr);
				let obj = {};
				obj.mgroupName =
					item.mgroup_name != null ? item.mgroup_name : item.name;
				obj.nickname =
					item.nickname != null && item.nickname != ""
						? item.nickname
						: item.name;
				obj.unit = item.unit;
				that.tableDatas2.push(obj);
				that.getData(item.id, index);
			});
			this.updateChart(that.gyhourlyData, that.shhourlyData, that.lvhourlyData)
			that.mgroupObj = mgroupObj;
			that.indexList = indexList;
		},
		getData(id, index) {
			let that = this;
			let obj = {};
			obj.type = "hour";
			obj.year = that.year;
			obj.month = that.month;
			obj.day = that.day;
			obj.mpoint = id;
			obj.page = 0;
			this.$API.enm.mpoint.stat.req(obj).then((res) => {
				let sum = 0;
				res.forEach((item) => {
					let ind = item.hour + 3;
					that.tableDatas[index][ind] = item.val;
					sum += Number(item.val);
					let keyName = item.hour + "时";
					that.tableDatas2[index][keyName] = item.val;
					if (item.mpoint_name == "窑中压缩空气累计"){
						that.gyhourlyData[item.hour] = item.val;
					}else if(item.mpoint_name == "水泥磨压缩空气累积量"){
						that.shhourlyData[item.hour] = item.val;
					}else if(item.mpoint_name == "原料车间压缩空气"){
						that.lvhourlyData[item.hour] = item.val;
					}
				});
				sum = sum * 100;
				sum = Math.round(sum);
				sum = sum / 100;
				that.tableDatas[index][27] = sum.toFixed(2);
				that.tableDatas2[index].sum = sum.toFixed(2);
				that.$forceUpdate();
			});
		},
		updateChart (gyhourlyData, shhourlyData, lvhourlyData){
			let that = this;
			let options = { ...that.bar_option };
			options.series[0].data = gyhourlyData;
			options.series[1].data = lvhourlyData;
			options.series[2].data = shhourlyData;
			options.xAxis.data = that.xAxisData;
			that.optionHour = options;
		},
		dataLoop1() {
			let that = this;
			that.tableDatas = [];
			that.tableDatas_day = [];
			let _mgroup = [],
				_nameLength = [],
				indexList = [];
			let mgroupObj = {};
			that.mpointList.forEach((item, index) => {
				let indexs = _mgroup.indexOf(item.mgroup_name);
				if (indexs > -1) {
					_nameLength[indexs] += 1;
				} else {
					_mgroup.push(item.mgroup_name);
					_nameLength.push(1);
					indexList.push(index);
				}

				for (let i = 0; i < _mgroup.length; i++) {
					mgroupObj[_mgroup[i]] = _nameLength[i];
				}
				let arr = [];
				arr[0] =
					item.mgroup_name != null
						? item.mgroup_name
						: item.nickname != null
						? item.nickname
						: item.name;
				arr[1] = item.nickname != null ? item.nickname : item.name;
				arr[2] = item.unit;
				for (let i = 0; i < that.days; i++) {
					arr[i + 3] = 0;
				}
				that.tableDatas.push(arr);
				let obj = {};
				obj.mgroupName =
					item.mgroup_name != null ? item.mgroup_name : item.name;
				obj.nickname =
					item.nickname != null && item.nickname != ""
						? item.nickname
						: item.name;
				obj.unit = item.unit;

				that.tableDatas_day.push(obj);
				that.getData1(item.id, index);
			});
			that.updateMonthChart(that.gyhourlyData_month, that.shhourlyData_month, that.lvhourlyData_month);
			that.mgroupObj = mgroupObj;
			that.indexList = indexList;
		},
		updateMonthChart(gyhourlyData, shhourlyData, lvhourlyData) {
			let that = this;
			let options = { ...that.bar_option };
			options.series[0].data = gyhourlyData;
			options.series[1].data = lvhourlyData;
			options.series[2].data = shhourlyData;
			options.xAxis.data = that.xAxisData_day;
			that.optionDay = options;
		},
		getData1(id, index) {
			let that = this;
			let obj = {};
			obj.type = "day";
			obj.year = that.year;
			obj.month = that.month;
			obj.mpoint = id;
			obj.page = 0;
			this.$API.enm.mpoint.stat.req(obj).then((res) => {
				let sum = 0;
				res.forEach((item) => {
					console.log(item, 'item');
					let ind = item.day + 2;
					that.tableDatas[index][ind] = item.val;
					sum += Number(item.val);
					let keyName = item.day + "日";
					that.tableDatas_day[index][keyName] = item.val;
					if (item.mpoint_name == "窑中压缩空气累计"){
						that.gyhourlyData_month[item.day] = item.val;
					}else if(item.mpoint_name == "水泥磨压缩空气累积量"){
						that.shhourlyData_month[item.day] = item.val;
					}else if(item.mpoint_name == "原料车间压缩空气"){
						that.lvhourlyData_month[item.day] = item.val;
					}
				});
				sum = sum * 100;
				sum = Math.round(sum);
				sum = sum / 100;
				let dayss = 0;
				dayss = this.days + 3;
				that.tableDatas[index][dayss] = sum.toFixed(2);
				that.tableDatas_day[index].sum = sum.toFixed(2);
				that.$forceUpdate();
			});
		},
		dataLoop_month() {
			let that = this;
			that.tableDatas = [];
			that.tableDatas_month = [];
			let _mgroup = [],
				_nameLength = [],
				indexList = [];
			let mgroupObj = {};
			that.mpointList.forEach((item, index) => {
				let indexs = _mgroup.indexOf(item.mgroup_name);
				if (indexs > -1) {
					_nameLength[indexs] += 1;
				} else {
					_mgroup.push(item.mgroup_name);
					_nameLength.push(1);
					indexList.push(index);
				}

				for (let i = 0; i < _mgroup.length; i++) {
					mgroupObj[_mgroup[i]] = _nameLength[i];
				}
				let arr = [];
				arr[0] =
					item.mgroup_name != null ? item.mgroup_name : item.name;
				arr[1] = item.nickname != null ? item.nickname : item.name;
				arr[2] = item.unit;
				for (let i = 0; i < 12; i++) {
					arr[i + 3] = 0;
				}
				that.tableDatas.push(arr);
				let obj = {};
				obj.mgroupName =
					item.mgroup_name != null ? item.mgroup_name : item.name;
				obj.nickname =
					item.nickname != null && item.nickname != ""
						? item.nickname
						: item.name;
				obj.unit = item.unit;
				that.tableDatas_month.push(obj);
				that.getData_month(item.id, index);
			});
			that.updateMonthChart_month(that.gyhourlyData_year, that.shhourlyData_year, that.lvhourlyData_year);
			that.mgroupObj = mgroupObj;
			that.indexList = indexList;
		},
		updateMonthChart_month(gyhourlyData, shhourlyData, lvhourlyData){
			let that = this;
			let options = { ...that.bar_option };
			options.series[0].data = gyhourlyData;
			options.series[1].data = lvhourlyData;
			options.series[2].data = shhourlyData;
			options.xAxis.data = that.xAxisData_month;
			that.optionMonth = options;
		},
		getData_month(id, index) {
			let that = this;
			let obj = {};
			obj.type = "month";
			obj.year = that.year;
			obj.mpoint = id;
			obj.page = 0;
			this.$API.enm.mpoint.stat.req(obj).then((res) => {
				console.log(res);
				let sum = 0;
				res.forEach((item) => {
					let ind = item.month + 2;
					that.tableDatas[index][ind] = item.val;
					sum += Number(item.val);
					let keyName = item.month + "月";
					that.tableDatas_month[index][keyName] = item.val;
					if (item.mpoint_name == "窑中压缩空气累计"){
						that.gyhourlyData_year[item.month] = item.val;
					}else if(item.mpoint_name == "水泥磨压缩空气累积量"){
						that.shhourlyData_year[item.month] = item.val;
					}else if(item.mpoint_name == "原料车间压缩空气"){
						that.lvhourlyData_year[item.month] = item.val;
					}
				});
				sum = sum * 100;
				sum = Math.round(sum);
				sum = sum / 100;
				that.tableDatas[index][15] = sum.toFixed(2);
				that.tableDatas_month[index].sum = sum.toFixed(2);
				that.$forceUpdate();
			});
		},
		handleCellClick(row, column, cell, event) {
			let that = this;
			console.log("row", row);
			console.log("column", column);
			console.log("cell", cell);
			let index = that.tableDatas2.indexOf(row);
			console.log(index, "index");
			let lineData = that.tableDatas[index].slice(2, 26);
			that.option.xAxis.data = that.xAxisData;
			that.option.series[0].data = lineData;
			this.itemVisible = true;
		},
		handleCellClick1(row, column, cell, event) {
			let that = this;
			let index = that.tableDatas_day.indexOf(row);
			console.log('row', row)
			that.tableName = `${row.nickname}-电量日统计`
			let lineData = that.tableDatas[index].slice(3, that.days + 3);
			that.option.xAxis.data = that.xAxisData_day;
			that.option.series[0].data = lineData;
			this.itemVisible = true;
		},
		handleCellClick_month(row, column, cell, event) {
			let that = this;
			let index = that.tableDatas_month.indexOf(row);
			that.tableName = `${row.nickname}-电量日统计`
			//获取图数据
			let lineData = that.tableDatas[index].slice(2, 13);
			that.option.xAxis.data = that.xAxisData_month;
			that.option.series[0].data = lineData;
			this.itemVisible = true;
		},
		handleCellClick_range(row, column, cell, event) {
			let that = this;
			let index = that.tableDatas_range.indexOf(row);
			this.itemVisible = true;
		},
		exportExcel() {
			this.exportLoading = true;
			this.$XLSX("#hourBaseTable", this.tableName);
			this.exportLoading = false;
		},
		handlePrint() {
			this.$PRINT("#myReport");
		},
	}
};

</script>
<style scoped>
.printWrap {
	width: 100%;
	overflow-x: scroll;
}
.chartWrap {
	width: 1500px;
	margin-top: 20px;
	border: 1px solid #eeeeee;
}
.printContainer {
	width: 100%;
}
.chartTitle{
	text-align: center; 
    width: 100%; 
}
</style>
