<template>
	<div class="my-container">
		<div class="bill-main">
			<module-view :propConfig="config" ref="moduleView" @pagination="getDataList" @search="getDataList"
				@resert="onRefresh" @detail="shortBarge" @onRefresh="onRefresh">
			</module-view>
		</div>
		<batchbyOneModal ref="batchbyOneModal" />
		<liveView ref="liveView" />
	</div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import api from "@/api/currency";
import batchbyOneModal from './components/batchbyOneModal.vue'
import storeTag from './components/storeTag.vue'
import liveView from './components/liveView.vue'
@Component({ components: { batchbyOneModal, liveView } })
export default class Store extends Vue {
	timeNum = 0;
	calculateCount = 0;
	skuInfo: any = ''
	storeHouseInfo: any = ''
	tableInfo: any = ''
	timer: any = null
	//缓存tableConfig
	tableConfig: any = {}

	config: any = {
		attr: {
			calculateH: true
		},
		search: {
			attr: {
				size: 'mini',
			},
			columns: [
				[
					// {
					// 	span: 6,
					// 	label: '标题',
					// 	prop: 'name',
					// 	component: 'by-input',
					// 	// labelWidth: '70px',
					// 	compConfig: {
					// 		attr: {
					// 			placeholder: '请输入标题',
					// 			clearable: true
					// 		}
					// 	}
					// },
					{
						span: 6,
						label: '物料编码',
						prop: 'skuCode',
						component: 'by-input',
						// labelWidth: '70px',
						compConfig: {
							attr: {
								placeholder: '请输入物料编码',
								clearable: true
							}
						}
					},
					{
						span: 6,
						label: '69码-商品条码',
						prop: 'barCode',
						labelWidth: '130px',
						component: 'by-input',
						compConfig: {
							attr: {
								placeholder: '69码-商品条码',
								clearable: true
							}
						}
					},
					{
						span: 6,
						label: '财务编号',
						prop: 'accountingCode',
						component: 'by-input',
						compConfig: {
							attr: {
								placeholder: '请输入财务编号',
								clearable: true
							}
						}
					}
				]
			]
		},
		tool: {
			tools: {
				refresh: true,
				search: true,
			},
			customTools: [{
				name: '短驳调拨',
				icon: 'el-icon-discount',
				event: {
					click: () => {
						this.shortBargeHandel()
					}
				}
			}]
		},
		table: {
			attr: {
				size: 'mini',
				align: 'left',
				height: '620',
				checkbox: true,
			},
			columns: [
				{
					// width: '200px',
					title: '标题',
					field: 'skuTitle',
					// isDetail: true,
					fixed: 'left'
				},
				{
					// width: '200px',
					title: '副标题',
					field: 'skuSubtitle',
				},
				{
					// width: '140px',
					title: '物料编码',
					field: 'skuCode',
				},
				{
					// width: '140px',
					title: '69码-商品条码',
					field: 'barCode',
				},
				{
					// width: '140px',
					title: '财务编号',
					field: 'financialCode',
				},
				{
					title: '刷新极智嘉库存', action: true, plugins: [{
						icon: 'el-icon-refresh',
						name: '刷新',
						audit: '',
						event: {
							click: (item: any) => {
								(this as any).refreshStore(item)
							}
						}
					}]
				}, {
					title: '生命周期', action: true, plugins: [{
						icon: 'el-icon-view',
						name: '查看',
						audit: '',
						event: {
							click: (item: any) => {
								(this as any).openDrawer(item)
							}
						}
					}]
				}
			]
		},
	}
	mounted() {
		this.timer = setInterval(() => {
			this.getDataList()
			this.initTable();
		}, 300)
	}
	// 计算高度
	initTable() {
		if (!this.$refs.moduleView) {
			this.calculateCount++;
			if (this.calculateCount > 5) return;
			setTimeout(() => {
				this.initTable()
			}, 500)
			return
		}
		let tableId: any = (this as any).$refs.moduleView.tableID;
		this.config.table.attr.height = window.innerHeight - 320;
		(this as any).$refs.moduleView.$refs[tableId].recalculate();
	}
	//短驳处理
	shortBargeHandel() {
		let data = (this.$refs.moduleView as any).getSelectData();
		if (!data || data.length == 0) {
			this.$message('请选择数据');
			return
		}
		if (this.$refs.batchbyOneModal) {
			(this.$refs.batchbyOneModal as any).setShow(true);
			(this.$refs.batchbyOneModal as any).setValue(data)
		}
	}
	//打开抽屉
	openDrawer(item: any) {
		if (this.$refs.liveView) {
			(this.$refs.liveView as any).setItem(item);
			(this.$refs.liveView as any).setShow(true);
		}
	}
	addCol() {
		let storeCol = [
			{ title: '极智嘉良品数量', field: 'lpAmount' },
			{ title: '极智嘉次品数量', field: 'cpAmount' },
			{ title: '极智嘉可销售库存', field: 'remainAmount' },
			{ title: '极智嘉锁定数', field: 'lockAmount' },

		]
		//如果this.tableConfig.columns中不存在storeCol,则添加
		if (!this.tableConfig.columns.find((v: any) => (v.field == 'lpAmount' || v.field == 'cpAmount' || v.field == 'remainAmount' || v.field == 'lockAmount'))) {
			this.tableConfig.columns = [...this.tableConfig.columns, ...storeCol]
		}
	}
	//刷新极智嘉库存
	async refreshStore(item: any) {
		//获取this.tableInfo的skuCode字段的值，放入items数组
		let loading = this.$loading({ target: '.main-container' });
		try {
			let items = [item.skuCode]
			//调用api.getJZJInventory
			const res = await api.getJZJInventory({ wareHouseCode: '', items: items })
			if (res.data.code != 200) {
				this.$message.error(res.data.message)
				return
			}
			const resItems = res.data.items
			//遍历this.tableInfo，添加resItems中的数据
			for (let i = 0; i < this.tableInfo.length; i++) {
				for (let j = 0; j < resItems.length; j++) {
					if (this.tableInfo[i].skuCode == resItems[j].barCode) {
						this.tableInfo[i].lpAmount = resItems[j].lpAmount
						this.tableInfo[i].cpAmount = resItems[j].cpAmount
						this.tableInfo[i].remainAmount = resItems[j].remainAmount
						this.tableInfo[i].lockAmount = resItems[j].lockAmount
					}
				}
			}
			(this.$refs.moduleView as any).setTableValue(this.tableInfo);
		} catch (error) {
			console.error(error);
		} finally {
			loading.close();
		}
	}
	// 获取列表数据
	getDataList() {
		if (!this.$refs.moduleView) {
			if (this.timeNum > 5) {
				clearInterval(this.timer)
			}
			this.timeNum++;
			return
		}
		clearInterval(this.timer)
		// this.getPageList(); //旧代码无分页

		// 新分页
		let query = (this.$refs.moduleView as any).getQuery();
		this.newsGetPageList(query)
	}
	// 新分页
	newsGetPageList(query: any) {
		let loading = this.$loading({ target: '.main-container' });
		api.getMaterialInventory().then((res: any) => {
			if (res.code === 200) {
				this.skuInfo = res.data;
			} else loading.close();
		}).then(() => {
			api.pageList({}, 'maindataStorehouse').then((res: any) => {
				if (res.code === 200) {
					this.storeHouseInfo = res.data.records;
				} else loading.close();
				if (res.code === 200) {
					let moduleConfig = (this as any).$lodash.cloneDeep(this.config.table);
					this.storeHouseInfo = res.data.records;
					res.data.records.map((v: any, i: any) => {
						moduleConfig.columns.push({
							// width: '150px',
							title: v.name,
							field: 'custom' + i,
							component: storeTag
						});
					});
					(this as any).$refs.moduleView.setTableConfig(moduleConfig);
					this.tableConfig = moduleConfig
					this.addCol();//添加查询极智嘉商品库存相关数据列
				}
			}).then(() => {
				api.pageList(query, 'maindataMaterialSku').then((res: any) => {
					loading.close();
					if (res.code === 200) {
						for (let i = 0; i < res.data.records.length; i++) {
							for (let j = 0; j < this.storeHouseInfo.length; j++) {
								let nowData = this.skuInfo.filter((v: any) => v.skuId == res.data.records[i].id && v.storeHouseId == this.storeHouseInfo[j].id);
								if (nowData[0]) res.data.records[i]['custom' + j] = nowData[0].inventory;
							}
						}
						(this.$refs.moduleView as any).setTableValue(res.data.records);
						this.tableInfo = res.data.records;
						loading.close();
						let page = {
							pageNo: res.data.current, //当前页
							pageSize: res.data.size, //每页条数
							total: res.data.total //总条数
						};
						(this.$refs.moduleView as any).setPage(page);
					} else this.$message.error(res.msg);
				}).catch(() => loading.close());
			}).catch(() => loading.close());
		}).catch(() => loading.close());
	}

	//旧代码无分页
	getPageList() {
		let loading = this.$loading({ target: '.main-container' });
		api.getMaterialInventory().then((res: any) => {
			if (res.code === 200) {
				this.skuInfo = res.data;
			} else loading.close();
		}).then(() => {
			api.pageList({}, 'maindataStorehouse').then((res: any) => {
				if (res.code === 200) {
					this.storeHouseInfo = res.data.records;
				} else loading.close();
				if (res.code === 200) {
					let moduleConfig = (this as any).$lodash.cloneDeep(this.config.table);
					this.storeHouseInfo = res.data.records;
					res.data.records.map((v: any, i: any) => {
						moduleConfig.columns.push({
							width: '120px',
							title: v.name,
							field: 'custom' + i,
						});
					});
					// moduleConfig.columns.push({
					// 	width: 120,
					// 	title: '操作',
					// 	action: true,
					// 	plugins: [{
					// 		name: '短驳',
					// 		event: {
					// 			click: (item : any) => {
					// 				(this as any).shortBarge(item)
					// 			}
					// 		}
					// 	}, {
					// 		name: '调拨',
					// 		event: {
					// 			click: (item : any) => (this as any).allocate(item)
					// 		}
					// 	}]
					// });
					(this as any).$refs.moduleView.setTableConfig(moduleConfig);
				}
			}).then(() => {
				api.pageList({
					pageNo: 1,
					pageSize: 20,
				}, 'maindataMaterialSku').then((res: any) => {
					if (res.code === 200) {
						for (let i = 0; i < res.data.records.length; i++) {
							for (let j = 0; j < this.storeHouseInfo.length; j++) {
								let nowData = this.skuInfo.filter((v: any) => v.skuId == res.data.records[i].id && v.storeHouseId == this.storeHouseInfo[j].id);
								if (nowData[0]) res.data.records[i]['custom' + j] = nowData[0].inventory;
							}
						}
						(this.$refs.moduleView as any).setTableValue(res.data.records);
						this.tableInfo = res.data.records;
						loading.close();
						// let page = {
						// 	pageNo: res.data.current, //当前页
						// 	pageSize: res.data.size, //每页条数
						// 	total: res.data.total //总条数
						// }; 	
						// (this.$refs.moduleView as any).setPage(page);
					} else loading.close();
				}).catch(() => loading.close());
			}).catch(() => loading.close());
		}).catch(() => loading.close());
	}
	// 查询
	search() {
		let searchID: any = (this as any).$refs.moduleView.searchID;
		let value = (this as any).$refs.moduleView.$refs[searchID].value;
		if (value.name) {
			if (value.skuCode) {
				// let newData = this.tableInfo.filter((v : any) => v.skuCode == value.skuCode && v.name == value.name);
				let newData = this.tableInfo.filter((v: any) => v.skuCode.indexOf(value.skuCode) > -1 && v.name.indexOf(value.name) > -1);
				(this.$refs.moduleView as any).setTableValue(newData);
			} else {
				// let newData = this.tableInfo.filter((v : any) => v.name == value.name);
				let newData = this.tableInfo.filter((v: any) => v.name.indexOf(value.name) > -1);
				(this.$refs.moduleView as any).setTableValue(newData);
			}
		} else {
			if (value.skuCode) {
				// let newData = this.tableInfo.filter((v : any) => v.skuCode == value.skuCode);
				let newData = this.tableInfo.filter((v: any) => v.skuCode.indexOf(value.skuCode) > -1);
				(this.$refs.moduleView as any).setTableValue(newData);
			} else this.getDataList();
		}

	}
	// 短驳
	shortBarge(e: any) {
		// console.log(e);
	}
	// 调拨
	allocate(item: any) {
		// console.log(item);
	}
	// 刷新/重置
	onRefresh() {
		(this as any).$refs.moduleView.clearSearch();
		this.getDataList();
	}
}
</script>
<style lang="scss" scoped>
.my-container {
	width: 100%;
	box-sizing: border-box;
	display: flex;
	padding: 16px;
	height: 100%;

	.bill-left {
		position: relative;
		border-right: solid #EEE 1px;
		flex-shrink: 0;

		.bill-tab {
			width: 150px;
			height: 100%;
			transition: all .5s;
			overflow: hidden;
		}

		.tab-title {
			font-size: 16px;
			padding-bottom: 16px;
			width: 200px;
		}
	}

	.bill-main {
		width: 100%;
		box-sizing: border-box;
		position: relative;
		height: 100%;
		overflow-y: hidden;
	}
}
</style>