<template>
	<el-container>
		<el-header>
			<div class="right-panel">
				<el-select v-model="queryType" @change="queryTypeChange">
					<el-option
						v-for="item in typeOptions"
						:key="item"
						:label="item"
						:value="item"
					>
					</el-option>
				</el-select>
				<el-date-picker
					v-if="queryType == '月'"
					v-model="queryDate"
					type="month"
					placeholder="查询月期"
					value-format="YYYY-MM"
					style="width: 100%"
				>
				</el-date-picker>
				<el-date-picker
					v-if="queryType == '年'"
					v-model="queryDate"
					type="year"
					placeholder="查询年份"
					value-format="YYYY"
					style="width: 100%"
				>
				</el-date-picker>
				<el-button
					type="primary"
					icon="el-icon-search"
					@click="handleQuery"
				></el-button>
			</div>
		</el-header>
		<el-main id="elMain">
			<el-row :gutter="10">
				<el-col :lg="12">
					<el-card shadow="never">
						<div class="echarts-scroll">
							<scEcharts ref="echarts1" id="bachart1" height="300px" :option="option"></scEcharts>
						</div>
					</el-card>
				</el-col>
				<el-col :lg="12">
					<el-card shadow="never" style="position: relative">
						<el-button
							@click="handleExport"
							class="tables"
							type="primary"
							>导出</el-button
						>
						<el-table
							:data="tableData"
							:height="tableHeight"
							id="exportDiv"
							:summary-method="getSummaries" 
							show-summary
						>
							<el-table-column type="index" width="50" />
							<el-table-column label="工段" prop="工段" 
								:filters="mgroupFilters"
								:filter-method="filterMgroup"
								filter-placement="bottom-end">
							</el-table-column>
							<el-table-column label="物料名" prop="物料名" min-width="100" 
								:filters="nameFilters"
								:filter-method="filterName"
								filter-placement="bottom-end">
							</el-table-column>
							<el-table-column label="任务数" prop="任务数">
							</el-table-column>
							<el-table-column label="生产数" prop="生产数">
							</el-table-column>
							<el-table-column label="合格数" prop="合格数">
							</el-table-column>
							<el-table-column label="不合格数" prop="不合格数">
							</el-table-column>
							<el-table-column label="完成进度" prop="完成进度">
								<template #default="scope">
									<span v-if="scope.row.完成进度&&scope.row.完成进度>0">{{(scope.row.完成进度).toFixed(2)}}%</span>
									<span v-else>{{scope.row.完成进度}}</span>
								</template>
							</el-table-column>
							<el-table-column label="合格率" prop="合格率">
								<template #default="scope">
									<span v-if="scope.row.合格率&&scope.row.合格率>0">{{(scope.row.合格率).toFixed(2)}}%</span>
									<span v-else>{{scope.row.合格率}}</span>
								</template>
							</el-table-column>
						</el-table>
					</el-card>
				</el-col>
			</el-row>
		</el-main>
	</el-container>
</template>

<script>
import scEcharts from "@/components/scEcharts";
export default {
	name: "chart",
	components: {
		scEcharts,
	},
	data() {
		return {
			tableHeight: 0,
			queryType: "月",
			queryDate: "",
			start_date: "",
			end_date: "",
			currentYear: "",
			currentMonth: "",
			typeOptions: ["月", "年"],
			option: {
				title: {
					text: "生产数量",
				},
				grid: {
					top: "80px",
				},
				tooltip: {
					trigger: "axis",
				},
				xAxis: {
					type: "category",
					data: [],
				},
				yAxis: [
					{
						type: "value",
						name: "数量",
					},
					{
						type: "value",
						name: "合格率",
						min: 0,
						max: 100,
						axisLabel: {
							formatter: "{value}%",
						},
					},
				],
				series: [],
			},
			nameFilters: [],
			mgroupFilters: [],
			processData: [],
			xAxisData: [],
			tableData: [],
		};
	},
	mounted() {
		let that = this;
		let date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let days = new Date(year, month, 0).getDate();
		that.currentYear = year;
		that.currentMonth = month;
		month = month > 9 ? month : "0" + month;
		that.start_date = year + "-" + month + "-01";
		that.end_date =year + "-" + month + "-" + days;
		that.queryDate = year + "-" + month;
		let height = document.getElementById("elMain").clientHeight - 40;
		that.tableHeight = height;
		document.getElementById('bachart1').style.height = height + 'px';
		that.getData6();
	},
	methods: {
		queryTypeChange(value) {
			console.log(value);
			this.queryDate = "";
		},
		getData6() {
			let that = this;
			that.nameFilters = [];
			that.mgroupFilters = [];
			let obj = {
				query: {
					start_date: this.start_date,
					end_date: this.end_date,
					dept_name: "6车间",
					select_cols_material: "",
					group_bys_material: "",
					order_bys_material: "",
					is_count_utask: -1,
					select_cols_mgroup: ", mgroup.name AS 工段",
					group_bys_mgroup: ", mgroup.name",
					order_bys_mgroup:",工段"
				},
				raise_exception: true,
			};
			if (that.queryType == "月") {
				obj.query.select_cols_date =
					",EXTRACT ( MONTH FROM mlog.handle_date ) AS 月";
				obj.query.group_bys_date =
					",EXTRACT ( MONTH FROM mlog.handle_date )";
				obj.query.order_bys_date = ", 月";
			}
			let xAxisData = [],nameData=[],seriesData=[];
			let colorPalette = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
			that.$API.bi.dataset.exec.req("lineWeek", obj).then((res) => {
				let data = res.data2.ds0;
				that.tableData = data;
				data.forEach((item) => {
					if (xAxisData.indexOf(item.工段) === -1) {
						xAxisData.push(item.工段);
						that.mgroupFilters.push({ text: item.工段, value: item.工段 });
					}
					if (nameData.indexOf(item.物料名) === -1) {
						nameData.push(item.物料名);
						that.nameFilters.push({ text: item.物料名, value: item.物料名 });
					}
				});
				nameData.forEach((materialName, idx) => {
					let color = colorPalette[idx % colorPalette.length];
					let barData = xAxisData.map((mgroup) => {
						let qualified = 0;
						data.forEach((item) => {
							if (item.工段 === mgroup && item.物料名 === materialName) {
								qualified += Number(item.合格数) || 0;
							}
						});
						return qualified;
					});
					let passRateData = xAxisData.map((mgroup) => {
						let qualified = 0;
						let produced = 0;
						data.forEach((item) => {
							if (item.工段 === mgroup && item.物料名 === materialName) {
								qualified += Number(item.合格数) || 0;
								produced += Number(item.生产数) || 0;
							}
						});
						return produced > 0
							? Number(((qualified / produced) * 100).toFixed(2))
							: null;
					});
					seriesData.push({
						name: materialName,
						type: "bar",
						yAxisIndex: 0,
						itemStyle: { color },
						label: {
							show: true,
							position: "top",
							formatter: "{c}",
							color: color,
						},
						barWidth: "15px",
						data: barData,
					});
					seriesData.push({
						name: materialName + " 合格率",
						type: "line",
						yAxisIndex: 1,
						smooth: true,
						data: passRateData,
						label: {
							show: true,
							position: "top",
							formatter: "{c}%",
							color: color,
						},
						lineStyle: { color },
						itemStyle: { color },
					});
				});
				that.xAxisData = xAxisData;
				that.option.xAxis.data = that.xAxisData;
				that.option.series = seriesData;
				that.$nextTick(() => {
					that.resizeChart(xAxisData.length, nameData.length);
				});
			});
		},
		resizeChart(xCount, materialCount) {
			let chartDiv = document.getElementById("bachart1");
			if (!chartDiv) return;
			let wrapper = chartDiv.parentElement;
			let parentWidth = wrapper.clientWidth;
			let groupWidth = Math.max(60, materialCount * 25 + 30);
			let neededWidth = xCount * groupWidth + 80;
			chartDiv.style.width = Math.max(parentWidth, neededWidth) + "px";
			let inst = this.$refs.echarts1 && this.$refs.echarts1.myChart;
			if (inst) inst.resize();
		},
		handleQuery() {
			if (this.queryDate !== "" && this.queryDate !== null) {
				if (this.queryType == "月") {
					this.start_date = this.queryDate + "-01";
					let arr = this.queryDate.split("-");
					this.end_date =this.queryDate +"-" +new Date(arr[0], arr[1], 0).getDate();
				} else {
					this.start_date = this.queryDate + "-01-01";
					this.end_date = this.queryDate + "-12-31";
				}
			} else {
				if (this.queryType == "月") {
					this.start_date =
						this.currentYear + "-" + this.currentMonth + "-01";
					this.end_date =
						this.currentYear +
						"-" +
						this.currentMonth +
						"-" +
						new Date(
							this.currentYear,
							this.currentMonth,
							0
						).getDate();
				} else {
					this.start_date = this.currentYear + "-01-01";
					this.end_date = this.currentYear + "-12-31";
				}
			}
			this.getData6();
		},
		getSummaries({ columns, data }) {
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				if (index == 3||index == 4||index == 5||index == 6) {
					const values = data.map((item) =>
						Number(item[column.property])
					);
					if (!values.every((value) => Number.isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr); //Number转换为数值
							let sum = Number(
								Number(prev) + Number(curr)
							).toFixed(2); //toFixed(2)数据项保留两位小数
							if (!isNaN(value)) {
								return sum;
							} else {
								return prev;
							}
						}, 0);
					} 
				}
			});
			return sums;
		},
		filterName(value, row) {
            return row.物料名 === value;
        },
		filterMgroup(value, row) {
            return row.工段 === value;
        },
		handleExport() {
			this.exportLoading = true;
			this.$XLSX("#exportDiv", "工序合格数");
			this.exportLoading = false;
		},
	},
};
</script>

<style scoped>
.tables {
	position: absolute;
	top: 6px;
	left: 4px;
	z-index: 10;
}
.echarts-scroll {
	width: 100%;
	overflow-x: auto;
	overflow-y: hidden;
}
.echarts-scroll > :deep(#bachart1) {
	min-width: 100%;
}
</style>
