<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="backReceiveCode">
						<uni-combox :candidates="backReceiveCodeList" emptyTips="无" @input="scanBarReceiveCode"
							v-model="formData.backReceiveCode"></uni-combox>
					</uni-forms-item>
					<!-- <uni-forms-item label="生产退料入库质检单" :labelWidth='90' name="backQualityCode">
						<uni-combox :candidates="backQualityCodeList" emptyTips="无" @input="scanBarQualityCode"
							v-model="formData.backQualityCode" />
					</uni-forms-item> -->
					<!-- 				<uni-forms-item label="生产退料收货单" :labelWidth='90' name="backReceiveCode">
					<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarReceiveCode"
						v-model="formData.backReceiveCode" type="text" />
				</uni-forms-item> -->
					<uni-forms-item label="生产退料入库单" :labelWidth='90' name="backInCode">
						<uni-combox :candidates="backInCodeList" emptyTips="无" @input="scanBarBackInCode"
							v-model="formData.backInCode"></uni-combox>
						<!-- <uni-easyinput suffixIcon="scan" @iconClick="scanBarPInCode" @confirm="scanBarbackInCodeCode"
						v-model="formData.backInCode" type="text" /> -->
					</uni-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarwarehouseCode"
							v-model="formData.warehouseCode" />
					</uni-forms-item>
					<uni-forms-item label="上架员" :labelWidth='90' name="shelfPutBy">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarshelfPutBy"
							v-model="formData.shelfPutBy" @confirm="isEmp" />
						<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>
					<button size="mini" v-if="value=='扫物料标签' &&formData.wmsBackInDetailList.length == 0" type="primary"
						style="text-align: center;margin-left: 30%;font-size: 18px;" @click="show=!show">添加物料标签</button>
					<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 v-for="(item, index) in formData.wmsBackInDetailList" :key="index">
							<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-forms-item label="物料编码" :labelWidth='90'>
								<uni-easyinput type="text" disabled v-model="item.materialCode" />
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'>
								<uni-easyinput type="text" disabled v-model="item.materialName" />
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'>
								<uni-easyinput type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="箱号" v-if="item.materialLotNo" :labelWidth='90'>
								<uni-easyinput type="text" disabled v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="类型" :labelWidth='90' name="'wmsBackInDetailList.'+ 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-tag v-else-if="item.type == null" text="无" type="primary"></uni-tag>
							</uni-forms-item>
							<uni-forms-item label="上架数量" :labelWidth='90'>
								<u-number-box inputWidth="120" button-size="36" v-model="item.number"
									min="0"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="备注" :labelWidth='90' name="remark">
								<uni-easyinput autoHeight type="textarea" v-model="item.remark"></uni-easyinput>
							</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>
	</view>
</template>

<script>
	import {
		listIn,
		getIn,
		delIn,
		addIn,
		updateIn,
		exportIn,
		getListDetail,
		updateStock,
		getInBySrc,
		getInByCode
	} from "@/api/wms/pdcBack/in";
	import {
		listReceive,
		getReceive,
		delReceive,
		addReceive,
		updateReceive,
		exportReceive,
		getRcvByTask,
		listReceiveDetail,
		updateReceiveDetail,
		listDetail
	} from "@/api/wms/pdcBack/receive";
	import {
		listMaterial
	} from "@/api/wms/request.js";
	import {

		getListDetailByBL,
	} from "@/api/wms/purchase.js";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";

	import {
		listDepartment
	} from "@/api/basic/department";
	import _ from 'lodash';
	export default {

		created() {
			this.selectTypeList()
			//监听编辑批号分批后的状态
			uni.$on('backWithParam', (param) => {
				if (param.status && param.index) {
					this.formData.wmsBackInDetailList[Number(param.index)].status = param.status
				}
				this.checkIsListed();
			});
		},
		mounted() {
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
		},
		data() {
			return {
				buttonDisabled: false,
				wmsLotNoList: [],
				dptList: [],
				empList: [],
				item: '',
				dataTree: [],
				pickerData: '',
				value: '正常',
				show: false,
				materialLabel: null,
				//是否都入库
				isAllListed: false,
				isRk: false,
				//是否打开编辑按钮
				isSplit: true,
				backReceiveCodeList: [],
				// backQualityCodeList: [],
				backInCodeList: [],
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				formData: {
					workOrderCode: '',
					backReceiveCode: '',
					// backQualityCode: null,
					wmsBackInDetailList: [],
					billType: "1",
					status: "1",
					id: null,
					backInCode: '',
					shelfPutBy: null
				},
				rules: {

				}
			}
		},
		methods: {
			deleteDetail(index) {
				this.formData.wmsBackInDetailList.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({
						backTaskDetailCode: data.backTaskDetailCode
					}).then(res => {
						console.log(res)
						//若已有收货单
						if (res.data.length > 0) {
							this.formData.backReceiveCode = res.data[0].backReceiveCode;
							this.formData.deptCode = res.data[0].deptCode
							this.formData.warehouseCode = res.data[0].warehouseCode
							// this.formData.workOrderCode = data.pwoCode;
							this.formData.backQualityCode = '';
							this.formData.backInCode = '';
							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) {
				// 禁用按钮
				this.buttonDisabled = true;

				console.log(row)
				//拆分下的列表
				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.secondNumber = row.number;
				singleInfo.secondUnitId = row.unitId;
				singleInfo.backInCode = row.backInCode;
				singleInfo.materialName = row.materialName;
				singleInfo.type = row.type;
				singleInfo.unitName = row.unit;
				singleInfo.specification = row.specification;
				singleInfo.whCode = row.whCode;
				singleInfo.areaCode = row.areaCode;
				singleInfo.shelvesCode = row.shelvesCode;
				singleInfo.storageLocationCode = row.storageLocationCode;
				singleInfo.storageInBillCode = row.backInCode;
				singleInfo.storageInBillDetailCode = row.backInDetailCode;
				singleInfo.erpDocLineKey1 = row.erpDocLineKey1;
				singleInfo.unitId = row.unitId;

				this.formData.productInCode = row.productInCode;
				await getListDetailByBL(singleInfo).then((response) => {
					if (
						response.materialDetailList &&
						response.materialDetailList.length > 0
					) {
						console.log(1)
						/** 导入拆分信息 */
						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 &&
							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;
							}
						}

					}
				});
				console.log(this.wmsLotNoList);
				uni.navigateTo({
					url: '/pages/wms/pdcBack/pdcBackListing?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.wmsBackInDetailList[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.areaCode == 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.backReceiveCodeList = [];
				// this.productQualityCodeList = [];
				this.backInCodeList = [];
				if (this.formData.workOrderCode) {
					listReceive({
						workOrderCode: this.formData.workOrderCode
					}).then(async response => {
						this.backReceiveCodeList = response.rows.map(item => {
							return item.backReceiveCode
						})
					});
					listIn({
						workOrderCode: this.formData.workOrderCode
					}).then(async response => {
						this.backInCodeList = response.rows.map(item => {
							return item.backInCode
						})
					});
				}
			},
			selectTypeList() {
				listReceive().then(async response => {
					this.backReceiveCodeList = response.rows.map(item => {
						return item.backReceiveCode
					})
				});
				listIn().then(async response => {
					this.backInCodeList = response.rows.map(item => {
						return item.backInCode
					})
				});
			},
			change(e) {
				console.log(e);
			},
			scanBarReceiveCode() {
				if (this.formData.backReceiveCode) {
					// this.formData.productQualityCode = '';
					this.formData.backInCode = '';
					this.selectTask();
				} else {
					this.$modal.msg("生产退料收货单！");
				}
			},
			// scanBarQualityCode() {
			// 	if (this.formData.productQualityCode) {
			// 		this.formData.productReceiveCode = '';
			// 		this.formData.productInCode = '';
			// 		this.selectTask();
			// 	} else {
			// 		this.$modal.msg("产品入库质检单！");
			// 	}
			// },
			selectTask() {
				getInBySrc(this.formData).then((res) => {
					console.log(res);
					// this.form = res.wmsBackIn;
					this.formData.wmsBackInDetailList = res.wmsBackIn.wmsBackInDetailList;
				});
				// getDetails(this.formData).then(res => {
				// 	this.formData.wmsBackInDetailList = res.details;
				// })
			},
			scanBarBackInCode(i) {
				console.log(i)
				this.formData.backReceiveCode = '';

				getInByCode({
					backInCode: i
				}).then((response) => {
					this.formData = response.wmsBackIn;
					this.checkIsListed();
				});
			},
			//上架员
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.shelfPutBy = res.result;
					}
				});
			},
			scanBarwarehouseCode() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.warehouseCode = 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.backReceiveCode) {
									_this.formData.wmsBackInDetailList.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;
											_this.checkIsListed();
											_this.$modal.msgSuccess("修改成功！");
										});
									} else {
										_this.$modal.loading('提交中')
										addIn(_this.formData).then((response) => {
											_this.$modal.closeLoading();
											_this.formData = response.data;
											_this.checkIsListed();
											_this.$modal.msgSuccess("保存成功！");
										});
									}

								}
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
			/** 提交按钮 */
			submit() {
				const _this = this;
				_this.formData.status = 2;
				//判断明细是否都入库
				if (
					_this.formData.wmsBackInDetailList.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.$modal.loading('提交中')
							_this.formData.wmsBackInDetailList.map(item => {
								item.secondNumber = item.number;
								item.secondUnitId = item.unitId;
								return item
							})
							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.wmsBackInDetailList.forEach((item) => {
					if (item.status == 0 || item.status == null) flag = false;
				});
				this.isAllListed = flag;
			},
		}
	}
</script>

<style>
</style>