<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"
				>
				</el-date-picker>
				<el-date-picker
					v-if="queryType == '年'"
					v-model="queryDate"
					type="year"
					placeholder="查询年份"
					value-format="YYYY"
				>
				</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="15">
				<el-col :lg="12">
					<el-card shadow="never" style="margin-bottom: 8px">
						<el-header>
							<div class="right-panel">
								<h2>产品交付统计</h2>
								<xtSelect
									:apiObj="apiObjMaterial"
									:params = "paramsMaterial"
									v-model="materialSale"
									v-model:label="materialName"
									v-model:obj="materialItem"
									@change="materialSaleChange"
								>
									<el-table-column type="index" width="50" />
									<el-table-column label="名称" prop="name"></el-table-column>
									<el-table-column label="规格" prop="specification"></el-table-column>
									<el-table-column label="型号" prop="model"></el-table-column>
									<el-table-column label="库存" prop="count"></el-table-column>
								</xtSelect>
								<!-- <el-select
									v-model="materialSale"
									clearable
									@change="materialSaleChange"
								>
									<el-option
										v-for="item in inmData"
										:key="item.id"
										:label="item.material_.name"
										:value="item.id"
									>
									</el-option>
								</el-select> -->
							</div>
						</el-header>
						<el-row>
							<el-col>
								<div
									id="bachart1"
									style="width: 100%; height: 300px"
								></div>
							</el-col>
							<el-card
								shadow="never"
								style="
									width: 100%;
									position: relative;
									margin-top: 20px;
								"
							>
								<el-button
									@click="handleExport('1')"
									class="tables"
									type="primary"
									>导出</el-button
								>
								<el-table
									:data="tableData1"
									id="exportDiv1"
									:height="tableHeight"
									:summary-method="getSummaries" show-summary
									row-key="id"
								>
									<el-table-column type="index" width="50" />
									<el-table-column label="年份" prop="年" width="70"/>
									<el-table-column v-if="queryType == '月'" width="60" label="周" prop="周"
									:filters="dateFilters"
                                    :filter-method="filterDate"
                                    filter-placement="bottom-end"/>
									<el-table-column v-else width="60" label="月份" prop="月" 
									:filters="dateFilters"
                                    :filter-method="filterDate"
                                    filter-placement="bottom-end"/>
									<el-table-column label="名称" prop="物料名" 
									:filters="nameFilters"
                                    :filter-method="filterName"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="规格" prop="规格" 
									:filters="specsFilters"
                                    :filter-method="filterSpecs"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="型号" prop="型号" 
									:filters="modelFilters"
                                    :filter-method="filterModel"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="数量" prop="数量">
									</el-table-column>
								</el-table>
							</el-card>
						</el-row>
					</el-card>
				</el-col>
				<el-col :lg="12">
					<el-card shadow="never" style="margin-bottom: 8px">
						<el-container>
							<el-header>
								<div class="right-panel">
									<h2>交付统计总表</h2>
								</div>
							</el-header>
							<el-main style="width: 100%; position: relative">
								<el-button
									@click="handleExport('2')"
									class="tables"
									type="primary"
									>导出</el-button
								>

								<scTable
									:data="tableData2"
									id="exportDiv2"
									:height="rightHeight"
									hideDo
									hidePagination
									:summary-method="getSummaries" show-summary
									row-key="id"
								>
									<el-table-column type="index" width="50" />
									<el-table-column label="年份" prop="年" width="70"/>
									<el-table-column v-if="queryType == '月'" width="70" label="周" prop="周" 
									:filters="dateFilters2"
                                    :filter-method="filterDate2"
                                    filter-placement="bottom-end"/>
									<el-table-column v-else width="70" label="月份" prop="月" 
									:filters="dateFilters2"
                                    :filter-method="filterDate2"
                                    filter-placement="bottom-end"/>
									<el-table-column label="名称" prop="物料名" 
									:filters="nameFilters2"
                                    :filter-method="filterName2"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="规格" prop="规格" 
									:filters="specsFilters2"
                                    :filter-method="filterSpecs2"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="型号" prop="型号" 
									:filters="modelFilters2"
                                    :filter-method="filterModel2"
                                    filter-placement="bottom-end">
									</el-table-column>
									<el-table-column label="数量" prop="数量">
									</el-table-column>
								</scTable>
							</el-main>
						</el-container>
					</el-card>
				</el-col>
			</el-row>
		</el-main>
	</el-container>
</template>

<script>
import * as echarts from "echarts";
import T from "@/components/scEcharts/echarts-theme-T.js";
echarts.registerTheme("T", T);
function deepCopy(obj) {
	return JSON.parse(JSON.stringify(obj));
}
export default {
	name: "chart",
	data() {
		return {
			queryType: "月",
			queryDate: "",
			start_date: "",
			end_date: "",
			currentYear: "",
			currentMonth: "",
			materialName: "",
			xAxisOrigin: [],
			xAxisData: [],
			typeOptions: ["月", "年"],
			basicOption: {
				backgroundColor: "transparent",
				title: {
					text: "",
				},
				grid: {
					top: "80px",
				},
				tooltip: {
					trigger: "axis",
				},
				xAxis: {
					type: "category",
					data: [],
				},
				yAxis: {
					type: "value",
				},
				lenged: [],
				series: [
					{
						data: [0, 0, 0, 0, 0, 0, 0],
						stack: "Ad",
						type: "bar",
						barWidth: "15px",
					},
				],
			},
			materialSale: "",
			saleOption: [],
			tableHeight: 0,
			rightHeight: 0,
			tableData1: [],
			tableData2: [],
			nameFilters: [],
			dateFilters: [],
			modelFilters: [],
			specsFilters: [],
			nameFilters2: [],
			dateFilters2: [],
			modelFilters2: [],
			specsFilters2: [],
			firstWeekNum: 1,
			endWeekNum: 4,
			monthList: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
			materialItem:{},
			paramsMaterial:{type__in : "10"},
			apiObjMaterial:this.$API.mtm.material.list,
		};
	},
	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;
		that.firstWeekNum = that.getWeekOfYear(year,month,1);
		that.endWeekNum = that.getWeekOfYear(year,month,days);
		month = month < 10 ? "0" + month : month;
		that.start_date = year + "-" + month + "-01";
		that.end_date =year + "-" + month + "-" + days;
		that.queryDate = year + "-" + month;
		let duration = that.endWeekNum - that.firstWeekNum + 1;
		for (let i = 1; i <= duration; i++) {
			that.xAxisOrigin.push("第" + i + "周");
		}
		that.xAxisData = that.xAxisOrigin;
		let height = document.getElementById("elMain").clientHeight;
		let chartheight = document.getElementById("bachart1").clientHeight;
		that.tableHeight = height - 140 - chartheight;
		that.rightHeight = height - 115;
		that.getTable();
		that.setChart("bachart1", that.basicOption);
		// this.getSaleOption();
	},
	methods: {
		setChart(name, option = null) {
			// 根据name 渲染数据, option需填写，否则option为模拟数据
			var myChart = echarts.getInstanceByDom(document.getElementById(name));
			if (myChart != null) {
				myChart.dispose(); // 销毁之前的实例
			}
			myChart = echarts.init(document.getElementById(name), "T");
			if (option == null) {
				option = Object.assign({}, this.basicOption);
			}
			setTimeout(() => {
				try {
					myChart.setOption(option);
				} catch (error) {}
			}, 500);
		},
		queryTypeChange(value) {
			console.log(value);
			this.queryDate = "";
		},
		getWeekOfYear(a,b,c) {
			var date1 = new Date(a, parseInt(b) - 1, c), //当前日期  
            date2 = new Date(a, 0, 1), //当年第一天  
            // d是当前日期是今年第多少天  
            d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
            // d + 当前年的第一天的周差距的和在除以7就是本年第几周  
            return Math.ceil((d + (date2.getDay() + 1 - 1)) / 7);
		},
		materialSaleChange() {
			this.getSaleData();
		},
		//交付物料选项
		getSaleOption() {
			let that = this;
			let obj = {};
			obj.page = 0;
			obj.type__in = "10";
			that.$API.mtm.material.list.req(obj).then((res) => {
				that.saleOption = res;
			});
		},
		//交付物料
		getSaleData() {
			let that = this;
			that.tableData1 = [];
			that.nameFilters = [];
			that.dateFilters = [];
            that.modelFilters = [];
            that.specsFilters = [];
			let nameList=[],dateList = [],specsList=[],modelList=[];
			let exec = that.queryType == "月" ? "saleOutWeek" : "saleOutMonth";
			let obj = {
				query: {
					start_date: that.start_date,
					end_date: that.end_date,
					mio_type: "sale_out",
					material_id: that.materialSale,
				},
			};
			that.$API.bi.dataset.exec.req(exec, obj).then((res) => {
				if (res.data2.ds0&&res.data2.ds0.length>0) {
					let data = res.data2.ds0;
					that.tableData1 = data;
					data.forEach((ite) => {
						if (nameList.indexOf(ite.物料名) > -1) {
						} else {
							nameList.push(ite.物料名);
							let obj = {};
							obj.text = ite.物料名;
							obj.value = ite.物料名;
							that.nameFilters.push(obj);
						}
						if(modelList.indexOf(ite.型号)>-1){}else{
							modelList.push(ite.型号);
							let obj2 = {};
							obj2.text = ite.型号;
							obj2.value = ite.型号;
							that.modelFilters.push(obj2);
						}
						if(specsList.indexOf(ite.规格)>-1){}else{
							specsList.push(ite.规格);
							let obj3 = {};
							obj3.text = ite.规格;
							obj3.value = ite.规格;
							that.specsFilters.push(obj3);
						}
						if(that.queryType == "月"){
							if(dateList.indexOf(ite.周)>-1){}else{
								dateList.push(ite.周);
								let obj4 = {};
								obj4.text = ite.周;
								obj4.value = ite.周;
								that.dateFilters.push(obj4);
							}
						}else{
							that.dateFilters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
						}
					})
					that.setChartData(data);
				}else{
					let option = deepCopy(that.basicOption);
					option.xAxis.data = that.xAxisData;
					that.setChart("bachart1",option);
				}
			});
		},
		getTable() {
			let that = this;
			that.nameFilters = [];
			that.dateFilters = [];
            that.modelFilters = [];
            that.specsFilters = [];
			that.nameFilters2 = [];
			that.dateFilters2 = [];
            that.modelFilters2 = [];
            that.specsFilters2 = [];
			let nameList=[],dateList = [],specsList=[],modelList=[];
			let obj = {
				query: {
					start_date: that.start_date,
					end_date: that.end_date,
					mio_type: "sale_out",
				},
			};
			let exec = that.queryType == "月" ? "saleOutWeek" : "saleOutMonth";
			that.$API.bi.dataset.exec.req(exec, obj).then((res) => {
				that.tableData2 = [];
				if (res.data2.ds0) {
					let data = res.data2.ds0;
					that.tableData1 = data;
					that.tableData2 = data;
					if(data.length>0){
						data.forEach((ite) => {
						    if (nameList.indexOf(ite.物料名) > -1) {
							} else {
								nameList.push(ite.物料名);
								let obj = {};
								obj.text = ite.物料名;
								obj.value = ite.物料名;
								that.nameFilters.push(obj);
							}
							if(modelList.indexOf(ite.型号)>-1){}else{
								modelList.push(ite.型号);
								let obj2 = {};
								obj2.text = ite.型号;
								obj2.value = ite.型号;
								that.modelFilters.push(obj2);
							}
							if(specsList.indexOf(ite.规格)>-1){}else{
								specsList.push(ite.规格);
								let obj3 = {};
								obj3.text = ite.规格;
								obj3.value = ite.规格;
								that.specsFilters.push(obj3);
							}
							if(that.queryType == "月"){
								if(dateList.indexOf(ite.周)>-1){}else{
									dateList.push(ite.周);
									let obj4 = {};
									obj4.text = ite.周;
									obj4.value = ite.周;
									that.dateFilters.push(obj4);
								}
							}else{
								that.dateFilters = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
							}
							that.nameFilters2 = that.nameFilters;
							that.modelFilters2 = that.modelFilters;
							that.specsFilters2 = that.specsFilters;
							that.dateFilters2 = that.dateFilters;
						})
					}
					that.setChartData(data);
				}
			});
		},
		handleQuery() {
			let that = this;
			if (this.queryType == "月") {
				if (this.queryDate !== "" && this.queryDate !== null) {
					let arr = that.queryDate.split("-");
                    let year = arr[0];
                    let month = arr[1];
                    let days = new Date(year, month, 0).getDate();
					that.start_date = that.queryDate + "-01";
					that.end_date =that.queryDate +"-" +days;
					that.firstWeekNum = that.getWeekOfYear(year,month,1);
					that.endWeekNum = that.getWeekOfYear(year,month,days);
					let duration = that.endWeekNum - that.firstWeekNum + 1;
					let xAxisData = [];
					for (let i = 1; i <= duration; i++) {
						xAxisData.push("第" + i + "周");
					}
					that.xAxisData = xAxisData;
				} else {
					that.start_date =that.currentYear + "-" + that.currentMonth + "-01";
					that.end_date =that.currentYear +"-" +that.currentMonth +"-" +new Date(that.currentYear,that.currentMonth,0).getDate();
					that.firstWeekNum = that.getWeekOfYear(that.currentYear,that.currentMonth,1);
					that.xAxisData = that.xAxisOrigin;
				}
			} else {
				if (that.queryDate !== "" && that.queryDate !== null) {
					that.start_date = that.queryDate + "-01-01";
					that.end_date = that.queryDate + "-12-31";
				} else {
					that.start_date = that.currentYear + "-01-01";
					that.end_date = that.currentYear + "-12-31";
				}
				that.xAxisData = that.monthList;
			}
			that.getTable();
			if (that.materialSale !== "" && that.materialSale !== null) {
				that.getSaleData();
			}
		},
		getSummaries({ columns, data }) {
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				if (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;
		},
		setChartData(data){
			let that = this;
			let option = deepCopy(that.basicOption);
			option.xAxis.data = that.xAxisData;
			option.series=[];
			let materials = [],seriesData = [];
			data.forEach((item) => {
				if(materials.indexOf(item.物料名) == -1){
					materials.push(item.物料名);
				}
			})
			materials.forEach((item) => {
				let obj = {};
				obj.name = item;
				obj.type = "bar";
				obj.stack = "Ad";
				obj.barWidth = "15px";
				obj.data = [0,0,0,0,0,0,0,0,0,0,0,0];
				seriesData.push(obj);
			})
			data.forEach((item) => {
				let index = 0;let indexY = 0;
				if (that.queryType == "月") {
					index = item.周 - that.firstWeekNum;
				} else {
					index = item.月 - 1;
				}
				indexY  = materials.indexOf(item.物料名);
				seriesData[indexY].data[index] = item.数量;
			});
			option.series = seriesData;
			that.setChart("bachart1", option);
		},
		filterName(value, row) {
            return row.物料名 === value;
        },
        filterDate(value, row) {
			if (this.queryType == "月") {
				return row.周 === value;
			}else{
				return row.月 === value;
			}
        },
        filterSpecs(value, row) {
            return row.规格 === value;
        },
        filterModel(value, row) {
             return row.型号 === value;
        },
		filterName2(value, row) {
            return row.物料名 === value;
        },
        filterDate2(value, row) {
			if (this.queryType == "月") {
				return row.周 === value;
			}else{
				return row.月 === value;
			}
        },
        filterSpecs2(value, row) {
            return row.规格 === value;
        },
        filterModel2(value, row) {
             return row.型号 === value;
        },
		handleExport(val) {
			this.exportLoading = true;
			let id = "#exportDiv" + val;
			let name = val == "1" ? "交付统计" : "交付统计总表";
			this.$XLSX(id, name);
			this.exportLoading = false;
		},
	},
};
</script>

<style scoped>
.tables {
	position: absolute;
	top: 4px;
	right: 6px;
	z-index: 10;
}
</style>
