<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 clearable suffixIcon="scan" @iconClick="scanBarPwo"
							v-model="formData.workOrderCode" @confirm="scanBarPwoCode" type="text" />
					</uni-forms-item>
					<uni-forms-item label="产品入库收货单" :labelWidth='90' name="productReceiveCode">
						<uni-combox :candidates="productReceiveCodeList" emptyTips="无" @input="scanBarReceiveCode"
							v-model="formData.productReceiveCode"></uni-combox>
					</uni-forms-item>
					<uni-forms-item label="产品入库质检单" :labelWidth='90' name="productQualityCode">
						<uni-combox :candidates="productQualityCodeList" emptyTips="无" @input="scanBarQualityCode"
							v-model="formData.productQualityCode" />
					</uni-forms-item>
					<uni-forms-item label="产品入库单" :labelWidth='90' name="productInCode">
						<uni-combox-re labelKey="productInCode" valueKey="productInCode" :candidates="productInCodeList"
							emptyTips="无" @input="scanBarProductInCode"
							v-model="formData.productInCode"></uni-combox-re>
					</uni-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarwarehouseCode"
							v-model="formData.warehouseCode" />
						<uni-data-select style="margin-top: 5px;" v-model="formData.warehouseCode"
							:localdata="wcList"></uni-data-select>
					</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"
							@click="(data) => clickDetail(index,data)"
							v-for="(item, index) in formData.wmsProductInDetailList">
							<view>
								<uni-badge :text="index+1" class="uni-badge-left-margin" type="primary"></uni-badge>
								<button @click="open(index,item)" size="mini"
									:disabled="buttonDisabled ||!formData.id || !item.materialBatchNo"
									type="primary">编辑</button>
							</view>
							<!-- 							<uni-badge :text="index+1" type="primary"></uni-badge> -->
							<uni-forms-item label="物料编码" :name="'wmsProductInDetailList.'+ index +'.materialCode'">
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :name="'wmsProductInDetailList.'+ index +'.materialName'">
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" name="'wmsProductInDetailList.'+ index +'.materialBatchNo'">
								<uni-easyinput type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="物料箱号" name="'wmsProductInDetailList.'+ index +'.materialLotNo'">
								<uni-easyinput disabled type="text" v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="类型" 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="库位条码" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'.storageLocationBarcode'">
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarstorageLocationBarcode(index)"
									@confirm="splitStlBarcode(index)" type="text"
									v-model="item.storageLocationBarcode" />
							</uni-forms-item> -->
							<uni-forms-item label="上架数量" :labelWidth='90'
								name="'wmsProductInDetailList.'+ index +'number'">
								<u-number-box inputWidth="120" button-size="36" v-model="item.number"
									min="0"></u-number-box>
							</uni-forms-item>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</uni-collapse-item>
			</uni-forms>
		</uni-collapse>
		<uni-row :gutter="10">
			<uni-col :span="12">
				<u-button type="success" @click="savesubmit">保存</u-button>
			</uni-col>
			<uni-col :span="12">
				<u-button type="primary" :disabled="!isAllListed" @click="submit">提交</u-button>
			</uni-col>
		</uni-row>
		<!-- <u-modal :show="show" :title="title" content='是否进行批号分包入库'></u-modal> -->
	</view>
</template>

<script>
	import {
		listQuality,
		addIn,
		listTask,
		getTask,
		getReceive,
		getDetails,
		listReceive,
		updateIn,
		listIn,
		getIn,
		listReceiveDetail,
		updateProductIndetail
	} from "@/api/wms/pdcIn.js";
	import {
		getListDetailByBL
	} from "@/api/wms/purchase.js"
	import uniComboxRe from "../../../uni_modules/uni-combox/components/uni-combox/uni-combox-re.vue"
	import {
		listDepartment
	} from "@/api/basic/department";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";
	import {
		listWarehouse
	} from "@/api/wms/warehouse";
	import _ from 'lodash';
	export default {
		created() {
			//监听编辑批号分批后的状态
			uni.$on('backWithParam', (param) => {
				console.log(param);
				if (param.status && param.index) {
					this.formData.wmsProductInDetailList[Number(param.index)].status = param.status
				}
				this.checkIsListed();
			});
		},
		mounted() {
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
			listWarehouse().then((res) => {
				this.wcList = res.rows.map(item => {
					let obj = {
						text: item.warehouseName,
						value: item.warehouseCode
					}
					return obj
				})
			})
		},
		components: {
			uniComboxRe
		},
		data() {
			return {
				buttonDisabled: false,
				dptList: [],
				empList: [],
				wcList: [],
				item: '',
				dataTree: [],
				pickerData: '',
				value: '正常',
				show: false,
				materialLabel: null,
				range: [],
				isRk: false,
				//是否打开编辑按钮
				isSplit: true,
				workOrderCode: '',
				productReceiveCodeList: [],
				productQualityCodeList: [],
				productInCodeList: [],
				formData: {
					workOrderCode: '',
					productReceiveCode: '',
					productQualityCode: '',
					shelfPutBy: null,
					wmsProductInDetailList: [],
					billType: "1",
					status: "1",
					id: null,
					productInCode: ''
				},
				//是否都入库
				isAllListed: false,
				// storageLocationBarcode:null,
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					shelfPutBy: {
						rules: [{
							required: true,
							errorMessage: '请输入上架员编码!'
						}]
					},
					// workOrderCode: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入工单!'
					// 	}]
					// }
				},
				wmsLotNoList: []
			}
		},
		methods: {
			deleteDetail(index) {
				this.formData.wmsProductInDetailList.splice(index, 1);
			},
			clickDetail(itemIndex, {
				position,
				index
			}) {
				if (index == 0) {
					this.deleteDetail(itemIndex);
				}
			},
			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) {
					//判断是否已入库
					listReceiveDetail({
						productInTaskDetailId: data.id
					}).then(res => {
						console.log(res)
						//若已有收货单
						if (res.data.length > 0) {
							this.formData.productReceiveCode = res.data[0].productReceiveCode;
							// this.formData.workOrderCode = data.pwoCode;
							this.formData.productQualityCode = '';
							this.formData.productInCode = '';
							this.selectTask();
							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);
					}
				});
			},
			//进入编辑页
			open: _.debounce(async function(index, row) {
				console.log(row)
				// 禁用按钮
				this.buttonDisabled = true;
				//拆分下的列表
				this.wmsLotNoList = [];
				//选中的物料明细项
				let selectedRow = row;
				//是否分批
				let isSecondOpen = false;
				//每份数量
				let eachNumber = null;
				//拆分数量
				let splitNumber = null;
				//头部信息
				let singleInfo = {};
				singleInfo.materialCode = row.materialCode;
				singleInfo.materialBatchNo = row.materialBatchNo;
				singleInfo.materialLotNo = row.materialLotNo;
				singleInfo.number = row.number;
				singleInfo.unit = row.unit;
				singleInfo.unitId = row.unitId;
				singleInfo.secondNumber = row.number;
				singleInfo.secondUnitId = row.unitId;
				singleInfo.productInCode = row.productInCode;
				singleInfo.materialName = row.materialName;
				singleInfo.type = row.type;
				singleInfo.storageInBillDetailCode = row.productInDetailCode;
				this.formData.productInCode = row.productInCode;
				await getListDetailByBL({
					materialCode: row.materialCode,
					storageInBillDetailCode: row.productInDetailCode,
					batchNo: row.materialBatchNo,
					lotNo: row.materialLotNo,
				}).then((response) => {
					console.log(response)
					if (
						response.materialDetailList &&
						response.materialStockList
					) {
						/** 导入拆分信息 */
						if (response.materialDetailList.length > 0) {
							if (response.materialDetailList[0].splitNumber != null) {
								splitNumber = response.materialDetailList[0].splitNumber;
							} else if (response.materialDetailList[0].eachNumber != null) {
								eachNumber = response.materialDetailList[0].eachNumber;
							} else if (response.materialDetailList[0].eachSecondNumber != null) {
								eachSecondNumber =
									response.materialDetailList[0].eachSecondNumber;
							}
						}
						/** 导入拆分详情 */
						if (response.materialStockList.length > 0) {
							this.wmsLotNoList = response.materialStockList.map((item) => {
								item.batchNo = item.materialBatchNo;
								item.locCascade = [
									item.whCode,
									item.areaCode,
									item.shelvesCode,
									item.storageLocationCode,
								];
								if (item.whCode != null) {
									item.connectedLocation = item.whCode;
									if (item.areaCode != null) {
										item.connectedLocation = item.connectedLocation + '-' +
											item
											.areaCode;
										if (item.shelvesCode != null) {
											item.connectedLocation = item.connectedLocation +
												'-' +
												item
												.shelvesCode;
											if (item.storageLocationCode != null) {
												item.connectedLocation = item
													.connectedLocation +
													'-' +
													item.storageLocationCode;
											}
										}
									}
								}
								return item;
							});
						}
						if (response.materialStockList.length != 0) {
							isSecondOpen = true;
						}
					} else {
						if (singleInfo.materialLotNo) {
							console.log(singleInfo)
							splitNumber = 1;
							singleInfo.storageInBillCode = singleInfo.productInCode;
							this.wmsLotNoList.push(singleInfo);
							console.log(this.wmsLotNoList)
							isSecondOpen = true;
						}
					}
				});
				console.log(6)
				console.log(this.wmsLotNoList);
				uni.navigateTo({
					url: '/pages/wms/pdcIn/pdcListing?singleInfo=' + encodeURIComponent(JSON.stringify(
							singleInfo)) +
						'&wmsLotNoList=' + encodeURIComponent(JSON.stringify(
							this.wmsLotNoList)) +
						'&selectedRow=' + encodeURIComponent(JSON.stringify(
							selectedRow)) +
						'&eachNumber=' + eachNumber +
						'&splitNumber=' + splitNumber +
						'&isSecondOpen=' + isSecondOpen +
						'&index=' + index
				});
				// 在页面跳转后恢复按钮状态
				setTimeout(() => {
					this.buttonDisabled = false;
				}, 500); // 延时，确保跳转完成后再启用按钮
			}, 1000, {
				leading: true,
				trailing: false
			}),
			splitStlBarcode(i) {
				this.formData.wmsProductInDetailList[i].whCode = null;
				this.formData.wmsProductInDetailList[i].areaCode = null;
				this.formData.wmsProductInDetailList[i].shelvesCode = null;
				this.formData.wmsProductInDetailList[i].storageLocationCode = null;

				let array = this.formData.wmsProductInDetailList[i].storageLocationBarcode.split('-');
				let [whCode, areaCode, shelvesCode, storageLocationCode, extra] = array;

				this.formData.wmsProductInDetailList[i].whCode = whCode || null;
				this.formData.wmsProductInDetailList[i].areaCode = areaCode || null;
				this.formData.wmsProductInDetailList[i].shelvesCode = shelvesCode || null;
				this.formData.wmsProductInDetailList[i].storageLocationCode = extra ? `${storageLocationCode}-${extra}` :
					storageLocationCode || null;
				// 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('-');

				// const checkAndSetField = (obj, field, value, msg) => {
				// 	if (!value) {
				// 		_this.$modal.msg(msg);
				// 		_this.$set(obj, field, null);
				// 		_this.$nextTick(() => {
				// 			_this.$set(obj, "storageLocationBarcode", null);
				// 		});
				// 		return false;
				// 	}
				// 	return true;
				// };

				// let warehouseObj = _this.$store.getters.warehouseOptions.find(item => item.warehouseCode == whCode);
				// if (!checkAndSetField(detail, 'whCode', warehouseObj, "仓库不存在！")) return;

				// let areaObj = _this.$store.getters.areaOptions.find(item => item.storageAreaCode == areaCode);
				// if (!checkAndSetField(detail, 'areaCode', areaObj, "库区不存在！")) return;

				// let shelvesObj = _this.$store.getters.shelvesOptions.find(item => item.storageShelvesCode == shelvesCode);
				// if (!checkAndSetField(detail, 'shelvesCode', shelvesObj, "货架不存在！")) return;

				// let locationObj = _this.$store.getters.locationOptions.find(item => item.storageLocationCode ==
				// 	`${storageLocationCode}-${extra}`);
				// if (!checkAndSetField(detail, 'storageLocationCode', locationObj, "库位不存在！")) return;

				// // 更新formData中的对应字段
				// detail.whCode = whCode || null;
				// detail.areaCode = areaCode || null;
				// detail.shelvesCode = shelvesCode || null;
				// detail.storageLocationCode = extra ? `${storageLocationCode}-${extra}` : storageLocationCode || null;
			},
			scanBarstorageLocationBarcode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.$set(_this.formData.wmsProductInDetailList[i], "storageLocationBarcode", res
							.result);
						_this.splitStlBarcode(i);
					}
				});
			},
			// clearPwo() {
			// 	if (this.formData.workOrderCode == '' || !this.formData.workOrderCode) {
			// 		this.selectTypeList();
			// 	}
			// },
			scanBarPwo() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.workOrderCode = res.result;
						_this.scanBarPwoCode();
					}
				});
			},
			scanBarPwoCode() {
				this.productReceiveCodeList = [];
				this.productQualityCodeList = [];
				this.productInCodeList = [];
				if (this.formData.workOrderCode) {
					listReceive({
						workOrderCode: this.formData.workOrderCode
					}).then(async response => {
						for (var i = 0; i < response.rows.length; i++) {
							this.productReceiveCodeList.push(response
								.rows[i].productReceiveCode);
						}
					});
					listQuality({
						workOrderCode: this.formData.workOrderCode
					}).then(async response => {
						for (var i = 0; i < response.rows.length; i++) {
							this.productQualityCodeList.push(response.rows[i].productQualityCode);
						}
					});
					listIn({
						workOrderCode: this.formData.workOrderCode
					}).then(async response => {
						this.productInCodeList = response.rows
						// for (var i = 0; i < response.rows.length; i++) {
						// 	this.productInCodeList.push(response.rows[i].productInCode);
						// }
					});
				}
			},
			change(e) {
				console.log(e);
			},
			// selectTypeList() {
			// 	this.productReceiveCodeList = [];
			// 	this.productQualityCodeList = [];
			// 	this.productInCodeList = [];
			// 	listReceive().then(async response => {
			// 		for (var i = 0; i < response.rows.length; i++) {
			// 			this.productReceiveCodeList.push(response.rows[i].productReceiveCode);
			// 		}
			// 	});
			// 	listQuality().then(response => {
			// 		for (var i = 0; i < response.rows.length; i++) {
			// 			this.productQualityCodeList.push(response.rows[i].productQualityCode);
			// 		}
			// 	});
			// 	listIn().then(response => {
			// 		for (var i = 0; i < response.rows.length; i++) {
			// 			this.productInCodeList.push(response.rows[i].productInCode);
			// 		}
			// 	});
			// },
			scanBarReceiveCode() {
				if (this.formData.productReceiveCode) {
					this.formData.productQualityCode = '';
					this.formData.productInCode = '';
					this.selectTask();
				} else {
					this.$modal.msg("产品入库收货单！");
				}
			},
			scanBarQualityCode() {
				if (this.formData.productQualityCode) {
					this.formData.productReceiveCode = '';
					this.formData.productInCode = '';
					this.selectTask();
				} else {
					this.$modal.msg("产品入库质检单！");
				}
			},
			selectTask() {
				getDetails(this.formData).then(res => {
					this.formData.wmsProductInDetailList = res.details;
					this.formData.warehouseCode = res.inBill.warehouseCode;
				})
			},
			scanBarProductInCode(i) {
				this.formData.productReceiveCode = '';
				this.formData.productQualityCode = '';
				getIn(this.productInCodeList.find(item => item.productInCode == i).id).then((response) => {
					this.formData = response.data;
					this.checkIsListed();
				});
			},
			//上架员
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.shelfPutBy = res.result;
					}
				});
			},
			savesubmit() {
				const _this = this;
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定保存吗？',
						success: function(res) {
							if (res.confirm) {
								if (_this.formData.productReceiveCode || _this.formData
									.productQualityCode) {
									// _this.formData.wmsProductInDetailList.map(item => {
									// 	item.secondNumber = item.number;
									// 	item.secondUnitId = item.unitId;
									// 	return item
									// })
									if (_this.formData.id != null) {
										_this.$modal.loading('提交中')
										updateIn(_this.formData).then((response) => {
											_this.$modal.closeLoading();
											_this.formData = response.data;
											console.log(_this.formData);
											_this.checkIsListed();
											_this.$modal.msgSuccess("修改成功！");
										});
									} else {
										_this.$modal.loading('提交中')
										addIn(_this.formData).then((response) => {
											_this.$modal.closeLoading();
											_this.formData = response.data;
											console.log(_this.formData);
											_this.checkIsListed();
											_this.$modal.msgSuccess("保存成功！");
										});
									}

								}
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
			/** 提交按钮 */
			submit() {
				const _this = this;
				_this.formData.status = 2;
				//判断明细是否都入库
				if (
					_this.formData.wmsProductInDetailList.filter((obj) => obj.status != 1).length == 0
				) {
					_this.formData.status = 3;
				}
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定完成入库吗？',
						success: function(res) {
							// _this.formData.wmsProductInDetailList.map(item => {
							// 	item.secondNumber = item.number;
							// 	item.secondUnitId = item.unitId;
							// 	return item
							// })
							_this.$modal.loading('提交中')
							updateIn(_this.formData).then(response => {
								_this.$modal.msgSuccess("入库成功！");
								_this.$modal.closeLoading();
								setTimeout(() => {
									_this.$tab.switchTab("/pages/work/index");
								}, 500);
							});
							// }
						}
					});
				});
			},
			//检查是否都入库
			checkIsListed() {
				let flag = true;
				this.formData.wmsProductInDetailList.forEach((item) => {
					if (item.status == 0 || item.status == null) flag = false;
				});
				this.isAllListed = flag;
			},
		}
	}
</script>

<style>
</style>