<template>
	<view class="page">
		<StickyNavBar>
			<NavBar :title="$t('选择库存')"></NavBar>
            <view class="info">
              <view>{{ info.materialNo }}|{{ info.materialName }}</view>
              <view class="info-sub" v-if="qtySummary">{{ qtySummary }} {{$t('总量/已提交')}}</view>
            </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" v-if="item.reservedQuantity > 0">{{$t('未确认占用：{0}pcs', [ item.reservedQuantity ])}}</view>
						<view class="item">{{$t('可用库存：{0}pcs', [ getAvailableStock(item) ])}}</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: [],
                applyNo: '',
                btnArr: [
                    {
                        style: '',
                        type: 'warning',
                        text: i18n.t('返回'),
                        way: 'goBack'
                    },
                    {
                        style: '',
                        type: 'primary',
                        text: i18n.t('提交'),
                        way: 'goSubmit'
                    }
                ]
			};
		},
		computed: {
            qtySummary() {
                const info = this.info || {}
                if (info.totalQuantity == null && info.deliverQuantity == null) return ''
                const total = info.totalQuantity != null ? info.totalQuantity : info.deliverQuantity
                const shipped = (Number(info.confirmedOutQuantity) || 0) + (Number(info.unconfirmedOutQuantity) || 0)
                return this.$t('{0}/{1}pcs', [total, shipped])
            }
        },
		onLoad(option) {
			if (option && option.params) {
                const params = JSON.parse(decodeURIComponent(option.params))
                this.info = params.info
                this.applyNo = params.applyNo || params.info.applyNo || ''
                const existingData = params.existingData || []

                this.$u.api
				.getforinvmlinfo({
					ml001: this.info.materialNo,
					gtStock: 0,
					saleOutNo: this.applyNo,
					lineSeq: this.info.to003
				}).then(({data}) => {
                    if (data) {
                        const list = [...data].sort((a, b) => String(a.ml009 || '').localeCompare(String(b.ml009 || '')))
                        this.initOutQuantityDefaults(list, existingData)
                        this.goodsList = list
                    }
                })
			}
		},
		watch: {

		},
		created() {},
		methods: {
            getAvailableStock(item) {
                if (item.availableQuantity != null && item.availableQuantity !== '') {
                    return item.availableQuantity
                }
                return item.ml005
            },
            getRemainingUnshipped(existingData) {
                const deliverQty = Number(this.info.deliverQuantity) || 0
                const shipped = (existingData || []).reduce((sum, item) => sum + (Number(item.outQuantity) || 0), 0)
                return Math.max(0, deliverQty - shipped)
            },
            initOutQuantityDefaults(list, existingData) {
                let remaining = this.getRemainingUnshipped(existingData)
                list.forEach(element => {
                    const existingItem = existingData.find(item =>
                        item.warehouse === element.ml002 &&
                        item.location === element.ml003 &&
                        item.batchNo === element.ml004
                    )
                    if (existingItem) {
                        element.outQuantity = existingItem.outQuantity
                        return
                    }
                    const stock = Number(this.getAvailableStock(element)) || 0
                    const qty = Math.min(stock, remaining)
                    element.outQuantity = qty > 0 ? qty : 0
                    remaining -= element.outQuantity
                })
            },
            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 {
        min-height: 120rpx;
        padding: 16rpx 20rpx;
        line-height: 1.5;
    }
    .info-sub {
        font-size: 24rpx;
        color: #333;
        line-height: 40rpx;
        margin-top: 0;
    }

	.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>