<template>
	<el-container>
		<el-aside style="width: 50%; background: #ffffff">
			<el-container>
				<el-header>
					<div class="left-panel">
						<span style="font-size: 14px">库存统计</span>
					</div>
					<div class="right-panel">
						<el-select
							v-model="params.type"
							clearable
							@change="materialTypeChange"
						>
							<el-option
								v-for="item in materialTypeOptions"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							>
							</el-option>
						</el-select>
						<el-button
							type="primary"
							icon="el-icon-search"
							@click="materialTypeChange"
						></el-button>
						<el-button @click="handleExport('1')" type="primary"
							>导出</el-button
						>
					</div>
				</el-header>
				<el-main>
					<scTable
						v-if="params.type == 10 || params.type == 20"
						ref="tables1"
						:data="tableData1"
						id="exportDiv1"
						stripe
						hideDo
						hidePagination
						:summary-method="getSummaries" show-summary
					>
						<el-table-column type="index" width="50"/>
						<el-table-column label="物料名" prop="material_name" 
						:filters="nameFilters1"
						:filter-method="filterName1"
						filter-placement="bottom-end"/>
						<el-table-column label="型号" prop="material_model" 
						:filters="modelFilters1"
						:filter-method="filterModel1"
						filter-placement="bottom-end"/>
						<el-table-column label="规格" prop="material_specification" 
						:filters="specsFilters1"
						:filter-method="filterSpecs1"
						filter-placement="bottom-end"/>
						<el-table-column prop="dept_name" label="完成车间" 
						:filters="deptFilters1"
						:filter-method="filterDept1"
						filter-placement="bottom-end"/>
						<el-table-column label="库存总数" prop="count" />
					</scTable>
					<scTable
						v-else
						ref="tables11"
						:data="tableData11"
						id="exportDiv11"
						stripe
						hideDo
						:summary-method="getSummaries2" 
						show-summary
					>
						<el-table-column type="index" width="50" />
						<el-table-column label="物料名" prop="name"
						:filters="nameFilters11"
						:filter-method="filterName11"
						filter-placement="bottom-end"/>
						<el-table-column label="型号" prop="model" 
						:filters="modelFilters11"
						:filter-method="filterModel11"
						filter-placement="bottom-end"/>
						<el-table-column label="规格" prop="specification" 
						:filters="specsFilters11"
						:filter-method="filterSpecs11"
						filter-placement="bottom-end"/>
						<el-table-column label="库存总数" prop="count_mb"/>
						<el-table-column label="周预估值" v-if="params.type == 30">
							<template #default="scope">
								<el-input
									v-model="scope.row.week_esitimate_consume"
									@blur="weekcountChange(scope.row)"
								></el-input>
							</template>
						</el-table-column>
						<el-table-column label="可用天数" v-if="params.type == 30">
							<template #default="scope">
								<span v-if="scope.row.week_esitimate_consume &&scope.row.week_esitimate_consume !==null">
									{{Math.floor(scope.row.count_mb /scope.row.week_esitimate_consume) * 7}}
								</span>
							</template>
						</el-table-column>
					</scTable>
				</el-main>
			</el-container>
		</el-aside>
		<el-main class="nopadding">
			<el-container>
				<el-header>
					<div class="left-panel">
						<span style="font-size: 14px">库存出入库统计</span>
					</div>
					<div class="right-panel">
						<el-select
							v-model="query.mio_type"
							clearable
							@change="mioTypeChange"
							style="width: 100px"
						>
							<el-option
								v-for="e in mioTypeEnum.values"
								:key="e.key"
								:value="e.key"
								:label="e.text"
							></el-option>
						</el-select>
						<el-select
							v-model="queryType"
							style="width: 100px"
							@change="queryTypeChnge"
						>
							<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: 100px"
						>
						</el-date-picker>
						<el-date-picker
							v-if="queryType == '年'"
							v-model="queryDate"
							type="year"
							placeholder="查询年"
							value-format="YYYY"
							style="width: 100px"
						>
						</el-date-picker>
						<el-button
							type="primary"
							icon="el-icon-search"
							@click="handleQuery"
						></el-button>
						<el-button @click="handleExport('2')" type="primary">导出</el-button>
					</div>
				</el-header>
				<el-main>
					<scTable
						ref="tables2"
						:data="tableData"
						id="exportDiv2"
						stripe
						hideDo
						hidePagination
						:summary-method="getSummaries"
						show-summary
					>
						<el-table-column label="物料名" prop="物料名"
							:filters="nameFilters2"
							:filter-method="filterName2"
							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="规格" 
							:filters="specsFilters2"
							:filter-method="filterSpecs2"
							filter-placement="bottom-end"
						></el-table-column>
						<el-table-column label="出入库类型">
							<span>{{ mio_type_name }}</span>
						</el-table-column>
						<el-table-column label="执行车间" prop="执行车间"
							:filters="deptFilters2"
							:filter-method="filterDept2"
							filter-placement="bottom-end">
						</el-table-column>
						<template v-if="queryType == '月' &&(query.mio_type == 'pur_in' ||query.mio_type == 'do_in' ||query.mio_type == 'other_in')">
							<el-table-column label="月入库总数" prop="数量"></el-table-column>
						</template>
						<template v-if="queryType == '月' &&(query.mio_type == 'do_out' ||query.mio_type == 'sale_out' ||query.mio_type == 'other_out')">
							<el-table-column label="月出库数量" prop="数量">
							</el-table-column>
						</template>
						<template v-if="queryType == '年' &&(query.mio_type == 'pur_in' ||query.mio_type == 'do_in' ||query.mio_type == 'other_in')">
							<el-table-column label="年入库总数" prop="数量"></el-table-column>
						</template>
						<template v-if="queryType == '年' &&(query.mio_type == 'do_out'||query.mio_type == 'sale_out'||query.mio_type == 'other_out')">
							<el-table-column label="年出库总数" prop="数量"></el-table-column>
						</template>
					</scTable>
				</el-main>
			</el-container>
		</el-main>
	</el-container>
</template>
<script>
import { mioTypeEnum } from "@/utils/enum.js";
function deepCopy(obj) {
	return JSON.parse(JSON.stringify(obj));
}
export default {
	name: "chart",
	data() {
		return {
			mioTypeEnum,
			apiObj: this.$API.mtm.material.list,
			materialType: "",
			params: { is_hidden: false, type: 10, count__gte: 1 },
			query: {
				mio_type: mioTypeEnum.values[0].key,
			},
			mio_type_name: mioTypeEnum.values[0].text,
			queryType: "月",
			queryDate: "",
			start_date: "",
			end_date: "",
			currentYear: "",
			currentMonth: "",
			currentLastDay: "",
			tableData: [],
			tableData1: [],
			tableData11: [],
			nameFilters1: [],
			deptFilters1: [],
			modelFilters1: [],
			specsFilters1: [],
			nameFilters11: [],
			modelFilters11: [],
			specsFilters11: [],
			nameFilters2: [],
			deptFilters2: [],
			modelFilters2: [],
			specsFilters2: [],
			typeOptions: ["月", "年"],
			materialTypeOptions: [
				{ id: 10, name: "成品" },
				{ id: 20, name: "半成品" },
				{ id: 30, name: "主要原料" },
				{ id: 40, name: "辅助材料" },
				{ id: 70, name: "办公用品" },
			],
		};
	},
	mounted() {
		let that = this;
		let date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let lastDay = new Date(year, month, 0).getDate();
		that.currentYear = year;
		that.currentMonth = month > 9 ? month : "0" + month;
		that.currentLastDay = lastDay;
		that.queryDate = that.currentYear + "-" + that.currentMonth;
		that.start_date = that.currentYear + "-" + that.currentMonth + "-01";
		that.end_date = that.currentYear + "-" + that.currentMonth + "-" + lastDay;
		that.getTableData();
		that.getTableData1();
	},
	methods: {
		queryTypeChnge() {
			this.queryDate =null;
		},
		getTableData1() {
			let that = this;
			that.tableData1 = [];
			that.nameFilters1 = [];
			that.deptFilters1 = [];
            that.modelFilters1 = [];
            that.specsFilters1 = [];
			let nameList=[],deptList = [],specsList=[],modelList=[];
			let obj = {
				query: {
					material_types: that.params.type,
				},
			};
			that.$API.bi.dataset.exec.req("materialCount", obj).then((res) => {
				if (res.data2.ds0) {
					let data = res.data2.ds0;
					that.tableData1 = data;
					if(data.length>0){
						data.forEach((ite) => {
							if (nameList.indexOf(ite.material_name) > -1) {} else {
								nameList.push(ite.material_name);
								let obj = {};
								obj.text = ite.material_name;
								obj.value = ite.material_name;
								that.nameFilters1.push(obj);
							}
							if(modelList.indexOf(ite.material_model)>-1){}else{
								modelList.push(ite.material_model);
								let obj2 = {};
								obj2.text = ite.material_model;
								obj2.value = ite.material_model;
								that.modelFilters1.push(obj2);
							}
							if(specsList.indexOf(ite.material_specification)>-1){}else{
								specsList.push(ite.material_specification);
								let obj3 = {};
								obj3.text = ite.material_specificationv;
								obj3.value = ite.material_specification;
								that.specsFilters1.push(obj3);
							}
							if(deptList.indexOf(ite.dept_name)>-1){}else{
								deptList.push(ite.dept_name);
								let obj4 = {};
								obj4.text = ite.dept_name;
								obj4.value = ite.dept_name;
								that.deptFilters1.push(obj4);
							}
						})
					}
				}
			});
		},
		getTableData11(){
			let that = this;
			that.tableData11 = [];
			that.nameFilters11 = [];
            that.modelFilters11 = [];
            that.specsFilters11 = [];
			let nameList=[],specsList=[],modelList=[];
			this.$API.mtm.material.list.req(that.params).then((res) => {
				that.tableData11 = res.results;
				if(res.results.length>0){
					res.results.forEach((ite) =>{
						if (nameList.indexOf(ite.name) > -1) {} else {
							nameList.push(ite.name);
							let obj = {};
							obj.text = ite.name;
							obj.value = ite.name;
							that.nameFilters11.push(obj);
						}
						if(modelList.indexOf(ite.model)>-1){}else{
							modelList.push(ite.model);
							let obj2 = {};
							obj2.text = ite.model;
							obj2.value = ite.model;
							that.modelFilters11.push(obj2);
						}
						if(specsList.indexOf(ite.specification)>-1){}else{
							specsList.push(ite.specification);
							let obj3 = {};
							obj3.text = ite.specification;
							obj3.value = ite.specification;
							that.specsFilters11.push(obj3);
						}
					});
				}
			});
		},
		materialTypeChange(){
			let that = this;
			if(that.params.type == 10 || that.params.type == 20){
				that.getTableData1();
			}else{
				that.getTableData11();
			}
		},
		//更改周预估用量
		weekcountChange(row) {
			let obj = {week_esitimate_consume: row.week_esitimate_consume};
			this.$API.mtm.material.setWeekConsume.req(row.id, obj).then((res) => {
				this.$refs.tables1.refresh();
			});
		},
		//获取表格数据
		getTableData() {
			let that = this;
			that.nameFilters2 = [];
			that.deptFilters2 = [];
            that.modelFilters2 = [];
            that.specsFilters2 = [];
			let nameList=[],deptList = [],specsList=[],modelList=[];
			let exec = that.queryType == "月" ? "saleOutMonth" : "saleOutYear";
			let obj = {
				query: {
					start_date: that.start_date,
					end_date: that.end_date,
					mio_type: that.query.mio_type,
				},
			};
			that.$API.bi.dataset.exec.req(exec, obj).then((res) => {
				if (res.data2.ds0) {
					let data = res.data2.ds0;
					that.tableData = 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.nameFilters2.push(obj);
							}
							if(modelList.indexOf(ite.型号)>-1){}else{
								modelList.push(ite.型号);
								let obj2 = {};
								obj2.text = ite.型号;
								obj2.value = ite.型号;
								that.modelFilters2.push(obj2);
							}
							if(specsList.indexOf(ite.规格)>-1){}else{
								specsList.push(ite.规格);
								let obj3 = {};
								obj3.text = ite.规格;
								obj3.value = ite.规格;
								that.specsFilters2.push(obj3);
							}
							if(deptList.indexOf(ite.执行车间)>-1){}else{
								deptList.push(ite.执行车间);
								let obj4 = {};
								obj4.text = ite.执行车间;
								obj4.value = ite.执行车间;
								that.deptFilters2.push(obj4);
							}
						})
					}
				}
			});
		},
		mioTypeChange() {
			for (let key in this.mioTypeEnum.values) {
				if (this.mioTypeEnum.values[key].key == this.query.mio_type) {
					this.mio_type_name = this.mioTypeEnum.values[key].text;
				}
			}
			this.getTableData();
		},
		handleQuery() {
			let that = this;
			if (that.queryType == "月") {
				if (that.queryDate !== "" && that.queryDate !== null) {
					that.start_date = that.queryDate + "-01";
					let arr = that.queryDate.split("-");
					that.end_date = that.queryDate + "-" + new Date(arr[0], arr[1], 0).getDate();
				} else {
					that.start_date = that.currentYear + "-" + this.currentMonth + "-01";
					that.end_date = that.currentYear + "-" + this.currentMonth + "-" + that.currentLastDay;
				}
			} else {
				if (this.queryDate !== "" && this.queryDate !== null) {
					this.start_date = this.queryDate + "-01-01";
					this.end_date = this.queryDate + "-12-31";
				} else {
					this.start_date = this.currentYear + "-01-01";
					this.end_date = this.currentYear + "-12-31";
				}
			}
			this.getTableData();
		},
		getSummaries({ columns, data }) {
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				if (index == 5) {
					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);
							let sum = Number(Number(prev) + Number(curr)).toFixed(2);
							if (!isNaN(value)) {
								return sum;
							} else {
								return prev;
							}
						}, 0);
					}
				}
			});
			return sums;
		},
		getSummaries2({ columns, data }) {
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return;
				}
				if (index == 4) {
					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);
							let sum = Number(Number(prev) + Number(curr)).toFixed(2);
							if (!isNaN(value)) {
								return sum;
							} else {
								return prev;
							}
						}, 0);
					}
				}
			});
			return sums;
		},

		filterName1(value, row) {
            return row.物料名 == value;
        },
		filterSpecs1(value, row) {
            return row.规格 == value;
        },
        filterModel1(value, row) {
             return row.型号 == value;
        },
		filterDept1(value, row) {
             return row.完成车间 == value;
        },
		filterName11(value, row) {
            return row.物料名 == value;
        },
		filterSpecs11(value, row) {
            return row.规格 == value;
        },
        filterModel11(value, row) {
             return row.型号 == value;
        },
		filterName2(value, row) {
            return row.物料名 == value;
        },
		filterSpecs2(value, row) {
            return row.规格 == value;
        },
        filterModel2(value, row) {
             return row.型号 == value;
        },
		filterDept2(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>
