<template>
	<div
		class="app-container contrastAnalysisBox"
		id="contrastAnalysisBox">
		<!-- 搜索工作栏 -->
		<search-area
			@submit="getList"
			@export="exportExl" />
		<div v-show="chartData.length">
			<bar-chart
				ref="analysisBarChart"
				:chartData="chartData"
				:timeDim="timeDim" />
			<base-table
				:table-props="tableProps"
				:table-data="list"
				:max-height="tableH"
				class="contrast-out-table" />
		</div>
		<!-- 没有数据 -->
		<div
			class="no-data-bg"
			v-show="!chartData.length"></div>
	</div>
</template>
<script>
import { getCompare } from '@/api/analysis/energyAnalysis';
import SearchArea from './components/searchArea';
import BarChart from './components/barChart';
import tableHeightMixin from '@/mixins/lb/tableHeightMixin';
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx/xlsx.mjs';
// import moment from 'moment'
export default {
	name: 'ContrastAnalysis',
	components: { SearchArea, BarChart },
	mixins: [tableHeightMixin],
	data() {
		return {
			chartData: [],
			timeDim: '',
			tableProps: [],
			list: [],
			tableH: this.tableHeight(250) / 2,
		};
	},
	methods: {
		_setTableHeight() {
			this.tableH = this.tableHeight(250) / 2;
		},
		getList(params) {
			this.timeDim = params.timeDim;
			getCompare({ ...params }).then((res) => {
				if (res.code === 0) {
					this.getTableList(res.data || []);
					this.chartData = res.data || [];
				} else {
					this.chartData = [];
				}
			});
		},
		getTableList(arr) {
			this.tableProps = [];
			this.list = [];
			let tempX = [];
			let timeArr = arr[0].trendRespVOList || [];
			this.list = timeArr.map((item) => {
				return { time: item.time };
			});
			for (let i = 0; i < arr.length; i++) {
				let obj = {};
				obj.prop = arr[i].objId;
				obj.label = arr[i].objName;
				obj.minWidth = 100;
				tempX.push(obj);
				let tiemList = arr[i].trendRespVOList;
				for (let j = 0; j < tiemList.length; j++) {
					this.list[j][arr[i].objId] = tiemList[j].useNum
						? tiemList[j].useNum.toFixed(2)
						: null;
				}
			}
			this.tableProps = [{ prop: 'time', label: '时间' }].concat(tempX);
		},
		// 导出
		exportExl() {
			if (this.list.length > 0) {
				var wb = XLSX.utils.table_to_book(
					document.querySelector('.contrast-out-table')
				);
				let fileName = '对比分析.xlsx';
				var wbout = XLSX.write(wb, {
					bookType: 'xlsx',
					bookSST: true,
					type: 'array',
				});
				try {
					FileSaver.saveAs(
						new Blob([wbout], { type: 'application/octet-stream' }),
						fileName
					);
					this.$message.success('导出成功');
				} catch (e) {
					if (typeof console !== 'undefined') console.log(e, wbout);
				}
				return wbout;
			} else {
				this.$modal.msgWarning('暂无数据导出');
			}
		},
	},
};
</script>
<style lang='scss'>
.contrastAnalysisBox {
	.contrast-out-table {
		margin-top: 20px;
	}
}
</style>