<!-- 全厂电量统计 -->
<template>
	<div class="app-container" id="app-container" style="height: 100%">
		<el-header id="app-header">
			<div class="left-panel">
				<el-date-picker
					v-model="search_date"
					type="month"
					value-format="YYYY-MM"
					format="YYYY-MM"
					placeholder="月"
					style="margin-right: 6px"
					@change="dateChange"
				/>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="getTableData"
				></el-button>
				<el-button
					type="primary"
					@click="exportExcel()"
					:loading="exportLoading"
					>导出xlsx
				</el-button>
				<el-button type="primary" @click="handlePrint">打印 </el-button>
			</div>
		</el-header>
		<el-main>
			<el-card>
				<div>
					<div ref="print" id="myReport">
						<!-- <table
							border="1"
							:width="tableWidth"
							cellspacing="0"
							:key="timeStamp"
							id="myTable"
							class="myTable"
						>
							<thead class="myTableHead">
								<tr>
									<th :colspan="headerLength">
										电量消耗日报表
									</th>
								</tr>
								<tr>
									<th>工段</th>
									<th>设备</th>
									<th>单位</th>
									<th v-for="item in this.days" :key="item">
										{{ item }}日
									</th>
									<th>本月合计</th>
								</tr>
							</thead>
							<tr
								v-for="(item, index) in tableDatas"
								:key="index"
							>
								<td
									class="numCell"
									v-if="index == 0"
									rowspan="4"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="index == 4"
									rowspan="5"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="index == 9"
									rowspan="5"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="index == 14"
									rowspan="4"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="index == 18"
									rowspan="3"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="index == 21"
									rowspan="5"
								>
									{{ item[0] }}
								</td>
								<td
									class="numCell"
									v-else-if="
										index == 26 ||
										index == 27 ||
										index == 28 ||
										index == 29
									"
								>
									{{ item[0] }}
								</td>
								<td class="numCell">{{ item[1] }}</td>
								<td class="numCell">{{ item[2] }}</td>
								<td
									v-for="day in days"
									:key="day"
									class="numCell"
									@click="itemClick(item, index)"
								>
									{{ item[2 + day] }}
								</td>
								<td class="numCell">
									{{ item[headerLength - 1] }}
								</td>
							</tr>
						</table> -->
						<el-table
							id="hourBaseTable"
							:data="tableDatas2"
							style="width: 100%"
							border
							:height="tableHeight"
							:span-method="objectSpanMethod"
							@cell-click="handleCellClick"
						>
							<el-table-column
								label="工段"
								prop="mgroupName"
								width="100"
								fixed
							>
							</el-table-column>
							<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"
								: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>
					</div>
				</div>
			</el-card>
		</el-main>

		<el-dialog v-model="itemVisible" :title="tableName" 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,
			year: "",
			month: "",
			myChart: null,
			search_date: "",
			headerLength: 33,
			tableHeight: 600,
			itemVisible: false,
			xAxisData: [],
			indexList: [],
			mpointList: [],
			tableDatas: [],
			tableDatas2: [],
			timeStamp: null,
			tableWidth: "3300",
			itemChartTitle: "",
			tableName: "电量日统计",
			sourceData: {},
			mgroupObj: {},
			option: {
				title: {
					// text: "电量日统计",
					x: "center",
				},
				grid: {
					// 图表距离边框的距离，可用百分比和数字（px）配置
					top: "20%",
					left: "3%",
					right: "6%",
					bottom: "5%",
					containLabel: true,
				},
				legend: {
					// 图例配置选项
					orient: "horizontal", //图例布局方式：水平 'horizontal' 、垂直 'vertical'
					x: "right", // 横向放置位置，选项：'center'、'left'、'right'、'number'（横向值 px）
					y: "10", // 纵向放置位置，选项：'top'、'bottom'、'center'、'number'（纵向值 px）
					data: [],
				},
				xAxis: {
					type: "category",
					data: [],
					name: "时间",
					// x轴名称样式
					nameTextStyle: {
						fontWeight: 600,
						fontSize: 14,
					},
					axisLine: {
						lineStyle: {
							color: "#3366CC",
						},
					},
					axisLabel: {
						rotate: 45, // X 轴标签文字旋转角度
						interval: 0, //设置 X 轴数据间隔几个显示一个，为0表示都显示
					},
					boundaryGap: false, //数据从 Y 轴起始
				},
				yAxis: {
					type: "value",
					name: "对象值",
					// y轴名称样式
					nameTextStyle: {
						fontWeight: 500,
						fontSize: 14,
					},
					//min:0, // 配置 Y 轴刻度最小值
					//max:4000,  // 配置 Y 轴刻度最大值
					//splitNumber:7,  // 配置 Y 轴数值间隔
					axisLine: {
						lineStyle: {
							// Y 轴颜色配置
							color: "#3366CC",
						},
					},
				},
				tooltip: {
					show: true, // 是否显示
					trigger: "axis", // axis   item   none
					axisPointer: {
						// 坐标轴指示器配置项。
						type: "cross", // 'line' 直线指示器  'shadow' 阴影指示器  'none' 无指示器  'cross' 十字准星指示器。
						axis: "auto", // 指示器的坐标轴。
						snap: true, // 坐标轴指示器是否自动吸附到点上
					},
					showContent: true,
				},
				series: [
					{
						name: "",
						data: [4, 1, 9, 2, 11, 3, 5, 7, 8, 10, 6, 12],
						type: "line",
						symbolSize: 8, //设置折线上圆点大小
						symbol: "circle",
						smooth: 0.5, // 设置折线弧度
						itemStyle: {
							normal: {
								label: {
									show: true, // 在折线拐点上显示数据
								},
								lineStyle: {
									width: 1, // 设置虚线宽度
									type: "dotted", // 虚线'dotted' 实线'solid'
									color: "#3366CC", // 折线颜色设置为0，即只显示点，不显示折线
								},
							},
						},
					},
				],
			},
		};
	},
	mounted() {
		let that = this;
		var nowDate = new Date();
		let year = nowDate.getFullYear();
		let month = nowDate.getMonth() + 1;
		let month_s = month > 9 ? month : "0" + month;
		that.year = year;
		that.month = month;
		that.search_date = year + "-" + month_s;
		that.days = new Date(year, month, 0).getDate();
		that.timeStamp = nowDate.getTime();
		that.headerLength = that.days + 4;
		that.tableWidth = that.headerLength * 100 + "";
		for (let n = 1; n <= that.days; n++) {
			that.xAxisData.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,
					};
				}
			}
		},
		dateChange(e) {
			let that = this;
			let arr = e.split("-");
			that.year = Number(arr[0]);
			that.month = Number(arr[1]);
			let nowDate = new Date();
			that.timeStamp = nowDate.getTime();
			this.dataLoop();
		},
		getMPoints() {
			let that = this;
			that.$API.enm.mpoint.list
				.req({
					page: 0,
					enabled: 1,
					need_display: 1,
					ordering: "report_sortstr",
					material__code__in: "elec,elec_0",
					query: "{ id, name, nickname, mgroup_name, unit, report_sortstr }",
				})
				.then((res) => {
					that.mpointList = res.filter((item) => {
						return item.report_sortstr !== "";
					});
					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.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.tableDatas2.push(obj);
				that.getData(item.id, index);
			});
			that.mgroupObj = mgroupObj;
			that.indexList = indexList;
		},
		getData(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) => {
					let ind = item.day + 2;
					that.tableDatas[index][ind] = item.val;
					sum += Number(item.val);
					let keyName = item.day + "日";
					that.tableDatas2[index][keyName] = 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.tableDatas2[index].sum = sum.toFixed(2);
				that.$forceUpdate();
			});
		},
		handleCellClick(row, column, cell, event) {
			let that = this;

			let index = that.tableDatas2.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;
			that.option.series[0].data = lineData;
			this.itemVisible = true;
		},
		itemClick(item, index) {
			let that = this;
			let lineData = that.tableDatas[index].slice(3, that.headerLength);
			that.option.xAxis.data = that.xAxisData;
			that.option.series[0].data = lineData;
			this.itemVisible = true;
		},
		exportExcel() {
			this.exportLoading = true;
			this.$XLSX("#myTable", this.tableName);
			this.exportLoading = false;
		},
		handlePrint() {
			this.$PRINT("#myReport");
		},
	},
};
</script>
<style scoped>
.printWrap {
	width: 100%;
	overflow-x: scroll;
}
</style>
