<template>
	<view class="stock-transfer-page">
		<NavBar :title="$t('库存调拨')"></NavBar>
		<view class="container">
			<view class="search-area">
				<uni-easyinput v-model="value" prefixIcon="search" :placeholder="$t('请输入调拨产品号')" trim="all" focus />
				<button class="search-btn" :loading="loadings" @click="handleSearch">{{$t('确认')}}</button>
			</view>
			<view class="sub-title">
				{{$t('调拨明细')}}
			</view>
			<view class="detail">
				<view class="card" v-for="(item, index) in list" :key="index" @click="handleDetail(item, index)">
					<view class="top">
						<view class="product-number">
							{{`${item[0].ml001}${item[0].materialName}`|}}
						</view>
						<view class="top-r">
							<view class="total-quantity">
								{{getTotalQuantity(item)}}ps
							</view>
							<u-icon name="minus" size="32" @click.native.stop="handleDelete(item, index)"></u-icon>
						</view>
					</view>
					<view class="bottom">
						<!-- 按批次分组显示 -->
						<view class="batch-group" v-for="(batchGroup, batchIndex) in getBatchGroups(item)" :key="batchIndex">
							<view class="batch-header">
								<view class="batch-title">{{$t('批次号')}}：{{batchGroup.batchNo || $t('无批次号')}}</view>
								<view class="batch-total">{{getBatchStockTotal(batchGroup.items)}}ps</view>
							</view>
							<view class="batch-content">
								<view class="content" v-for="(ele, idx) in batchGroup.items" :key="idx">
									<view class="left">
										<view class="text current-storage">
											{{$t('当前储位')}}：{{`${ele.ml002}|${ele.ml003}`}}
										</view>
										<view class="text transfer-storage">
											{{$t('调入储位')}}：
											{{ele.allocateLocation ?  `${ele.allocateWarehouse}|${ele.allocateLocation}`: ''}}
										</view>
									</view>
									<view class="right">
										{{ele.allocateQuantity ? ele.allocateQuantity : 0}}ps
									</view>
								</view>
								<!-- 批次内分隔符 -->
								<view class="batch-separator" v-if="batchGroup.items.length > 1">
									<view class="separator-line"></view>
									<view class="separator-text">{{$t('同批次')}}</view>
									<view class="separator-line"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<button class="sumbit-btn" :loading="loading" @click="handleSumbit">{{$t('调拨确认')}}</button>
		</view>
	</view>
</template>

<script>
	import i18n from '@/lang/index';
	export default {
		data() {
			return {
				loading: false,
				loadings: false,
				value: "",
				list: [],
				numList: [],
			}
		},
		methods: {
			// 按批次分组数据
			getBatchGroups(item) {
				const batchMap = {};
				item.forEach(ele => {
					const batchNo = ele.ml004 || 'no-batch';
					if (!batchMap[batchNo]) {
						batchMap[batchNo] = {
							batchNo: ele.ml004,
							items: []
						};
					}
					batchMap[batchNo].items.push(ele);
				});
				return Object.values(batchMap);
			},
			// 计算所有批次数量合计
			getTotalQuantity(item) {
				return item.reduce((total, ele) => {
					return total + (Number(ele.ml005) || 0);
				}, 0);
			},
			// 计算批次调拨总数
			getBatchTotal(items) {
				return items.reduce((total, item) => {
					return total + (Number(item.allocateQuantity) || 0);
				}, 0);
			},
			// 计算批次库存总数
			getBatchStockTotal(items) {
				return items.reduce((total, item) => {
					return total + (Number(item.ml005) || 0);
				}, 0);
			},
			getValue(data) {
				const index = this.numList.findIndex((item) => {
					return item == data[0]['ml001'].trim();
				})
				this.list.splice(index, 1, data);
			},
			handleReset() {
				this.value = "";
				this.list = [];
				this.numList = [];
			},
			handleSearch() {
				if (this.loadings) {
					return this.$u.toast(i18n.t('请勿重复提交'))
				}
				this.loadings = true;
				if (this.numList.includes(this.value)) {
					this.$u.toast(i18n.t('该调拨产品号数据已存在'));
					setTimeout(() => {
						this.value = "";
					}, 1000);
					return;
				}
				const params = {
					ml001: this.value,
					gtStock: 0
				}
				this.$u.api.getforinvmlinfoApi(params)
					.then(res => {
						this.loadings = false;
						if (res.success) {
							if (res.data.length > 0) {
								this.list.push(res.data);
								this.numList.push(this.value);
								setTimeout(() => {
									this.value = "";
								}, 1000);
							}
						} else {
							this.$u.toast(res.errorMessage);
						}
					})
			},
			handleDetail(row, index) {
				uni.navigateTo({
					url: '/pages/stockTransfer/select?info=' + encodeURIComponent(JSON.stringify(row))
				});
			},
			handleDelete(row, index) {
				this.list.splice(index, 1);
				this.numList.splice(index, 1);
			},
			handleSumbit() {
				if (this.loading) {
					return this.$u.toast(i18n.t('请勿重复提交'));
				}
				if (this.list.length == 0) {
					return this.$u.toast(i18n.t('提交数据不能为空'));
				}
				
				// 检查每组产品是否至少录入了一批调拨数据
				for (let i = 0; i < this.list.length; i++) {
					const item = this.list[i];
					let hasValidTransfer = false;
					
					for (let v = 0; v < item.length; v++) {
						const ele = item[v];
						const allocateQuantity = Number(ele.allocateQuantity) || 0;
						
						if (allocateQuantity > 0 && ele.allocateWarehouse && ele.allocateLocation) {
							hasValidTransfer = true;
							break;
						}
					}
					
					if (!hasValidTransfer) {
						const productName = `${item[0].ml001}${item[0].materialName}`;
						this.$u.toast(`${productName} ${i18n.t('至少需要录入一批调拨数据')}`);
						return;
					}
				}
				
				// 收集所有有效的调拨数据（调拨数大于0且有完整的调拨信息）
				let validTransferData = [];
				let hasInvalidData = false;
				
				for (let i = 0; i < this.list.length; i++) {
					for (let v = 0; v < this.list[i].length; v++) {
						const item = this.list[i][v];
						const allocateQuantity = Number(item.allocateQuantity) || 0;
						
						// 如果调拨数大于0，则检查必填项
						if (allocateQuantity > 0) {
							if (!item.allocateWarehouse) {
								this.$u.toast(i18n.t('调入库存不能为空'));
								hasInvalidData = true;
								break;
							}
							if (!item.allocateLocation) {
								this.$u.toast(i18n.t('调入储位不能为空'));
								hasInvalidData = true;
								break;
							}
							
							// 添加到有效数据中
							validTransferData.push({
								allocateLocation: item.allocateLocation,
								allocateQuantity: item.allocateQuantity,
								allocateWarehouse: item.allocateWarehouse,
								location: item.ml003,
								materialNo: item.ml001,
								warehouse: item.ml002,
								materialName: item.materialName,
								batchNo: item.ml004
							});
						}
					}
					if (hasInvalidData) break;
				}
				
				if (hasInvalidData) {
					return;
				}
				this.loading = true;
				this.$u.api.transferConfirmApi({
						data: validTransferData
					})
					.then(res => {
						this.loading = false;
						if (res.success) {
							this.$u.toast(i18n.t('提交成功'));
							setTimeout(() => {
								this.handleReset();
							}, 1000);
						} else {
							this.$u.toast(res.errorMessage);
						}
					})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.stock-transfer-page {
		width: 100%;
		height: 100%;
		background-color: #ffffff;

		.container {
			.search-area {
				display: flex;
				justify-content: space-between;
				align-content: center;
				padding: 24rpx;

				/deep/.uni-easyinput {
					height: 60rpx;

					.uni-easyinput__content {
						height: 100%;
						border-radius: 36rpx;
					}
				}

				.search-btn {
					height: 60rpx;
					line-height: 60rpx;
					margin-left: 12rpx;
					font-size: 26rpx;
				}
			}

			.sub-title {
				font-size: 32rpx;
				font-weight: bolder;
				padding-left: 24rpx;
			}

			.detail {
				width: calc(100% - 40rpx);
				margin: 20rpx;
				padding: 20rpx;
				padding-bottom: 120rpx;
				background-color: #f1f1f3;
				border-radius: 12rpx;

				.card {
					padding: 12rpx;
					margin-bottom: 24rpx;
					box-sizing: border-box;
					background-color: #ffffff;
					border-radius: 12rpx;

					.top {
						height: 60rpx;
						padding: 0 12rpx;
						padding-bottom: 8rpx;
						box-sizing: border-box;
						display: flex;
						justify-content: space-between;
						align-items: center;
						border-bottom: 1px solid #d8dadf;

						.top-r {
							display: flex;
							justify-content: space-between;
							align-items: center;
							padding-right: 12rpx;

							.total-quantity {
								margin-right: 12rpx;
							}
						}
					}

					.bottom {
						padding: 12rpx;
						box-sizing: border-box;

						.batch-group {
							margin-bottom: 24rpx;
							
							&:last-child {
								margin-bottom: 0;
							}

							.batch-header {
								display: flex;
								justify-content: space-between;
								align-items: center;
								padding: 16rpx 12rpx;
								background-color: #f8f9fa;
								border-radius: 8rpx;
								margin-bottom: 12rpx;

								.batch-title {
									font-size: 28rpx;
									font-weight: bold;
									color: #333;
								}

								.batch-total {
									font-size: 26rpx;
									color: #666;
								}
							}

							.batch-content {
								.content {
									padding: 24rpx 12rpx;
									margin-bottom: 16rpx;
									display: flex;
									justify-content: space-between;
									font-size: 28rpx;
									background-color: #f1f1f3;
									border: 1px solid #d8dadf;
									border-radius: 12rpx;
									box-sizing: border-box;

									.left {
										.text {
											font-size: 28rpx;
										}
									}

									.right {
										padding-right: 28rpx;
									}
								}

								.batch-separator {
									display: flex;
									align-items: center;
									margin: 16rpx 0;
									
									.separator-line {
										flex: 1;
										height: 1px;
										background-color: #d8dadf;
									}
									
									.separator-text {
										padding: 0 16rpx;
										font-size: 24rpx;
										color: #999;
										background-color: #f1f1f3;
									}
								}
							}
						}
					}
				}
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 150rpx;
			padding: 24rpx;
			background-color: #ffffff;

			.sumbit-btn {
				width: 300rpx;
			}
		}
	}
</style>