<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"
            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"
            placeholder="请选择批次号"
            :disabled="loading"
            @change="onBatchChange"
        />
      </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"
              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"
              placeholder="请选择批次号"
              :disabled="loading"
              @change="onBatchChange"
          />
        </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">{{item.te010 || $t('无批号')}}</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"
            placeholder="请选择库位"
            :disabled="loading"
            @change="onNewLocationChange"
          />
        </u-form-item>
        <u-form-item :label="$t('批次号：')">
          <zxz-uni-data-select
            v-model="newBatch.te010"
            :localdata="newBatchBatchOptions"
            placeholder="请选择批次号"
            :disabled="loading"
          />
        </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: {
		// 加载库存数据
		loadInventoryData() {
			if (!this.form.tb003) return
			
			this.loading = true
      console.log( this.form);
			this.$u.api.getforinvmlinfo({
				ml001: this.form.tb003, // 物料品号
        ml002: this.form.tb009 //仓库
			}).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() {
			// 从库存数据中提取唯一的库位
			const locations = [...new Set(this.inventoryData.map(item => item.ml003).filter(Boolean))]
			
			this.locationOptions = locations.map(location => ({
				text: location,
				value: location
			}))
			
			// 设置默认库位
			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('未找到该物料的库存信息'))
			}
		},
		
		// 库位变化时更新批次号选项
		onLocationChange(location) {
			if (!location) {
				this.batchOptions = []
				this.form.te010 = ''
				return
			}
			
			// 根据选择的库位筛选批次号
			const batches = this.inventoryData
				.filter(item => item.ml003 === location.value)
				.map(item => ({
					text: item.ml004 || i18n.t('无批号'),
					value: item.ml004 || ''
				}))
			
			this.batchOptions = batches
			
			// 设置默认批次号
			if (this.batchOptions.length > 0) {
				// 如果明细响应数据中有批次号，优先使用
				if (this.form.te010 && this.batchOptions.some(opt => opt.value === this.form.te010)) {
					// 保持原有批次号
				} else {
					// 默认选择第一个批次号
					this.form.te010 = this.batchOptions[0].value
				}
			}
		},
		
		// 批次号变化时的处理
		onBatchChange(batch) {
			if (batch && this.form.te025) {
				// 可以根据需要在这里添加批次号变化时的逻辑
				// 比如更新可领数量等
			}
		},
		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) {
			if (!location) {
				this.newBatchBatchOptions = []
				this.newBatch.te010 = ''
				return
			}
			const batches = this.inventoryData
				.filter(item => item.ml003 === location.value)
				.map(item => ({
					text: item.ml004 || i18n.t('无批号'),
					value: item.ml004 || ''
				}))
			this.newBatchBatchOptions = batches
			if (this.newBatchBatchOptions.length > 0) {
				if (!this.newBatch.te010 || !this.newBatchBatchOptions.some(opt => opt.value === this.newBatch.te010)) {
					this.newBatch.te010 = this.newBatchBatchOptions[0].value
				}
			}
		},
		confirmAddBatch() {
			if (!this.form.islot) return
			if (!this.newBatch.te025) {
				return this.$u.toast(i18n.t('请输入库位'))
			}
			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.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>
  
