<template>
	<view class="page">
		<StickyNavBar>
			<NavBar :title="$t('选择库存')"></NavBar>
            <view class="info">{{ info.materialNo }}|{{ info.materialName }}</view>
		</StickyNavBar>
        <ContentLoadingMore class="cardbox" :loadmore='true' :list='goodsList'>
			<view class="cardContent" v-for="(item, index) in goodsList">
				<view class="listItemTitle" @click="handleClick(item)">
					<view>
            <view class="item">{{$t('库房/储位：{0}|{1}', [ item.ml002 , item.ml003 ])}}</view>
            <view class="item">{{$t('批次号：')}}{{item.ml004}}</view>
            <view class="item">{{$t('最近入库日：')}}{{item.ml009}}</view>
						<view class="item">{{$t('库存数：{0}pcs', [ item.ml005 ])}}</view>
						<view class="item">{{$t('出货数：')}}<uni-easyinput
                            v-model="item.outQuantity"
                            placeholder=""
                        ></uni-easyinput></view>
					</view>
				</view>
			</view>
		</ContentLoadingMore>
        <BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
	</view>
</template>

<script>
import i18n from '../../lang/index'

    import ContentLoadingMore from '@/components/ContentLoadingMore/index.vue';
    import BottomBtn from '@/components/BottomBtn/index.vue';
	import StickyNavBar from '@/components/StickyNavBar/index.vue';
	import lhmx from './components/lhmx.vue';
	import kcmx from './components/kcmx.vue';
	export default {
		components: {
			StickyNavBar,
            ContentLoadingMore,
            BottomBtn,
			lhmx,
			kcmx
		},
		data() {
			return {
				current: 0,
                info: {},
                goodsList: [],
                btnArr: [
                    {
                        style: '',
                        type: 'warning',
                        text: i18n.t('返回'),
                        way: 'goBack'
                    },
                    {
                        style: '',
                        type: 'primary',
                        text: i18n.t('提交'),
                        way: 'goSubmit'
                    }
                ]
			};
		},
		computed: {},
		onLoad(option) {
			if (option && option.params) {
                const params = JSON.parse(decodeURIComponent(option.params))
                this.info = params.info
                const existingData = params.existingData || []
                
                this.$u.api
				.getforinvmlinfo({
					ml001: this.info.materialNo
				}).then(({data}) => {
                    if (data) {
                        data.forEach(element => {
                            element['outQuantity'] = 0
                            // 恢复已录入的数量
                            const existingItem = existingData.find(item => 
                                item.warehouse === element.ml002 && 
                                item.location === element.ml003 && 
                                item.batchNo === element.ml004
                            )
                            if (existingItem) {
                                element['outQuantity'] = existingItem.outQuantity
                            }
                        });
                        this.goodsList = data
                    }
                })
			}
		},
		watch: {

		},
		created() {},
		methods: {
            getBtnHandle(row) {
                this[row.way]();
            },
            goBack() {
                uni.navigateBack();
            },
            goSubmit() {
                if (this.goodsList.length === 0) {
                    return;
                }
                
                // 验证先进先出规则
                const validationResult = this.validateFIFO();
                if (!validationResult.valid) {
                    this.$u.toast(validationResult.message);
                    return;
                }
                
                const data = JSON.parse(JSON.stringify(this.goodsList));

                uni.$emit('sendkcData', data, this.info);
                uni.navigateBack();
            },
            
            // 验证先进先出规则
            validateFIFO() {
                let previousDate = null;
                
                for (let i = 0; i < this.goodsList.length; i++) {
                    const currentItem = this.goodsList[i];
                    const outQuantity = Number(currentItem.outQuantity) || 0;
                    const stockQuantity = Number(currentItem.ml005) || 0;
                    const currentDate = currentItem.ml009; // 最近入库日
                    
                    // 跳过未出库的记录
                    if (outQuantity === 0) {
                        continue;
                    }
                    
                    // 检查前一条记录（如果存在且日期不同）
                    if (i > 0) {
                        const previousItem = this.goodsList[i - 1];
                        const previousOutQuantity = Number(previousItem.outQuantity) || 0;
                        const previousStockQuantity = Number(previousItem.ml005) || 0;
                        const previousDate = previousItem.ml009;
                        
                        // 如果最近入库日相同，不验证，当作同一批次处理
                        if (currentDate === previousDate) {
                            continue;
                        }
                        
                        // 如果日期不同，检查前一条是否已出完
                        if (previousOutQuantity > 0 && previousOutQuantity < previousStockQuantity) {
                            return {
                                valid: false,
                                message: i18n.t('请按顺序先进先出', [i, previousDate, i + 1])
                            };
                        }
                    }
                }
                
                return { valid: true };
            },
			handleTabChange(index) {
				this.current = index;
			}
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background: #f8f8f8;
	}
    .info {
        height: 120rpx;
        padding: 0 20rpx;
        line-height: 120rpx;
    }

	.headerTitle {
		padding: 20rpx;
		font-weight: 600;

		.items {
			line-height: 40rpx;
		}
	}

	.btn {
		padding: 20rpx;
		background: #fff;

		.topSearch {
			margin-bottom: 20rpx;
		}
	}

	.bottomBtn {
		position: sticky;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		background: #fff;
		bottom: 0rpx;
		margin-top: 20rpx;

		.u-btn {
			width: 300rpx;
		}
	}

	.blue {
		color: #3f9dcc;
	}

	.total {
		background: #fff;
		color: #000;
		padding: 0rpx 40rpx;
		display: flex;
		justify-content: space-between;
		font-size: 32rpx;

		.line {
			margin: 0px 10rpx;
		}
	}

	.cardbox {
		min-height: calc(100vh - 480rpx);
		padding: 0 20rpx;
		margin-top: 20rpx;
	}

	.cardContent {
		border-radius: 8px;
		background: #fff;
		margin-top: 20rpx;
	}

	.listItemTitle {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		border-bottom: 2px solid #f8f8f8;

		.u-btn {
			width: 150rpx;
			margin: 0px;
			margin-top: 10rpx;
		}

		.item {
			line-height: 50rpx;
			color: #333;
			font-size: 28rpx;
            display: flex;
			font-weight: 500;
            align-items: center;
			word-break: break-all;
			font-weight: 600;
		}
	}

	.listBottom {
		.bottomTitle {
			height: 80rpx;
			position: relative;

			.desc {
				color: #bbb;
				font-size: 24rpx;
				line-height: 80rpx;
				padding-left: 20rpx;
			}

			.topIcons {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				color: #aaa;
			}
		}

		.bottomBox {
			padding: 20rpx;

			.bottomItem {
				background: #f8f8f8;
				padding: 20rpx;
				margin-bottom: 20rpx;

				.items {
					color: #333;
					font-size: 24rpx;
					height: 40rpx;
					line-height: 40rpx;
				}
			}
		}
	}

	::v-deep .u-sticky {
		top: 0 !important;
		background: #fff;
	}

	.checkedCase {
		margin-top: 10rpx;
	}
</style>