<template>
	<div class="app-container sectionProductionReport">
		<!-- 搜索工作栏 -->
		<search-bar
			:formConfigs="formConfig"
			ref="searchBarForm"
			@headBtnClick="buttonClick" />
		<base-table
			class="sectionProductionTable1"
			:table-props="tableProp"
			:table-data="tableData"
			:span-method="objectSpanMethod"
			:max-height="tableH" />
		<!-- 搜索工作栏 -->
		<search-bar
			style="margin-top: 10px"
			:formConfigs="formConfig2"
			ref="searchBarForm"
			@headBtnClick="buttonClick2" />
		<base-table
			class="sectionProductionTable2"
			:table-props="tableProp2"
			:table-data="tableData2"
			:span-method="objectSpanMethod2"
			:max-height="tableH" />
	</div>
</template>
<script>
const tableProp1 = [
	{
		prop: 'lineName',
		label: '生产线',
		width: 110,
		fixed: true,
	},
	{
		label: '时间',
		fixed: true,
		width: 110,
		children: [
			{
				prop: 'procedure',
				label: '工序',
				width: 140,
			},
		],
	},
];
import {
	originalSection,
	getOriginalLine,
	getProcessingLine,
	processing,
} from '@/api/report/customizedReports';
import FileSaver from 'file-saver';
import moment from 'moment';
export default {
	name: 'SectionProduction',
	data() {
		return {
			tableH: this.tableHeight(280) / 2,
			formConfig: [
				{
					type: 'select',
					label: '生产线',
					selectOptions: [],
					param: 'lineId',
				},
				{
					type: 'select',
					label: '时间',
					selectOptions: [
						{ id: '1', name: '当前班次' },
						{ id: '2', name: '近24小时' },
						{ id: '3', name: '日报' },
					],
					defaultSelect: '1',
					param: 'timeType',
					clearable: false,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'separate',
				},
				{
					type: 'button',
					btnName: '导出',
					name: 'export',
					plain: true,
					color: 'primary',
				},
			],
			formConfig2: [
				{
					type: 'select',
					label: '生产线',
					selectOptions: [],
					param: 'lineId',
				},
				{
					type: 'select',
					label: '时间',
					defaultSelect: '1',
					selectOptions: [
						{ id: '1', name: '当前班次' },
						{ id: '2', name: '近24小时' },
						{ id: '3', name: '日报' },
					],
					param: 'timeType',
					clearable: false,
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
				{
					type: 'separate',
				},
				{
					type: 'button',
					btnName: '导出',
					name: 'export',
					plain: true,
					color: 'primary',
				},
			],
			queryParams: {
				startTime: '1706114700000',
				endTime: '1706190300000',
				lineId: '',
			},
			queryParams2: {
				startTime: '1706114700000',
				endTime: '1706190300000',
				lineId: '',
			},
			tableProp1,
			tableProp: [],
			tableData: [],
			tableProp2: [],
			tableData2: [],
			procedureName: [
				{ name: '压延(拉引量t)', ename: 'calenderingCapacity' },
				{ name: '优化切割(片)', ename: 'cuttingNum' },
				{ name: '堆垛(片)', ename: 'unloadPieces' },
				{ name: '堆垛(托)', ename: 'unloadCount' },
				{ name: '良品率(%)', ename: 'rate' },
			],
			span: [], //表2第一列合并
		};
	},
	created() {
		window.addEventListener('resize', this._setTableHeight);
	},
	destroyed() {
		window.removeEventListener('resize', this._setTableHeight);
	},
	mounted() {
		this.getLine();
		this.tableProp = this.tableProp1;
		this.tableProp2 = this.tableProp1;
		this.getList();
		this.getList2();
	},
	methods: {
		_setTableHeight() {
			this.tableH = this.tableHeight(280) / 2;
		},
		getLine() {
			getOriginalLine().then((res) => {
				this.formConfig[0].selectOptions = res.data || [];
			});
			getProcessingLine().then((res) => {
				this.formConfig2[0].selectOptions = res.data || [];
			});
		},
		getList() {
			// 获取数据
			originalSection({ ...this.queryParams }).then((res) => {
				let data = res.data;
				let timeArr = this.uniqueTime(data, 'timeStr');
				this.tableProp = [];
				let arr = [];
				timeArr.map((item) => {
					let obj = {};
					obj.prop = item.timeStr;
					obj.label = item.timeStr;
					obj.minWidth = 140;
					arr.push(obj);
				});
				this.tableProp = this.tableProp1.concat(arr); //表头
				this.transferData(data);
			});
		},
		getTime(val) {
			switch (val) {
				case '1':
					let nowTime = moment().valueOf();
					let dTime = moment(
						moment().format('YYYY-MM-DD') + ' 07:00:00'
					).valueOf();
					let nTime = moment(
						moment().format('YYYY-MM-DD') + ' 19:00:00'
					).valueOf();
					let fTime =
						moment(moment().valueOf() - 86400).format('YYYY-MM-DD') +
						' 19:00:00';
					console.log(fTime);
					// if (nowTime >= dTime) {
					// 	return [dTime, nowTime]
					// }else if (){

					// }
					break;
				case '2':
					break;
				default:
			}
		},
		buttonClick(val) {
			if (val.btnName === 'search') {
				this.queryParams.lineId = val.lineId;
				this.getTime(val.timeType);
				this.getList();
			} else {
				//导出
				this.exportTable('.sectionProductionTable1', '原片工段数据.xlsx', 0);
			}
		},
		//导出表格
		exportTable(className, fileName, num) {
			// 处理查询参数
			var fix = document.querySelectorAll('.el-table__fixed')[num];
			var table = document.querySelector(className).childNodes[0];
			var wb;
			import('xlsx').then((excel) => {
				if (fix) {
					wb = excel.utils.table_to_book(table.removeChild(fix));
					table.appendChild(fix);
				} else {
					wb = excel.utils.table_to_book(table);
				}
				/* 获取二进制字符串作为输出 */
				var wbout = excel.write(wb, {
					bookType: 'xlsx',
					bookSST: true,
					type: 'array',
				});
				try {
					FileSaver.saveAs(
						new Blob([wbout], { type: 'application/octet-stream' }),
						//设置导出文件名称
						fileName
					);
				} catch (e) {
					if (typeof console !== 'undefined') console.log(e, wbout);
				}
				return wbout;
			});
		},
		transferData(data) {
			let tempData = [];
			let lineNum = 0; //第一条产线
			for (let i = 0; i < data.length; i++) {
				if (i === 0) {
					this.procedureName.map((item) => {
						let obj = {};
						obj.lineName = data[i].lineName;
						obj.procedure = item.name;
						obj[data[i].timeStr] = data[i][item.ename];
						tempData.push(obj);
					});
					lineNum++;
				} else {
					if (data[i].lineName === data[i - 1].lineName) {
						//相同产线,添加列
						let startNum = 5 * (lineNum - 1);
						let endNum = 5 * lineNum - 1;
						for (let k = startNum; k <= endNum; k++) {
							let str = this.procedureName[k % 5];
							tempData[k][data[i].timeStr] = data[i][str.ename];
						}
					} else {
						//不同产线，同时添加5行
						this.procedureName.map((item) => {
							let obj = {};
							obj.lineName = data[i].lineName;
							obj.procedure = item.name;
							obj[data[i].timeStr] = data[i][item.ename];
							tempData.push(obj);
						});
						lineNum++;
					}
				}
			}
			this.tableData = tempData;
		},
		// 时间去重
		uniqueTime(arr, prop) {
			return arr.filter((value, index, self) => {
				return (
					self.findIndex((t) => {
						return t[prop] === value[prop];
					}) === index
				);
			});
		},
		// 合并第一列
		objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			if (columnIndex === 0) {
				if (rowIndex % 5 === 0) {
					return {
						rowspan: 5,
						colspan: 1,
					};
				} else {
					return {
						rowspan: 0,
						colspan: 0,
					};
				}
			}
		},
		getList2() {
			// 获取数据
			processing({ ...this.queryParams2 }).then((res) => {
				this.tableData2 = [];
				let data = res.data;
				for (let i = 0; i < data.length; i++) {
					for (let j = 0; j < data[i].productDet.length; j++) {
						let obj = {};
						obj.lineName = data[i].lineName;
						obj.procedure = data[i].productDet[j].name;
						data[i].productDet[j].data.map((item) => {
							obj[item.timeStr] = item.input || null;
						});
						obj.sum = data[i].productDet[j].allInput;
						this.tableData2.push(obj);
					}
				}
				let arr = [];
				let propsArr = data[0].timeStr || [];
				propsArr.map((t) => {
					let obj = {};
					obj.prop = t;
					obj.label = t;
					obj.minWidth = 140;
					arr.push(obj);
				});
				arr.push({ prop: 'sum', label: '合计' });
				this.tableProp2 = this.tableProp1.concat(arr); //表头
				this.getSpanArr(this.tableData2);
			});
		},
		// 表格2
		buttonClick2(val) {
			if (val.btnName === 'search') {
				this.queryParams2.lineId = val.lineId;
				this.getList2();
			} else {
				this.exportTable('.sectionProductionTable2', '深加工工段数据.xlsx', 1);
			}
		},
		// 获取合并行
		getSpanArr(data) {
			this.span = [];
			for (var i = 0; i < data.length; i++) {
				if (i === 0) {
					this.span.push(1);
					this.index = 0;
				} else {
					if (data[i].lineName === data[i - 1].lineName) {
						this.span[this.index] += 1;
						this.span.push(0);
					} else {
						this.span.push(1);
						this.index = i;
					}
				}
			}
		},
		objectSpanMethod2({ rowIndex, columnIndex }) {
			if (columnIndex === 0) {
				const _row = this.span[rowIndex];
				return {
					rowspan: _row,
					colspan: 1,
				};
			}
		},
	},
};
</script>
<style lang="scss">
.sectionProductionReport {
	.el-table thead.is-group tr:first-of-type th:nth-child(2) {
		border-bottom: none;
	}
	.el-table thead.is-group tr:first-of-type th:nth-child(2) div.cell {
		padding-left: 82px;
	}
	.el-table th.el-table__cell {
		height: 28px;
	}
	.el-table thead.is-group tr:first-of-type th:nth-child(2):before {
		content: '';
		position: absolute;
		height: 80px;
		top: 0;
		left: 0;
		background-color: #ebeef5;
		transform: rotate(-70deg);
		-webkit-transform-origin: top;
		transform-origin: top;
		width: 1px;
	}
	.el-table thead.is-group tr:last-of-type th:nth-child(1):before {
		content: '';
		position: absolute;
		height: 67px;
		top: 0;
		left: 75px;
		background-color: #ebeef5;
		transform: rotate(-70deg);
		-webkit-transform-origin: top;
		transform-origin: top;
		width: 1px;
	}
}
</style>
