<template>
	<view class="page">
		<view class="listItemTitle">
			<view @click="handleDetail(null)">
				<view class="item">{{$t('交货单：{0}', [ applyNo ])}}</view>
			</view>
		</view>
		<view class="listBottom">
			<view class="bottomTitle">
				<view class="desc">{{$t('拣货明细')}}</view>
			</view>
			<view  class="bottomBox">
				<view class="bottomItem" v-for="(ele, idx) in goodlist" :key="lineKey(ele, idx)" >
          <view class="box-top">
              <view class="left">
                  <view class="items">{{ ele.materialNo }}|{{ ele.materialName }}</view>
                  <view class="items">{{$t('计划出库日期：{0}', [ ele.planOutDate ])}}</view>
                  <view class="items">{{formatQtyLine(ele)}} {{$t('总量/已提交')}}</view>
              </view>
              <view class="right">
                  <u-icon name="plus" color="#000" size="32" @click="addKC(ele)" v-if="Number(ele.deliverQuantity) > 0"></u-icon>
                  <view class="items pick-line">{{localPickedQuantity(ele)}}/{{ele.deliverQuantity}}pcs {{$t('本次待提交')}}</view>
              </view>
          </view>
					<view class="detail-box">
              <template v-for="(item, index) in list">
                  <view class="detail-line-wrap" v-if="isSameLine(item, ele) && item.outQuantity"  :key="lineKey(ele, idx) + '-d-' + index" @click="handleDetail(item)">
                      <view class="detail-line" :class="{'detail-line--pending': item.fromServer}">
                          <view class="left-info">
                              <text>{{item.warehouse}}|{{item.location}}</text>
                              <text class="batch-info" v-if="item.batchNo">{{item.batchNo}}</text>
                              <text class="pending-tag" v-if="item.fromServer">{{$t('未确认')}}</text>
                          </view>
                          <text style="margin-left: auto">{{item.outQuantity}}pcs</text>
                      </view>
                  </view>
              </template>
          </view>
				</view>
			</view>
		</view>

		<BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
	</view>
</template>

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

import StickyNavBar from '@/components/StickyNavBar/index.vue';
import ContentLoadingMore from '@/components/ContentLoadingMore/index.vue';
import BottomBtn from '@/components/BottomBtn/index.vue';
export default {
	components: {
		StickyNavBar,
		ContentLoadingMore,
		BottomBtn
	},
	props: {
		order: {
			type: String
		},
	},
	data() {
		return {
			r1:'',
			number: 0,
			totalNum: 0,
            show: false,
			applyNo: '',
			wxparams: '',
            list: [],

            goodlist: [],
			btnArr: [
				{
					style: '',
					type: 'warning',
					text: i18n.t('返回'),
					way: 'goBack'
				},
				{
					style: '',
					type: 'primary',
					text: i18n.t('确认'),
					way: 'goSubmit'
				}
			],
			isFocus: false,
			show: true,
		};
	},
    computed: {
    },
    created () {
        uni.$on('sendkcData', (data, info) => {
            // 先移除相同物料的旧数据
            this.list = this.list.filter(item => !this.isSameLine(item, info));

            // 添加新数据
            data.forEach((vvvv) => {
                if (vvvv.outQuantity) {
                    this.list.push({
                        to003: info.to003,
                        deliverQuantity: info.deliverQuantity,
                        location: vvvv.ml003,
                        materialName: info.materialName,
                        materialNo: info.materialNo,
                        outQuantity: vvvv.outQuantity,
                        planOutDate: info.planOutDate,
                        unit: info.unit,
                        warehouse: vvvv.ml002,
                        batchNo: vvvv.ml004
                    })
                }
            })
        });
        if(this.order) {
            this.$u.api
				.stockSaleOutList({
					saleOutNo: this.order
				})
				.then(({data}) => {
					if (data && data.applyNo) {
						this.applyNo = data.applyNo
                        this.list = []
                        this.goodlist = []
                        data.data.forEach(v => {
							this.goodlist.push(this.normalizeSaleLine(v))
                            ;(v.unconfirmedPicks || []).forEach(p => {
                                this.list.push({
                                    to003: v.to003 || p.to003,
                                    materialNo: v.materialNo,
                                    materialName: v.materialName,
                                    deliverQuantity: v.deliverQuantity,
                                    planOutDate: v.planOutDate,
                                    unit: v.unit,
                                    warehouse: p.warehouse,
                                    location: p.location,
                                    batchNo: p.batchNo,
                                    outQuantity: p.outQuantity,
                                    fromServer: true
                                })
                            })
            })
					}
				});
        }
    },

    beforeDestroy() {
    // 移除监听事件，防止内存泄漏
    uni.$off('sendkcData');
    },
	methods: {
        handleDetail(item){
            this.$emit('kcdetail', item)
        },
        goBack() {
            uni.navigateBack();
        },
        goSubmit() {
            if (this.list.length === 0) {
                return;
            }
            const arr = this.list.filter(v => v.outQuantity && !v.fromServer)
            if (arr.length === 0) {
                return;
            }
            this.$u.api.confirmStock({
                applyNo: this.applyNo,
                data: arr
            }).then(res => {
                if (res.success) {
                    this.$u.toast(i18n.t('提交成功'))
					setTimeout(() => {
						uni.$emit('saleckSubmitSuccess')
						uni.navigateBack()
					}, 300)
                }
            })
        },
        addKC(ele) {
            // 获取当前物料的已录入数据
            const existingData = this.list.filter(item =>
                this.isSameLine(item, ele) && !item.fromServer
            );

            const params = {
                info: { ...ele, applyNo: this.applyNo },
                existingData: existingData,
                applyNo: this.applyNo
            };
            
            uni.navigateTo({
                url: `/pages/saleck/selectCK?params=${encodeURIComponent(JSON.stringify(params))}`
            });
        },
        getBtnHandle(row) {
            this[row.way]();
        },
        deliverQuantity(materialNo) {
            const y = JSON.parse(JSON.stringify(this.list))
            const arr = y.filter(i => i.materialNo = materialNo)
            return arr.reduce((pre, cur) => pre + Number(cur.deliverQuantity), 0)
        },
        lineKey(line, idx) {
            return `${line.materialNo || ''}_${line.to003 || ''}_${idx}`
        },
        isSameLine(a, b) {
            if (!a || !b) return false
            return a.materialNo === b.materialNo && String(a.to003 || '') === String(b.to003 || '')
        },
        normalizeSaleLine(v) {
            const total = v.totalQuantity != null ? v.totalQuantity : v.deliverQuantity
            return {
                to003: v.to003,
                materialName: v.materialName,
                materialNo: v.materialNo,
                planOutDate: v.planOutDate,
                unit: v.unit,
                totalQuantity: total,
                confirmedOutQuantity: Number(v.confirmedOutQuantity) || 0,
                unconfirmedOutQuantity: Number(v.unconfirmedOutQuantity) || 0,
                deliverQuantity: Number(v.deliverQuantity) || 0
            }
        },
        formatQtyLine(ele) {
            const total = ele.totalQuantity != null ? ele.totalQuantity : ele.deliverQuantity
            const shipped = (Number(ele.confirmedOutQuantity) || 0) + (Number(ele.unconfirmedOutQuantity) || 0)
            return i18n.t('{0}/{1}pcs', [total, shipped])
        },
        localPickedQuantity(ele) {
            const arr = this.list.filter(i => this.isSameLine(i, ele) && !i.fromServer)
            const num = arr.reduce((pre, cur) => pre + (Number(cur.outQuantity) || 0), 0)
            return isNaN(num) ? 0 : num
        },
        outQuantity(materialNo, deliverQuantity) {
            return this.localPickedQuantity({ materialNo, deliverQuantity })
        },
		deleGonds(row, idx) {
			this.$emit('deleGonds', row, idx);
		}
	}
};
</script>

<style lang="scss" scoped>
.page {
	background: #fff;
}
.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;
	}
}
.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;
		font-weight: 500;
		word-break: break-all;
		font-weight: 600;
	}
}
.listBottom {
    background: #f3f3f5;
    height: calc(100vh - 290rpx);
    overflow: auto;
	.bottomTitle {
		height: 80rpx;
		position: relative;
        background: #fff;
		.desc {
			color: #000;
			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;
        min-height: calc(100% - 520rpx);
        overflow: auto;
		.bottomItem {
			background: #fff;
            border: 1px solid #d4d7dc;
            border-radius: 5px;
			
			margin-bottom: 20rpx;
			position: relative;
			.items {
				color: #333;
				font-size: 24rpx;
				line-height: 40rpx;
				::v-deep .uni-easyinput{
					width: 200rpx;
				}
			}
            .box-top {
                padding: 20rpx;
                display: flex;
                justify-content: space-between;
                
                .right {
                    text-align: right;
                }
            }
            .detail-box {
                padding: 20rpx;
                background: #fff;
                
            }
            .detail-line-wrap {
                &:first-child {
                    border-top: 1px solid #d4d7dc;
                }
            }
            .detail-line {
                background: rgb(243, 243, 245);
                display: flex;
                padding: 10rpx;
                border: 1px solid #d4d7dc;
                min-height: 80rpx;
                border-radius: 5px;
                margin-top: 10px;
                align-items: center;
                
            }
            .left-info {
                display: flex;
                flex-direction: column;
                justify-content: center;
                flex: 1;
                gap: 5rpx;
            }
            .batch-info {
                font-size: 22rpx;
                color: #666;
                line-height: 1.2;
            }
            .pick-line {
                font-size: 22rpx;
                line-height: 1.4;
                text-align: right;
            }
            .pending-tag {
                font-size: 20rpx;
                color: #e6a23c;
            }
            .detail-line--pending {
                border-color: #f3d19e;
                background: #fdf6ec;
            }
		}
	}
}
::v-deep .u-sticky {
	top: 0 !important;
	background: #fff;
}
.boxBtn {
	position: absolute;
	bottom: 10rpx;
	right: 10rpx;
}
.checkedBox{
	text-align: right;
}
::v-deep .uni-checkbox-input-disabled:before{
	color: #007aff !important;
}
</style>
