<template>
	<div class="app-container">
		<el-header>
			<div class="left-panel">
				<el-date-picker
					v-model="query.year_s"
					type="year"
					value-format="YYYY"
					format="YYYY"
					placeholder="查询年份"
					class="headerSearch"
				/>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="handleQuery"
				></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-card style="margin-top: 5px">
			<div class="printWrap">
				<div ref="print" id="myReport" class="printContainer">
					<table
						border="1"
						width="1075"
						cellspacing="0"
						:key="timeStamp"
						id="myTable"
						class="myTable"
					>
						<thead class="myTableHead">
							<tr>
								<th colspan="12">电石渣工段班组月度对比分析</th>
							</tr>
							<tr>
								<th rowspan="2">月份</th>
								<th rowspan="2">班组</th>
								<th rowspan="2">总产量（t）</th>
								<th rowspan="2">单位产品成本（元/吨）</th>
								<th colspan="7">产品单位电耗</th>
								<th rowspan="2">得分</th>
							</tr>
							<tr>
								<th>当期值（kKW·h/t）</th>
								<th>目标值（kKW·h/t）</th>
								<th>当期与目标值差值（KW·h/t）</th>
								<th>环期值（KW·h/t）</th>
								<th>当期与环期值差值（KW·h/t）</th>
								<th>环比增长率（%）</th>
								<th>同比增长率（%）</th>
							</tr>
						</thead>
						<tr v-for="(item, index) in tableDatas" :key="index">
							<td
								v-for="(item0, index0) in item"
								:key="index0"
								class="numCell"
							>
								{{ item0 }}
							</td>
						</tr>
					</table>
				</div>
			</div>
		</el-card>
	</div>
</template>
<script>
export default {
	data() {
		return {
			query: {
				year_s: "",
				page: 0,
				type: "month_st",
				mgroup: "",
			},
			timeStamp: null,
			exportLoading: false,
			tableDatas: [],
			goalDatas: [],
		};
	},
	mounted() {
		let that = this;
		var myDate = new Date();
		let year = myDate.getFullYear();
		this.timeStamp = myDate.getTime();
		that.query.year_s = year;
		this.$API.mtm.mgroup.list
			.req({ page: 0, search: "电石渣" })
			.then((res) => {
				that.query.mgroup = res[0].id;
				let params = {};
				params.page = 0;
				params.year = year;
				params.mgroup = that.query.mgroup;
				this.$API.mtm.goal.list.req(params).then((res) => {
					if (res.length > 0) {
						res.forEach((item) => {
						    if (item.goal_cate_name == "单位产品分布电耗（KW·h/t）") {
						        that.getData(item);
						    }
						})
					}
				});
			});
	},
	methods: {
		getGoalData() {
			const self = this;
			let params = {};
			params.page = 0;
			params.year = self.query.year_s;
			params.mgroup = self.query.mgroup;
			this.$API.mtm.goal.list.req(params).then((res) => {
				if (res.length > 0) {
						res.forEach((item) => {
						    if (item.goal_cate_name == "单位产品分布电耗（KW·h/t）") {
						        this.getData(item);
						    }
						})
					}
			})
			.catch((error) => {
            console.error('获取目标数据失败：', error);
        });
		},
		getData(goalData) {
			let that = this;
			let query0 = {};
			query0.page = 0;
			query0.type = "month_st";
			query0.year_s = that.query.year_s - 1;
			query0.mgroup = that.query.mgroup;
			let wrapArr = [],
				wrapArr0 = [],
				month_obj = {},
				compareArr0 = [];
			this.$API.enm.enstat.req(query0).then((res0) => {
				let data0 = res0;
				if (data0.length > 0) {
					data0.forEach((item0) => {
						//先按月份排序，再按班组排序
						wrapArr0[ind0] = item0;
					});
				} else {
			}
			});
				this.$API.enm.enstat.req(that.query).then((res) => {
					let data = res;
					if (data.length > 0) {
						data.forEach((item, index) => {
							//先按月份排序，再按班组排序
							let compareArr = []; 
							compareArr.push(item.month_s);
							compareArr.push(item.team_name);
							compareArr.push(item.elec_consume_unit);
							compareArr0[index]=compareArr;
							if (!month_obj[item.month_s]) {
								month_obj[item.month_s] = [];
							}
							month_obj[item.month_s].push({team:item.team_name, value: item.elec_consume_unit});
							// month_list.push(month_obj)
						});
						data.forEach((item) => {
							//先按月份排序，再按班组排序
							let n = item.month_s;
							let arr = [];
							let time = "" + item.year_s + "." + item.month_s;
							arr.push(time);
							arr.push(item.team_name);
							arr.push(item.total_production);
							arr.push(item.production_hour);

							arr[4] = item.elec_consume_unit; //当期值（KW·h/t）
							let keyVale = "goal_val_" + n;
							arr[5] = goalData[keyVale]; //目标值（KW·h/t）//需要接口获取
							arr[6] = (arr[4] - arr[5]).toFixed(2); //当期与目标差值（KW·h/t）
							let ind_pre = 0,
								huanqi = 0,
								huanqicha = 0,
								tongqi = 0,
								tongqicha = 0;
							if (n == 1) {
								ind_pre = 12;
								huanqi = wrapArr0[ind_pre]
									? wrapArr0[ind_pre].elec_consume_unit
									: "/";
							} else {
								// 如果 wrapArr数组长度大于0，那么循环遍历wrapArr数组，找到与item.month_s相差1的元素 而 item.name相同，并赋值给huanbi
								compareArr0.forEach((item0) => {
									if (item0[0] == item.month_s - 1 && item0[1] == item.team_name) {
										huanqi = item0[2];
								}
							})
							}
							arr[7] = huanqi; //环期值（KW·h/t）上个月的值
							if (arr[6] !== "/"){
								arr[8] = (arr[4] - arr[7]).toFixed(2); //当期与环期差值（KW·h/t）
							}else{
								arr[8] = "/"; //当期与环期差值（KW·h/t）
							}
							// arr[8] = huanqicha; //当期与环期差值（KW·h/t）
							let growthRate = 0;
							if (arr[8]!== "/" && arr[7]!== 0  && arr[8]!== 0 ) {
								growthRate = ((arr[8] / arr[7]) * 100).toFixed(2);
							} else{
								growthRate = "/";
							}
							arr[9] = growthRate; //环比增长率（%）
							if (wrapArr0[n]) {
								tongqicha =
									item.celec_consume_unit -
									wrapArr0[n].celec_consume_unit;
								tongqi = tongqicha / tongqi;
							} else {
								tongqicha = item.celec_consume_unit;
								tongqi = 0;
							}
							arr[10] = tongqi; //同比增长率（%）
							//如果n = month_list的key值，则遍历里面的对象按照value排序, 如果 index==0，则arr[11] = 100，如果 index==1，则arr[11] = 80，如果 index==2，则arr[11] = 70，如果 index==3，则arr[11] = 0
							if (month_obj[n]) {
							    const monthData = month_obj[n];
								const itemValue = item.elec_consume_unit; // 当前项的值
								const sortedData = monthData.sort((a, b) => parseFloat(b.value) - parseFloat(a.value));
								const index = sortedData.findIndex(obj => parseFloat(obj.value) === parseFloat(itemValue));								
								if (index === 0){
									arr[11] = 100;
								} else if (index === 1) {
									arr[11] = 80;
								} else if (index === 2) {
									arr[11] = 70;
								} else if (index === 3) {
									arr[11] = 0;
								}
							}
							wrapArr.push(arr);
						});
						that.tableDatas = wrapArr;
					} else {
					}
				});
		},
		handleQuery() {
			this.tableDatas = [];
			this.getGoalData();
		},
		itemClick(type, item) {
			this.type = type;
			this.asynDialog = true;
		},
		itemClick1(type, item) {
			this.chartShow = false;
			this.$API.bi.dataset.exec.req("3322567213885833216").then((res) => {
				this.myOption = JSON.parse(res.echart_options);
				this.chartShow = true;
			});
		},
		handlePrint() {
			this.$PRINT("#myReport");
		},
		exportExcel() {
			this.exportLoading = true;
			this.$XLSX("#myTable", this.tableName);
			this.exportLoading = false;
		},
	},
};
</script>
<style scoped>
.printWrap {
	width: 100%;
	overflow-x: scroll;
}
</style>
