<template>
	<view>
		<uni-collapse>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-collapse-item title="直接入库单" :open="true">
					<uni-forms-item label="工单" :labelWidth='90' name="workOrderCode">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBarPwo" @change="clearPwo"
							v-model="workOrderCode" @confirm="scanBarPwoCode" type="text" />
					</uni-forms-item>
					<uni-forms-item label="产品入库任务单" :labelWidth='90' name="productInTaskCode">
						<uni-combox :candidates="productInTaskCodeList" emptyTips="无" @input="scanBarCode"
							v-model="formData.productInTaskCode"></uni-combox>
					</uni-forms-item>
					<!-- 		    <uni-forms-item label="产品入库任务单" :labelWidth='90' name="productInTaskCode">
							<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarCode" v-model="formData.productInTaskCode" type="text"  />
						</uni-forms-item> -->
					<uni-forms-item label="上架员" :labelWidth='90' name="shelfPutBy">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar1" v-model="formData.shelfPutBy"
							type="text" />
						<uni-data-picker popup-title="请选择上架员" :localdata="dataTree" v-model="pickerData"
							@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
							@popupclosed="onpopupclosed" style="margin-top: 5px;" :preload="true">
						</uni-data-picker>
					</uni-forms-item>
					<uni-forms-item label="入库方式" :labelWidth='90'>
						<u-radio-group v-model="value" iconPlacement="left">
							<u-radio label="正常" name="正常"></u-radio>
							<u-radio label="扫物料标签" name="扫物料标签" style="margin-left: 10px;"></u-radio>
						</u-radio-group>
					</uni-forms-item>
					<!-- <uni-forms-item :labelWidth='90' > -->
					<button size="mini" v-if="value=='扫物料标签' && formData.wmsProductInDetailList.length == 0"
						type="primary" style="text-align: center;margin-left: 30%;font-size: 18px;"
						@click="show=!show">添加物料标签</button>
					<!-- </uni-forms-item> -->
					<u-modal :show="show" title="扫描物料标签编码" showCancelButton closeOnClickOverlay
						@cancel="cancelMaterialLabel" @close="cancelMaterialLabel" :showConfirmButton="false">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBarMaterialLabel" v-model="materialLabel"
							type="text" @confirm="confirmMaterialLabel" maxlength="-1" focus="true" />
					</u-modal>
				</uni-collapse-item>
				<uni-collapse-item title="直接入库单明细" :open="true">
					<uni-swipe-action>
						<uni-swipe-action-item :rightOptions="rightOptions" :key="index"
							v-for="(item, index) in formData.wmsProductInDetailList"
							@click="(data) => clickDetail(index,data)" @change="swipChange">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="物料编码" :labelWidth='90'
								:name="'wmsProductInDetailList.'+ index +'.materialCode'">
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'
								:name="'wmsProductInDetailList.'+ index +'.materialName'">
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'.materialBatchNo'">
								<uni-easyinput disabled type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="物料箱号" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'.materialLotNo'">
								<uni-easyinput disabled type="text" v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="类型" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'.type'">
								<uni-tag v-if="item.type == 1" text="合格" type="success"></uni-tag>
								<uni-tag v-else-if="item.type == 2" text="不良" type="warning"></uni-tag>
								<uni-tag v-else-if="item.type == 3" text="报废" type="error"></uni-tag>
							</uni-forms-item>
							<uni-forms-item label="库位条码" required  :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'.storageLocationBarcode'">
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarstorageLocationBarcode(index)"
									@change="splitStlBarcode(index)" type="text"
									v-model="item.storageLocationBarcode" />
							</uni-forms-item>
							<uni-forms-item label="上架数量" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'number'">
								<uni-easyinput disabled type="text" v-model="item.number" v-if="value == '扫物料标签'" />
								<u-number-box inputWidth="120" button-size="36" v-model="item.number" min="0"
									v-else></u-number-box>
							</uni-forms-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-collapse-item>
			</uni-forms>
		</uni-collapse>
		<u-button type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>
	import {
		addIn,
		listTask,
		getTask,
		getReveive,
		getDetails,
		listReceiveDetail,
		getDetail,
		directProductInByTaskDetail
	} from "@/api/wms/pdcIn.js";
	import {
		listDepartment
	} from "@/api/basic/department";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";
	export default {
		mounted() {
			this.selectTypeList();
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
		},
		data() {
			return {
				value: '正常',
				show: false,
				materialLabel: null,
				workOrderCode: '',
				productInTaskCodeList: [],
				checkStorageLocationBarcode: true,
				dptList: [],
				empList: [],
				item: '',
				dataTree: [],
				pickerData: '',
				formData: {
					billType: '2',
					status: '3',
					productInTaskCode: '',
					shelfPutBy: null,
					wmsProductInDetailList: [],
				},
				//类型
				typeOptions: [{
						value: 1,
						label: "合格",
					},
					{
						value: 2,
						label: "不良",
					},
					{
						value: 3,
						label: "报废",
					},
				],
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					productInTaskCode: {
						rules: [{
							required: true,
							errorMessage: '请输入产品入库任务单!'
						}]
					},
					shelfPutBy: {
						rules: [{
							required: true,
							errorMessage: '请输入上架员编码!'
						}]
					}
				}
			}
		},
		methods: {
			onnodeclick(e) {
				console.log(e)
				this.item = e
				this.onchange(this.item)
			},
			onpopupopened(e) {
				this.dataTree = []
				this.empList.filter(item => item.deptId).forEach(item => {
					item.departmentTitle = this.dptList.find(item2 => item2.id == item.deptId).departmentTitle
					// 检查dataTree中是否已存在相同部门
					let existingDept = this.dataTree.find(dept => dept.value === item.deptId);
					if (existingDept) {
						// 如果已存在相同部门，则将员工信息push进该部门的children数组
						existingDept.children.push({
							text: item.name,
							value: item.empCode
						});
					} else {
						// 如果不存在相同部门，则创建一个新部门对象，包括children数组，并将员工信息push进去
						let newDept = {
							text: item.departmentTitle,
							value: item.deptId,
							children: [{
								text: item.name,
								value: item.empCode
							}]
						};
						this.dataTree.push(newDept);
					}
				})
				console.log(this.dataTree)
			},
			onpopupclosed() {
				//处理不同步
				// this.$nextTick(() => {
				// this.pickerData = this.item.value;
				// this.formData.pickerData = this.item.value;
				// if (!this.item) return
				// this.onchange(this.item)
				// });
			},
			onchange(e) {
				console.log(e)
				this.formData.shelfPutBy = null
				this.$set(this.formData, 'shelfPutBy', e.value.split('/')[0])
			},
			addMaterialLabel() {
				this.show = true;
			},
			cancelMaterialLabel() {
				this.materialLabel = null;
				this.show = false;
			},
			confirmMaterialLabel(data) {
				data = JSON.parse(data)
				if (data) {
					this.id = data.id
					getDetail(data.id).then(res => {
						console.log(res)
						if (res.data) {
							this.formData.productInTaskCode = res.data.productInTaskCode;
							let obj = {
								materialCode: res.data.materialCode,
								materialName: res.data.materialName,
								materialBatchNo: res.data.materialBatchNo,
								materialLotNo: res.data.materialLotNo,
								type: res.data.type,
								storageLocationBarcode: res.data.storageLocationBarcode,
								number: res.data.number
							}
							this.formData.wmsProductInDetailList.push(obj)
							this.materialLabel = null;
							this.show = false;
						} else {
							this.$modal.msg("未查询到该条物料明细！")
						}
					})
				}
			},
			scanBarMaterialLabel() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.materialLabel = res.result;
						// console.log(materialLabel)
						_this.confirmMaterialLabel(_this.materialLabel);
					}
				});
			},
			splitStlBarcode(i) {
				const _this = this;
				const detail = _this.formData.wmsProductInDetailList[i];

				detail.whCode = null;
				detail.areaCode = null;
				detail.shelvesCode = null;
				detail.storageLocationCode = null;

				let barcode = detail.storageLocationBarcode;
				if (!barcode) {
					return; // 如果没有条码，不做任何处理
				}

				let [whCode, areaCode, shelvesCode, storageLocationCode, extra] = barcode.split('-');

				if (whCode) {
					let warehouseObj = _this.$store.getters.warehouseOptions.find(item => item.warehouseCode == whCode);
					if (!warehouseObj) {
						_this.checkStorageLocationBarcode = false;
						_this.$modal.msg("货架不存在！");
						return;
					}
					if (areaCode) {
						let areaObj = _this.$store.getters.areaOptions.find(item => item.storageAreaCode ==
							areaCode);
						if (!areaObj) {
							_this.checkStorageLocationBarcode = false;
							_this.$modal.msg("库区不存在！");
							return;
						}
						if (shelvesCode) {
							let shelvesObj = _this.$store.getters.shelvesOptions.find(item => item.storageShelvesCode ==
								shelvesCode);
							if (!shelvesObj) {
								_this.checkStorageLocationBarcode = false;
								_this.$modal.msg("货架不存在！");
								return;
							};
							if (storageLocationCode) {
								let locationObj = _this.$store.getters.locationOptions.find(item => item
									.storageLocationCode == (extra ?
										(storageLocationCode + '-' + extra) : storageLocationCode));
								if (!locationObj) {
									_this.checkStorageLocationBarcode = false;
									_this.$modal.msg("库位不存在！");
									return;
								};
							}
						}
					}
				}
				_this.checkStorageLocationBarcode = true;
				detail.whCode = whCode || null;
				detail.areaCode = areaCode || null;
				detail.shelvesCode = shelvesCode || null;
				detail.storageLocationCode = extra ? `${storageLocationCode}-${extra}` : storageLocationCode || null;
				console.log(this.wmsLotNoList[i]);
			},
			scanBarstorageLocationBarcode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						// _this.formData.wmsProductInDetailList[i].storageLocationBarcode = res.result;
						_this.$set(_this.formData.wmsProductInDetailList[i], "storageLocationBarcode", res
							.result);
						_this.splitStlBarcode(i);
					}
				});
			},
			clearPwo() {
				if (this.workOrderCode == '' || !this.workOrderCode) {
					this.selectTypeList();
				}
			},
			scanBarPwo() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.workOrderCode = res.result;
						_this.scanBarPwoCode();
					}
				});
			},
			scanBarPwoCode() {
				this.productInTaskCodeList = [];
				if (this.workOrderCode) {
					listTask({
						workOrderCode: this.workOrderCode
					}).then(async res => {
						for (var i in res.rows) {
							this.productInTaskCodeList.push(res.rows[i].productInTaskCode);
						}
					});
				}
			},
			selectTypeList() {
				listTask().then(async res => {
					for (var i in res.rows) {
						this.productInTaskCodeList.push(res.rows[i].productInTaskCode);
					}
				});
			},
			scanBarCode() {
				if (this.formData.productInTaskCode) {
					let obj = {
						productInTaskCode: this.formData.productInTaskCode
					}
					listTask(obj).then(async res => {
						getTask(res.rows[0].id).then(async res => {
							if (res.data.wmsProductInTaskDetailList.length != 0) {
								this.formData.wmsProductInDetailList = res.data
									.wmsProductInTaskDetailList.map(item => {
										item.id = null;
										return item
									})
							} else {
								this.formData.wmsProductInDetailList = [];
							}
						});
					});
				} else {
					this.$modal.msg("请输入任务单！");
				}
			},
			//产品入库任务单
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.productInTaskCode = res.result;
						_this.scanBarCode();
					}
				});
			},
			//上架员
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.shelfPutBy = res.result;
						console.log(res.result)
					}
				});
			},
			submit() {
				const _this = this;
				this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定完成直接入库吗？',
						success: function(res) {
							if (res.confirm) {
								if(!_this.formData.wmsProductInDetailList[0]["storageLocationCode"]){
									_this.$modal.msg("库位无法识别或未输入")
									return
								}
								if (_this.value == '扫物料标签') {
									let obj = {
										id: _this.id,
										whCode: _this.formData.wmsProductInDetailList[0].whCode,
										areaCode: _this.formData.wmsProductInDetailList[0]
											.areaCode,
										shelvesCode: _this.formData.wmsProductInDetailList[0]
											.shelvesCode,
										storageLocationCode: _this.formData.wmsProductInDetailList[
											0].storageLocationCode
									}
									if (!_this.checkStorageLocationBarcode) {
										_this.$modal.msg("库位条码校验错误，请重新输入！")
										return;
									}
						
									_this.$modal.loading('提交中')
									directProductInByTaskDetail(obj).then(async res => {
										_this.$modal.closeLoading();
										_this.$modal.msgSuccess("入库成功!");
										_this.$tab.switchTab('/pages/work/index');
									});
								} else {
									// if(!_this.formData.wmsProductInDetailList[0]["storageLocationCode"]){
									// 	_this.$modal.msg("库码必填！")
									// 	return
									// }
									if (_this.formData.productInTaskCode) {
										// _this.formData.wmsProductInDetailList.map(item => {
										// 	item.secondNumber = item.number;
										// 	item.secondUnitId = item.unitId;
										// 	return item
										// })
							
										if (!_this.checkStorageLocationBarcode) {
											_this.$modal.msg("库位条码校验错误，请重新输入！")
											return;
										}
										_this.$modal.loading('提交中')
										addIn(_this.formData).then(async res => {
											_this.$modal.closeLoading();
											_this.$modal.msgSuccess("入库成功!");
											_this.$tab.switchTab('/pages/work/index');
										});
									}
								}

							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			}
		}
	}
</script>

<style>
</style>