<template>
    <view class="page">
  <StickyNavBar>
	  <NavBar
      :title="$t('修改领料单信息')"
      right="checkbox"
      :extraRight="form.islot ? 'plus' : ''"
      @clickRight="submit"
      @clickExtraRight="openAddBatch"
    ></NavBar>
  </StickyNavBar>
	<view class="infoedit">
		<u-form ref="form" :modelValue="form" class="login-form" :labelWidth="160">
			<u-form-item prop="tb006" :label="$t('工艺：')" class="disabled">
				<input
					v-model="form.tb006"
					type="text"
					disabled
					
				>
				</input>
			</u-form-item>
			<u-form-item prop="tb003" :label="$t('材料品号：')" class="disabled">
				<input
					v-model="form.tb003"
					disabled
					type="text"
					
					@confirm="submit"
				>
				</input>
			</u-form-item>
			<u-form-item prop="tb012" :label="$t('材料品名：')" class="disabled">
				<input
					v-model="form.tb012"
					disabled
					type="text"
					
					@confirm="submit"
				>
				</input>
			</u-form-item>
			<u-form-item prop="tb004" :label="$t('需领数量：')" class="disabled">
				<input
					v-model="form.tb004"
					disabled
					type="text"
					
					@confirm="submit"
				>
				</input>
			</u-form-item>
			<u-form-item prop="tb005" :label="$t('已领数量：')" class="disabled">
				<input
					v-model="form.tb005"
					disabled
					type="text"
					
					@confirm="submit"
				>
				</input>
			</u-form-item>
      <view v-if="form.islot" class="batch-block default">
			<u-form-item prop="te025" :label="$t('库位：')">
        <zxz-uni-data-select
            v-model="form.te025"
            :localdata="locationOptions"
            displayValueOnly
            placeholder="请选择库位"
            :disabled="loading"
            @change="onLocationChange"
        />
      </u-form-item>
      <u-form-item prop="te010" :label="$t('批次号：')">
        <zxz-uni-data-select
            v-model="form.te010"
            :localdata="batchOptions"
            filterable
            allowInput
            :clear="false"
            :placeholder="$t('请扫码或输入批次号')"
            :disabled="loading || !form.te025"
            @confirm="onBatchInputConfirm('form')"
            @blur="onBatchInputConfirm('form')"
        />
      </u-form-item>
      <u-form-item prop="quantity" :label="$t('领料数量：')">
        <input
            v-model.number="form.quantity"
            type="text"

            @confirm="submit"
        >
        </input>
      </u-form-item>
      </view>
      <template v-else>
        <u-form-item prop="te025" :label="$t('库位：')">
          <zxz-uni-data-select
              v-model="form.te025"
              :localdata="locationOptions"
              displayValueOnly
              placeholder="请选择库位"
              :disabled="loading"
              @change="onLocationChange"
          />
        </u-form-item>
        <u-form-item prop="te010" :label="$t('批次号：')">
          <zxz-uni-data-select
              v-model="form.te010"
              :localdata="batchOptions"
              filterable
              allowInput
              :clear="false"
              :placeholder="$t('请扫码或输入批次号')"
              :disabled="loading || !form.te025"
              @confirm="onBatchInputConfirm('form')"
              @blur="onBatchInputConfirm('form')"
          />
        </u-form-item>
        <u-form-item prop="quantity" :label="$t('领料数量：')">
          <input
              v-model.number="form.quantity"
              type="text"
              @confirm="submit"
          >
          </input>
        </u-form-item>
      </template>
      <view v-if="form.islot" class="batch-blocks">
        <view class="batch-block" v-for="(item, idx) in chargaArr" :key="idx">
          <view class="batch-row">
            <text>{{$t('库位：')}}</text>
            <text class="batch-value">{{item.te025}}</text>
          </view>
          <view class="batch-row">
            <text>{{$t('批次号：')}}</text>
            <text class="batch-value">{{formatBatchLabel(item.te010, item.te025)}}</text>
          </view>
          <view class="batch-row">
            <text>{{$t('领料数量：')}}</text>
            <text class="batch-value">{{item.quantity}}</text>
          </view>
          <view class="batch-actions">
            <u-icon name="trash" size="28" color="#d9534f" @click="removeBatch(item)"></u-icon>
          </view>
        </view>
      </view>
			<u-form-item style="width:100%;">
			<button
				size="medium"
				type="primary"
				style="width:95%;margin-top: 50rpx"
				@click="submit()"
			>
				<span>{{$t('确定')}}</span>
			</button>
			</u-form-item>
		</u-form>
	</view>
	<uni-popup ref="addBatchPopup" type="bottom">
    <view style="padding:24rpx;background:#fff;">
      <u-form :modelValue="newBatch" :labelWidth="160">
        <u-form-item :label="$t('库位：')">
          <zxz-uni-data-select
            v-model="newBatch.te025"
            :localdata="locationOptions"
            displayValueOnly
            placeholder="请选择库位"
            :disabled="loading"
            @change="onNewLocationChange"
          />
        </u-form-item>
        <u-form-item :label="$t('批次号：')">
          <zxz-uni-data-select
            v-model="newBatch.te010"
            :localdata="newBatchBatchOptions"
            filterable
            allowInput
            :clear="false"
            :placeholder="$t('请扫码或输入批次号')"
            :disabled="loading || !newBatch.te025"
            @confirm="onBatchInputConfirm('newBatch')"
            @blur="onBatchInputConfirm('newBatch')"
          />
        </u-form-item>
        <u-form-item :label="$t('领料数量：')">
          <input v-model.number="newBatch.quantity" type="text"></input>
        </u-form-item>
        <u-form-item style="width:100%;">
          <view style="display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:20rpx">
            <button size="medium" type="default" style="width:48%" @click="$refs.addBatchPopup.close()">
              <span>{{$t('取消')}}</span>
            </button>
            <button size="medium" type="primary" style="width:48%" @click="confirmAddBatch">
              <span>{{$t('添加')}}</span>
            </button>
          </view>
        </u-form-item>
      </u-form>
    </view>
  </uni-popup>
    </view>
  </template>
  
  <script>
import i18n from '../../lang/index'

  import StickyNavBar from "@/components/StickyNavBar/index.vue";
  import ContentLoadingMore from "@/components/ContentLoadingMore/index.vue";
  export default {
    components: {
      StickyNavBar,
      ContentLoadingMore,
    },
	onLoad(option) {
		if (option.info) {
			let data = JSON.parse(decodeURIComponent(option.info));
			this.index = Number(option.index)
			this.info = data
			this.form = data.moctes[this.index]
			// 页面加载时查询库存
			this.loadInventoryData()
		}
	},
	computed: {
		chargaArr() {
			return this.info.moctes.filter(v => v.batch && v.tb003 === this.form.tb003)
		}
	},
    data() {
      return {
		info: null,
		index: 0,
		loading: false, // 加载状态
		inventoryData: [], // 库存数据
		locationOptions: [], // 库位选项
		batchOptions: [], // 批次号选项
		newBatchBatchOptions: [],
		newBatch: {
			te025: '',
			te010: '',
			quantity: null
		},
		form: {
			cd003: null,
      tb003: null,
      tb009: null,
			tb012: null,
			tb004: null,
			cd008: null,
			tb005: null,
			cd019: null,
		}
      };
    },
    created() {
    },
    methods: {
		parseStockQty(item) {
			return Number(item && item.ml005) || 0
		},
		formatWithQty(label, qty) {
			return `${label}（${qty}）`
		},
		getLocationStockQty(location) {
			return this.inventoryData
				.filter(item => item.ml003 === location)
				.reduce((sum, item) => sum + this.parseStockQty(item), 0)
		},
		getBatchStockQty(location, batch) {
			const batchVal = batch || ''
			const row = this.inventoryData.find(
				item => item.ml003 === location && (item.ml004 || '') === batchVal
			)
			return row ? this.parseStockQty(row) : 0
		},
		formatLocationLabel(location) {
			if (!location) return ''
			return this.formatWithQty(location, this.getLocationStockQty(location))
		},
		formatBatchLabel(batch, location) {
			return this.formatWithQty(batch || this.$t('无批号'), this.getBatchStockQty(location, batch))
		},
		buildLocationOptions(list) {
			const map = new Map()
			list.forEach(item => {
				const loc = item.ml003
				if (!loc) return
				map.set(loc, (map.get(loc) || 0) + this.parseStockQty(item))
			})
			return [...map.entries()].map(([location, qty]) => ({
				text: this.formatWithQty(location, qty),
				value: location
			}))
		},
		buildBatchOptions(list, location) {
			const map = new Map()
			list
				.filter(item => item.ml003 === location)
				.forEach(item => {
					const batch = item.ml004 || ''
					map.set(batch, (map.get(batch) || 0) + this.parseStockQty(item))
				})
			return [...map.entries()].map(([batch, qty]) => ({
				text: this.formatWithQty(batch || i18n.t('无批号'), qty),
				value: batch
			}))
		},
		// 加载库存数据
		loadInventoryData() {
			if (!this.form.tb003) return
			
			this.loading = true
			this.$u.api.getforinvmlinfo({
				ml001: this.form.tb003, // 物料品号
				ml002: this.form.tb009, // 仓库
				gtStock: 0 // 仅查询库存数>0，由后端过滤
			}).then(res => {
				this.loading = false
				if (res.success && res.data) {
					this.inventoryData = res.data
					this.initLocationOptions()
				} else {
					this.$u.toast(res.errorMessage || i18n.t('查询库存失败'))
				}
			}).catch(err => {
				this.loading = false
				this.$u.toast(i18n.t('查询库存失败'))
			})
		},
		
		// 初始化库位选项
		initLocationOptions() {
			this.locationOptions = this.buildLocationOptions(this.inventoryData)
			
			// 设置默认库位
			if (this.locationOptions.length > 0) {
				// 如果明细响应数据中有库位，优先使用
				if (this.form.te025 && this.locationOptions.some(opt => opt.value === this.form.te025)) {
					// 保持原有库位
				} else {
					// 默认选择第一个有数据的库位
					this.form.te025 = this.locationOptions[0].value
				}
				this.onLocationChange({value:this.form.te025})
			} else {
				this.$u.toast(i18n.t('未找到该物料的库存信息'))
			}
		},
		
		getLocationValue(location) {
			if (!location) return ''
			return typeof location === 'object' ? location.value : location
		},
		batchOptionsFor(location) {
			if (!location) return []
			return this.buildBatchOptions(this.inventoryData, location)
		},
		resolveBatchValue(input, location) {
			const val = String(input ?? '').trim().replace(/\r?\n/g, '')
			if (!location) return null
			const options = this.batchOptionsFor(location)
			if (!options.length) return null
			const exact = options.find(o => String(o.value) === val)
			if (exact) return exact.value
			const noBatchLabel = i18n.t('无批号')
			if ((val === '' || val === noBatchLabel) && options.some(o => o.value === '')) {
				return ''
			}
			const stripped = val.replace(/（[\d.]+）$/, '').trim()
			if (stripped === noBatchLabel && options.some(o => o.value === '')) return ''
			const byValue = options.find(o => String(o.value) === stripped)
			if (byValue) return byValue.value
			const byLabel = options.find(o => o.text === val || (stripped && o.text && o.text.startsWith(`${stripped}（`)))
			if (byLabel) return byLabel.value
			return null
		},
		normalizeBatchInput(target = 'form', showToast = true) {
			const obj = target === 'form' ? this.form : this.newBatch
			const location = obj.te025
			if (!location) {
				if (showToast && String(obj.te010 ?? '').trim()) {
					this.$u.toast(i18n.t('请先选择库位'))
				}
				obj.te010 = ''
				return false
			}
			const raw = String(obj.te010 ?? '').trim()
			if (!raw) {
				obj.te010 = ''
				return true
			}
			const resolved = this.resolveBatchValue(raw, location)
			if (resolved === null) {
				if (showToast) {
					this.$u.toast(i18n.t('批次号不在可选范围内'))
				}
				obj.te010 = ''
				return false
			}
			obj.te010 = resolved
			return true
		},
		onBatchInputConfirm(target = 'form') {
			this.normalizeBatchInput(target)
		},
		// 库位变化时更新批次号选项
		onLocationChange(location) {
			const loc = this.getLocationValue(location)
			if (!loc) {
				this.batchOptions = []
				this.form.te010 = ''
				return
			}
			this.batchOptions = this.batchOptionsFor(loc)
			const resolved = this.resolveBatchValue(this.form.te010, loc)
			this.form.te010 = resolved !== null ? resolved : ''
		},
		openAddBatch() {
			if (!this.form.islot) return
			if (!this.locationOptions.length) {
				this.loadInventoryData()
			}
			this.newBatch = { te025: this.locationOptions[0]?.value || '', te010: '', quantity: null }
			if (this.newBatch.te025) {
				this.onNewLocationChange({ value: this.newBatch.te025 })
			} else {
				this.newBatchBatchOptions = []
			}
			this.$refs.addBatchPopup.open()
		},
		onNewLocationChange(location) {
			const loc = this.getLocationValue(location)
			if (!loc) {
				this.newBatchBatchOptions = []
				this.newBatch.te010 = ''
				return
			}
			this.newBatchBatchOptions = this.batchOptionsFor(loc)
			const resolved = this.resolveBatchValue(this.newBatch.te010, loc)
			this.newBatch.te010 = resolved !== null ? resolved : ''
		},
		confirmAddBatch() {
			if (!this.form.islot) return
			if (!this.newBatch.te025) {
				return this.$u.toast(i18n.t('请输入库位'))
			}
			if (!this.normalizeBatchInput('newBatch')) return
			if (!this.newBatch.quantity && this.newBatch.quantity !== 0) {
				return this.$u.toast(i18n.t('请输入领料数量'))
			}
      if (this.form.te025 === this.newBatch.te025 && (this.form.te010 || '') === (this.newBatch.te010 || '')) {
        return this.$u.toast(i18n.t('不能重复添加相同批次'))
      }
      const duplicate = this.chargaArr.some(cur => cur.tb003 === this.form.tb003 && cur.te025 === this.newBatch.te025 && (cur.te010 || '') === (this.newBatch.te010 || ''))
      if (duplicate) {
        return this.$u.toast(i18n.t('不能重复添加相同批次'))
      }
			const used = this.chargaArr.reduce((pre, cur) => pre + (Number(cur.quantity) || 0), 0)
			const total = Number(this.form.tb004) || 0
			const remaining = total - used
			if (Number(this.newBatch.quantity) > remaining) {
				return this.$u.toast(i18n.t('超出可领料数量'))
			}
			const item = {
				tb003: this.form.tb003,
				tb006: this.form.tb006,
				ta001: this.form.ta001,
				ta002: this.form.ta002,
				ta006: this.form.ta006,
        tb004: this.form.tb004,
        tb009: this.form.tb009,
				batch: true,
        show: true,
				te010: this.newBatch.te010,
				te025: this.newBatch.te025,
				quantity: Number(this.newBatch.quantity) || 0
			}
			this.getValue(item, null)
			this.$refs.addBatchPopup.close()
			this.$u.toast(i18n.t('添加成功'))
		},
		removeBatch(batch) {
			const idx = this.info.moctes.findIndex(it => it.batch && it.tb003 === this.form.tb003 && it.te025 === batch.te025 && it.te010 === batch.te010)
			if (idx !== -1) {
				this.getValue(null, idx, true)
				this.$u.toast(i18n.t('删除成功'))
			}
		},
		
        calckw(str){
			if(!str) return i18n.t('批号')
			if(typeof str === 'string' && !str.trim()) {
				return i18n.t('批号')
			}
			return str
		},
		addBatch() {
			const item = {
				tb003: this.form.tb003,
				tb006: this.form.tb006,
				ta001: this.form.ta001,
				ta002: this.form.ta002,
				ta006: this.form.ta006,
        tb004: this.form.tb004,
        tb009: this.form.tb009,
				batch: true,
        show: true,
				te010: this.form.te010,
				te025: this.form.te025,
				quantity: 0
			}
			const num = this.chargaArr.reduce((pre, cur) => {
				return pre + cur.quantity
			}, 0)
			uni.navigateTo({
              url: '/pages/moctcforcreate/Batch?info=' + encodeURIComponent(JSON.stringify(item)) + '&num=' + num
            });
		},
		editBatch(item, index) {
			const num = this.chargaArr.reduce((pre, cur) => {
				return pre + cur.quantity
			}, 0)
			uni.navigateTo({
              url: '/pages/moctcforcreate/Batch?info=' + encodeURIComponent(JSON.stringify(item))  + '&num=' + num + '&index=' + index
            });
		},
		getValue(item, index, splice = false){
			if (splice) return this.info.moctes.splice(index, 1)
			if(index === null) {
				this.info.moctes.push(item)
			} else {
				this.$set(this.info.moctes, index, item)
			}
		},
		submit(row) {
			if (this.form.te025 && String(this.form.te010 ?? '').trim() && !this.normalizeBatchInput('form')) {
				return
			}
			if (!this.form.islot) {
				if (this.form['quantity'] && !this.form['te025']) {
					return this.$u.toast(i18n.t('请输入库位'))
				}
                if (!this.form['quantity'] && this.form['quantity'] !== 0) {
					return this.$u.toast(i18n.t('请输入领料数量'))
				}
				if (this.form['tb004'] || this.form['quantity']) {
                    console.log(this.form['tb004'], this.form['quantity'])
					const tb004 = this.form['tb004'] || 0
					const quantity = this.form['quantity'] || 0
					if (tb004 < quantity) return this.$u.toast(i18n.t('超出可领料数量'))
				}
			} else {
        const defaultQty = Number(this.form['quantity']) || 0
        const batchSum = this.chargaArr.reduce((pre, cur) => pre + (Number(cur.quantity) || 0), 0)
        if (defaultQty && !this.form['te025']) {
          return this.$u.toast(i18n.t('请输入库位'))
        }
        const tb004 = Number(this.form['tb004']) || 0
        if (defaultQty + batchSum > tb004) {
          return this.$u.toast(i18n.t('超出可领料数量'))
        }
			}
			let pages = getCurrentPages() 
			
			// 2. 上一页面实例
				// 注意是length长度，所以要想得到上一页面的实例需要 -2
				// 若要返回上上页面的实例就 -3，以此类推
			let prevPage = pages[pages.length -2] 
			// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
			prevPage.$vm.getValue(this.info) 

      // 触发全局事件，通知 Info 页面更新
      uni.$emit('moctcForCreateUpdate', this.info)
			
			// 4. 返回上一页面
			uni.navigateBack({
				delta: 1 // 返回的页面数
			})
		}
    },
  };
  </script>
  
  <style lang="scss" scoped>
  ::v-deep .u-sticky {
    top: 0 !important;
    background: #fff;
  }
  .infoedit {
	padding: 20rpx 20rpx;
	.underline {
		border-bottom: 1px solid #d5d5d5;
		padding-bottom: 0px;
    	line-height: 40px;
		font-weight: 500;
		margin-left: 20rpx;
		font-size: 19px;
	}
	.u-border-bottom:after {
		display: none;
	}
	
  }
  .batchContent{
	color: #787878;
	font-size: 17px;
	width: 100%;
	padding: 15rpx;
	.itemtitle{
		font-weight: 600;
		font-size: 19px;
	}
	&>view{
		width: 100%;
		display: flex;
		justify-content: space-between;
	}
  }
  .batch-blocks{
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding: 10rpx 0;
  }
  .batch-block{
    width: 100%;
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 12rpx;
    padding: 20rpx;
  }
  .batch-row{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;
  }
  .batch-value{
    color: #333;
  }
  .batch-actions{
    display: flex;
    justify-content: flex-end;
    margin-top: 8rpx;
  }
  
  // 下拉框样式优化
  ::v-deep .uni-select {
    height: 35px;
    border: 1px solid #d5d5d5;
    border-radius: 4px;
    padding: 0 10px;
  }
  
  ::v-deep .uni-select__input-text {
    font-size: 14px;
    color: #333;
  }
  
  ::v-deep .uni-select__input-placeholder {
    color: #999;
  }

  </style>
  
