<template>
	<div class="app-container" style="flex: 1; height: 1px">
		<search-bar
			:formConfigs="formConfig"
			ref="searchBarForm"
			@headBtnClick="handleSearchBarBtnClick" />

		<!-- <div v-if="tableData.length"> -->
		<div class="custom-tabs" style="">
			<el-tabs
				v-model="activeName"
				@tab-click="handleTabClick"
				style="height: 100%">
				<el-tab-pane :label="'\u2002数据列表\u2002'" name="table">
					<base-table
						v-if="activeName == 'table' && ready"
						:span-method="mergeRow"
						:page="1"
						:limit="999"
						:table-props="tableProps"
						:table-data="tableData" />
					<div v-if="tableData.length == 0" class="no-data-bg"></div>
				</el-tab-pane>
				<el-tab-pane :label="'\u3000产线平衡分析图\u3000'" name="graph">
					<div class="graph" style="height: 800px">
						<!-- graph  -->
						<AnalysisChart
							v-if="activeName == 'graph'"
							:table-data="tableData"
							:daterange="dateArr"></AnalysisChart>
						<!-- <div v-else class="no-data-bg"></div> -->
						<!-- <Graph
										v-if="list.length"
										:equipment-list="list"
										:render="renderKey" /> -->
						<!-- <BalanceChart ref="lineChart" /> -->
						<!-- <div v-if="list.length == 0" class="no-data-bg"></div> -->
					</div>
				</el-tab-pane>
			</el-tabs>
		</div>
	</div>
</template>

<script>
import BalanceChart from '../balanceChart';
import basicPageMixin from '@/mixins/lb/basicPageMixin';
import AnalysisChart from './chart.vue';

export default {
	components: {
		BalanceChart,
		AnalysisChart,
	},
	mixins: [basicPageMixin],
	data() {
		return {
			activeName: 'table',
			tableProps: [
				{
					prop: 'sectionName',
					label: '工段',
					align: 'center',
				},
				{
					prop: 'equName',
					label: '设备',
					align: 'center',
				},
			],
			tableData: [],
			formConfig: [
				{
					type: 'select',
					label: '产线',
					selectOptions: [],
					param: 'lineIds',
					defaultSelect: '',
					multiple: false,
					filterable: true,
				},
				{
					type: 'datePicker',
					label: '时间',
					dateType: 'monthrange',
					format: 'yyyy-MM',
					valueFormat: 'timestamp',
					rangeSeparator: '-',
					startPlaceholder: '开始时间',
					endPlaceholder: '结束时间',
					width: 240,
					param: 'timeArr',
				},
				{
					type: 'button',
					btnName: '查询',
					name: 'search',
					color: 'primary',
				},
			],
			queryParams: {
				lineId: null,
				startTime: null,
				endTime: null,
			},
			sectionMap: {},
			lastSection: null,
			currRowIndex: 0,
			spanArr: [],
			// 保存时间列表
			dateArr: [],
			ready: false,
		};
	},

	mounted() {
		this.getLine();
	},

	methods: {
		handleTabClick(tab, event) {
			if (tab.name == 'graph') this.renderKey = Math.random();
		},

		/** 初始化 tableProps */
		initTableProps() {
			this.tableProps = [
				{
					prop: 'sectionName',
					label: '工段',
					align: 'center',
				},
				{
					prop: 'equName',
					label: '设备',
					align: 'center',
				},
			];
		},

		/** 获取产线 */
		async getLine() {
			this.formConfig[0].selectOptions = [];
			const { code, data } = await this.http(
				'/base/core-production-line/listAll',
				'get'
			);
			if (code == 0) {
				this.formConfig[0].selectOptions = data;
			}
		},

		/** 获取产线平衡数据 */
		async getCT() {
			const { code, data } = await this.http(
				'/analysis/equipment-analysis/getCT',
				'post',
				this.queryParams
			);
			if (code == 0) {
				return data;
			}
			return { data: [], nameData: [] };
		},

		/** 解析数据 */
		async getList() {
			const { data, nameData } = await this.getCT();
			await this.buildProps(nameData);
			await this.buildTableData(data);
			this.tableData = this.tableData.sort((a, b) => {
				if (a.sectionName < b.sectionName) return -1;
				return 1;
			});
			// const p = this.tableProps
			// const d = this.tableData
			// debugger;
			this.ready = true;
		},

		buildProps(nameData) {
			this.initTableProps();
			this.dateArr = [];
			return new Promise((resolve, reject) => {
				try {
					const dateArr = Array.from(
						new Set(
							nameData
								.map((item) => (item.tree == 1 ? item.name : undefined))
								.filter((v) => v)
						)
					);
					// 排个序
					dateArr.sort().forEach((date) => {
						this.tableProps.push({
							label: date,
							align: 'center',
							children: [
								{
									prop: date + '_eq_ct',
									label: '设备CT',
									align: 'center',
								},
								{
									prop: date + '_eq_tt',
									label: '设备TT',
									align: 'center',
								},
								{
									prop: date + '_pl_ct',
									label: '产线CT',
									align: 'center',
								},
								{
									prop: date + '_pl_tt',
									label: '产线TT',
									align: 'center',
								},
							],
						});
					});
					this.dateArr = dateArr;
					resolve();
				} catch (err) {
					reject(err);
				}
			});
		},

		async buildTableData(data) {
			this.tableData = [];
			const sectionArr = Array.from(
				new Set(data.map((item) => item.sectionName))
			).sort();

			const sectionMap = sectionArr.reduce(
				(sum, curr) => ({ ...sum, [curr]: 0 }),
				{}
			);

			console.log('sectionArr', sectionArr);
			console.log('sectionMap', sectionMap);
			let spanArr = Array.from(sectionArr, () => 0);

			return new Promise((resolve, reject) => {
				/** 处理 工段 分组  */
				data.map((item) => {
					sectionMap[item.sectionName]++;
					/** 处理 设备  */
					const row = {
						equName: item.equName,
						sectionName: item.sectionName,
					};
					item.data.forEach((eq) => {
						const date = eq.dynamicName;
						eq.children.forEach((sub) => {
							if (sub.dynamicName == '设备CT')
								row[date + '_eq_ct'] = sub.dynamicValue;
							if (sub.dynamicName == '设备TT')
								row[date + '_eq_tt'] = sub.dynamicValue;
							if (sub.dynamicName == '产线CT')
								row[date + '_pl_ct'] = sub.dynamicValue;
							if (sub.dynamicName == '产线TT')
								row[date + '_pl_tt'] = sub.dynamicValue;
						});
					});
					this.tableData.push(row);
				});

				/** 生成span数组 */
				const tmp = [...spanArr];
				for (const [index, key] of sectionArr.entries()) {
					tmp[index + 1] = tmp[index] + sectionMap[key];
				}

				console.log('tep', tmp);
				spanArr = tmp;

				this.sectionMap = sectionMap;
				this.spanArr = spanArr;
				resolve();
			});
		},

		mergeRow({ row, column, rowIndex, columnIndex }) {
			if (columnIndex == 1) {
				const span = this.sectionMap[row.sectionName];
				if (this.spanArr.includes(rowIndex)) {
					console.log('span...');
					return [span, 1];
				}
				return [0, 0];
			}
		},

		getData() {
			// this.listQuery.lineId = '1672847052717821953'
			// this.listQuery.startTime = '1693497600000';
			// this.listQuery.endTime = '1693843200000';
			this.urlOptions.getDataListURL(this.listQuery).then((res) => {
				console.log(res);
				let arr = [
					{
						prop: 'sectionName',
						label: '工段',
						align: 'center',
					},
					{
						prop: 'equName',
						label: '设备',
						align: 'center',
					},
				];
				let sectionArr = [];
				res.data.data.forEach((ele, index) => {
					let tempData = [];
					let eqData = [];
					let plData = [];
					ele.data.forEach((item, index) => {
						item.children.forEach((params) => {
							if (params.dynamicName === '设备CT') {
								tempData[item.dynamicName + '_eq'] = params.dynamicValue;
								eqData[index] = params.dynamicValue;
							} else {
								tempData[item.dynamicName + '_pl'] = params.dynamicValue;
								plData[index] = params.dynamicValue;
							}
						});
					});
					const equipment = {
						name: ele.equName,
						eqData: eqData,
						plData: plData,
					};
					tempData['equName'] = ele.equName;
					tempData['sectionName'] = ele.sectionName;
					this.tableData.push(tempData);
					const { sectionName } = tempData;
					sectionArr.push(sectionName);
					this.yData.push(equipment);
					console.log('看看equ', this.yData);
				});
				this.setRowSpan(sectionArr);
				res.data.nameData.forEach((item) => {
					this.timeList.push(item.name);
				});
				const timeArray = Array.from(new Set(this.timeList));
				for (const times of timeArray) {
					if (times !== '设备CT' && times !== '产线CT') {
						const subprop = {
							label: times,
							align: 'center',
							children: [
								{ prop: times + '_eq', label: '设备CT', align: 'center' },
								{ prop: times + '_pl', label: '产线CT', align: 'center' },
							],
						};
						arr.push(subprop);
						this.xData.push(times);
					}
				}
				this.tableProps = arr;

				console.log('表格横坐标', this.xData, this.yData);
				this.$nextTick(() => {
					this.$refs.lineChart.initChart(this.xData, this.yData);
				});
				// this.total = response.data.total;
				// this.dataListLoading = false;
			});
		},

		handleSearchBarBtnClick(btn) {
			switch (btn.btnName) {
				case 'search':
					this.queryParams.lineId = btn.lineIds || null;
					this.queryParams.startTime = btn.timeArr ? btn.timeArr[0] : null;
					this.queryParams.endTime = btn.timeArr ? btn.timeArr[1] : null;

					if (!btn.lineIds || !btn.timeArr.length) {
						this.$message({
							message: '请选择产线和时间',
							type: 'warning',
						});
					}
					this.getList();
					break;
			}
		},

		buttonClick(val) {
			// console.log(val)
			switch (val.btnName) {
				case 'search':
					// this.listQuery.pageNo = 1;
					// this.listQuery.pageSize = 10;
					this.listQuery.lineId = val.lineIds;
					this.listQuery.startTime = val.time
						? String(new Date(val.time[0]).getTime())
						: undefined;
					this.listQuery.endTime = val.time
						? String(new Date(val.time[1]).getTime())
						: undefined;
					if (val.time && val.lineIds) {
						this.tableData = [];
						this.xData = [];
						this.yData = [];
						this.tableProps = [];
						this.spanArr = [];
						this.timeList = [];
						this.getData();
					} else {
						this.$message({
							message: '请选择产线和时间',
							type: 'warning',
						});
					}
					break;
				case 'reset':
					this.$refs.searchBarForm.resetForm();
					this.listQuery = {
						pageSize: 10,
						pageNo: 1,
						total: 1,
					};
					this.getDataList();
					break;
				default:
					console.log(val);
			}
		},
	},
};
</script>
<style scoped>
.custom-tabs >>> .el-tabs__header {
	margin-bottom: 8px;
	display: inline-block;
	transform: translateY(-12px);
}
.custom-tabs >>> .el-tabs__item {
	padding-left: 0px !important;
	padding-right: 0px !important;
	line-height: 36px !important;
	height: 36px;
}

.custom-tabs >>> .el-tabs__content {
	height: calc(100% - 42px);
}
.custom-tabs >>> .el-tab-pane {
	height: 100%;
}
</style>
