<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" v-if="value !== '扫物料标签'">
						<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="backTaskCode">
						<uni-easyinput v-model="formData.backTaskCode" disabled />
					</uni-forms-item>
					<uni-forms-item label="生产退料收货单" :labelWidth='90' name="backReceiveCode" v-if="value !== '扫物料标签'">
						<uni-combox :candidates="backReceiveCodeList" emptyTips="无" @input="scanBarReceiveCode"
							v-model="formData.backReceiveCode"></uni-combox>
					</uni-forms-item>
					<uni-forms-item label="生产退料入库单" :labelWidth='90' name="backInCode" v-if="value !== '扫物料标签'">
						<uni-combox :candidates="backInCodeList" emptyTips="无" @input="scanBarBackInCode"
							v-model="formData.backInCode"></uni-combox>
					</uni-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode" v-if="value !== '扫物料标签'">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarwarehouseCode"
							v-model="formData.warehouseCode" />
					</uni-forms-item>
					<uni-forms-item label="上架员" :labelWidth='90' name="shelfPutBy" v-if="value !== '扫物料标签'">
						<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>
							</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'
								name="'wmsBackInDetailList.'+ index +'.storageLocationBarcode'">
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarstorageLocationBarcode(index)"
									@change="splitStlBarcode(index,$event)" type="text"
									v-model="item.storageLocationBarcode" />
							</uni-forms-item>
							<uni-forms-item label="上架数量" :labelWidth='90'>
								<uni-easyinput disabled type="text" v-model="item.number" v-if="value == '扫物料标签'" />
								<u-number-box inputWidth="120" button-size="36" v-model="item.number" v-else
									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-forms-item label="单位" :labelWidth='90' :disabled="true">
								<uni-easyinput type="text" disabled v-model="item.unitText" />
							</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 {
		listIn,
		getIn,
		delIn,
		addIn,
		updateIn,
		exportIn,
		getListDetail,
		updateStock,
		getInBySrc,
		getInByCode,
		getTaskDetailByDetailCode,
		directBackInByTaskDetail
	} 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 {
		listUnit
	} from "@/api/basic/unit";
	
	import {
		getConnectLoc
	} from "@/api/wms/pdcIn.js";
	import _ from 'lodash';
	export default {

		created() {
			this.selectTypeList()
		},
		mounted() {
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
			listUnit().then((res) => {
				this.unitList = res.rows.map(item => {
					let obj = {
						text: item.unitCode + ":" + item.unitName,
						value: item.id
					}
					return obj
				})
			})

			console.log(this.$store)
		},
		data() {
			return {
				buttonDisabled: false,
				wmsLotNoList: [],
				dptList: [],
				empList: [],
				unitList: [],
				item: '',
				dataTree: [],
				pickerData: '',
				value: '正常',
				show: false,
				materialLabel: null,
				//是否都入库
				isAllListed: false,
				isRk: false,
				//是否打开编辑按钮
				isSplit: true,
				backReceiveCodeList: [],
				// backQualityCodeList: [],
				checkStorageLocationBarcode: true,
				backInCodeList: [],
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				formData: {
					workOrderCode: '',
					backReceiveCode: '',
					// backQualityCode: null,
					wmsBackInDetailList: [],
					billType: "1",
					status: "1",
					id: null,
					backInCode: '',
					shelfPutBy: null,
					backTaskCode: ''
				},
				backTaskDetailCode: '',
				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) {
					// this.id = data.id
					getTaskDetailByDetailCode(data.backTaskDetailCode).then(res => {
						console.log(res)
						if (res.backTaskDetail) {
							this.formData.backTaskCode = res.backTaskDetail.backTaskCode;
							let obj = {
								materialCode: res.backTaskDetail.materialCode,
								materialName: res.backTaskDetail.materialName,
								materialBatchNo: res.backTaskDetail.materialBatchNo,
								materialLotNo: res.backTaskDetail.materialLotNo,
								type: res.backTaskDetail.type,
								storageLocationBarcode: res.backTaskDetail.storageLocationBarcode,
								number: res.backTaskDetail.number
							}
							this.backTaskDetailCode = res.backTaskDetail.backTaskDetailCode
							this.formData.wmsBackInDetailList.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);
					}
				});
			},
			async splitStlBarcode(i,event) {
				const _this = this;
				const detail = _this.formData.wmsBackInDetailList[i];

				detail.whCode = null;
				detail.areaCode = null;
				detail.shelvesCode = null;
				detail.storageLocationCode = null;
				console.log(_this.$store)
				let barcode = detail.storageLocationBarcode;
				if (!barcode) {
					return; // 如果没有条码，不做任何处理
				}

				let [whCode, areaCode, shelvesCode, storageLocationCode, extra] = barcode.split('-');
				
				const data = await getConnectLoc({connectLoc:event})
				if(!data.data) return this.$modal.msg("库位条码校验错误，请重新输入！")
				
				_this.checkStorageLocationBarcode = true;
				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.wmsBackInDetailList[i], "storageLocationBarcode", res
							.result);
						_this.splitStlBarcode(i);
					}
				});
			},
			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 = '';
					console.log(this.formData, "this.formData");
					this.selectTask();
				} else {
					this.$modal.msg("生产退料收货单！");
				}
			},
			selectTask() {
				getInBySrc(this.formData).then((res) => {
					console.log(this.formData, "this.formData");
					// 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;
					}
				});
			},
			/** 提交按钮 */
			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('提交中')
							console.log(_this, " _this");
							// _this.formData.wmsBackInDetailList.map(item => {
							// 	item.secondNumber = item.number;
							// 	item.secondUnitId = item.unitId;
							// 	return item
							// })
							let obj = {
								backTaskDetailCode: _this.backTaskDetailCode,
								whCode: _this.formData.wmsBackInDetailList[0].whCode,
								areaCode: _this.formData.wmsBackInDetailList[0]
									.areaCode,
								shelvesCode: _this.formData.wmsBackInDetailList[0]
									.shelvesCode,
								storageLocationCode: _this.formData.wmsBackInDetailList[
									0].storageLocationCode,
								backTaskDetailCode:_this.formData .wmsBackInDetailList[0].backTaskDetailCode
							}
							if (!_this.checkStorageLocationBarcode) {
								_this.$modal.msg("库位条码校验错误，请重新输入！")
								return;
							}
							directBackInByTaskDetail(obj).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>