<template>
    <view class="page">
	<NavBar :title="$t('修改领料单信息')" right="checkbox" @clickRight="submit"></NavBar>
	<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>
      <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>
			<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>
    </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 = 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: [], // 批次号选项
		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) {
				// 可以根据需要在这里添加批次号变化时的逻辑
				// 比如更新可领数量等
			}
		},
		
        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,
				batch: 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 {
			}
			let pages = getCurrentPages() 
			
			// 2. 上一页面实例
				// 注意是length长度，所以要想得到上一页面的实例需要 -2
				// 若要返回上上页面的实例就 -3，以此类推
			let prevPage = pages[pages.length -2] 
			// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
			prevPage.$vm.getValue(this.info) 
			
			// 4. 返回上一页面
			uni.navigateBack({
				delta: 1 // 返回的页面数
			})
		}
    },
  };
  </script>
  
  <style lang="scss" scoped>
  /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;
	}
  }
  
  // 下拉框样式优化
  /deep/ .uni-select {
    height: 35px;
    border: 1px solid #d5d5d5;
    border-radius: 4px;
    padding: 0 10px;
  }
  
  /deep/ .uni-select__input-text {
    font-size: 14px;
    color: #333;
  }
  
  /deep/ .uni-select__input-placeholder {
    color: #999;
  }
  </style>
  