<template>
	<view>
		<uni-collapse>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<uni-collapse-item title="领料出库单" :open="true">
					<!-- <view class="example-body"> -->
					<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="drawTaskCode">
						<uni-combox :candidates="drawTaskCodeList" emptyTips="无" @input="scanBarCode"
							v-model="formData.drawTaskCode"></uni-combox>
					</uni-forms-item>
					<!-- </view>	 -->
					<!-- 					    <uni-forms-item label="生产领料任务单" :labelWidth='90' name="drawTaskCode">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarCode" v-model="formData.drawTaskCode" type="text"  />
					</uni-forms-item> -->
					<uni-forms-item label="领料员" :labelWidth='90' name="drawBy">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar1" v-model="formData.drawBy" type="text" />
						<uni-data-picker popup-title="请选择领料员" :localdata="dataTree" v-model="pickerData1"
							@change="onchange1" @nodeclick="onnodeclick1" @popupopened="onpopupopened"
							@popupclosed="onpopupclosed" style="margin-top: 5px;" :preload="true">
						</uni-data-picker>
					</uni-forms-item>
					<uni-forms-item label="出库员" :labelWidth='90' name="warehouseOutBy">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar2" v-model="formData.warehouseOutBy"
							type="text" />
						<uni-data-picker popup-title="请选择出库员" :localdata="dataTree" v-model="pickerData2"
							@change="onchange2" @nodeclick="onnodeclick2" @popupopened="onpopupopened"
							@popupclosed="onpopupclosed" style="margin-top: 5px;" :preload="true">
						</uni-data-picker>
					</uni-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
						<uni-easyinput v-model="formData.warehouseCode" type="text" />
					</uni-forms-item>
				</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.wmsDrawOutDetailList"
							@click="(data) => clickDetail(index,data)" @change="swipChange">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="领料出库单明细编码" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'.drawOutDetailCode'">
								<uni-easyinput type="text" disabled v-model="item.drawOutDetailCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料编码" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'.materialCode'">
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'.materialName'">
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'.materialBatchNo'">
								<uni-easyinput disabled type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="物料箱号" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'.materialLotNo'">
								<uni-easyinput disabled type="number" v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="库位条码" :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="'wmsDrawOutDetailList.'+ 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>
		<u-button type="primary" @click="submit">提交</u-button>
		<view>
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="success" cancelText="取消" confirmText="确定" title="数量检验" content="是否检验数量"
					@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		listPick,
		addOut,
		listTask,
		getDetails
	} from "@/api/wms/pdcMaterial.js";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";
	import {
		listDepartment
	} from "@/api/basic/department";
	export default {
		mounted() {
			this.selectTypeList();
			listDepartment().then((res) => {
				this.dptList = res.rows
			})
			listEmployee().then((res) => {
				this.empList = res.rows
			})
		},
		data() {
			return {
				dptList: [],
				empList: [],
				item: '',
				dataTree: [],
				pickerData1: '',
				pickerData2: '',
				workOrderCode: '',
				drawTaskCodeList: [],
				checkStorageLocationBarcode: true,
				formData: {
					drawTaskCode: '',
					warehouseCode: null,
					drawBy: null,
					warehouseOutBy: null,
					wmsDrawOutDetailList: [],
					billType: '1'
				},
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					drawTaskCode: {
						rules: [{
							required: true,
							errorMessage: '请输入领料任务单!'
						}]
					},
					materialCode: {
						rules: [{
							required: true,
							errorMessage: '请输入物料编码!'
						}]
					},
					number: {
						rules: [{
							required: true,
							errorMessage: '请输入出库数量!'
						}]
					},
					drawBy: {
						rules: [{
							required: true,
							errorMessage: '请输入领料员!'
						}]
					},
					warehouseOutBy: {
						rules: [{
							required: true,
							errorMessage: '请输入出库员!'
						}]
					},
				}
			}
		},
		methods: {
			onnodeclick1(e) {
				console.log(e)
				this.item = e
				this.onchange1(this.item)
			},
			onnodeclick2(e) {
				console.log(e)
				this.item = e
				this.onchange2(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 + '/'
								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)
				// });
			},
			onchange2(e) {
				console.log(e)
				this.formData.warehouseOutBy = null
				this.$set(this.formData, 'warehouseOutBy', e.value.split('/')[0])
				// if (e.value.includes('/')) {
				// 	this.$set(this.formData, 'warehouseOutBy', e.value.split('/')[0])
				// }
			},
			onchange1(e) {
				console.log(e)
				this.formData.drawBy = null
				this.$set(this.formData, 'drawBy', e.value.split('/')[0])
				// if (e.value.includes('/')) {
				// 	this.$set(this.formData, 'drawBy', e.value.split('/')[0])
				// }
			},
			splitStlBarcode(i) {
				const _this = this;
				const detail = _this.formData.wmsDrawOutDetailList[i];

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

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

				let [whCode, storageAreaCode, 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 (storageAreaCode) {
						let areaObj = _this.$store.getters.areaOptions.find(item => item.storageAreaCode ==
							storageAreaCode);
						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.storageAreaCode = storageAreaCode || 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.wmsDrawOutDetailList[i], "storageLocationBarcode", res
							.result);
						// _this.formData.wmsDrawOutDetailList[i].storageLocationBarcode = res.result;
						_this.splitStlBarcode(i);
					}
				});
			},
			swipChange(e, index) {
				console.log('返回：', e);
				console.log('当前索引：', index);
			},
			clickDetail(e, index) {
				console.log('返回：', e);
				this.formData.wmsDrawOutDetailList.splice(e, 1);
				// 		console.log('当前索引：', index);
			},
			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.drawTaskCodeList = [];
				if (this.workOrderCode) {
					listTask({
						workOrderCode: this.workOrderCode
					}).then(async response => {
						for (var i = 0; i < response.rows.length; i++) {
							this.drawTaskCodeList.push(response.rows[i].drawTaskCode);
						}
					});
				}
			},
			selectTypeList() {
				listTask().then(async res => {
					this.drawTaskCodeList = res.rows.map(item => {
						return item.drawTaskCode
					});
				});
			},
			scanBarCode() {
				if (this.formData.drawTaskCode) {
					let data = {
						drawTaskCode: this.formData.drawTaskCode
					}
					getDetails(data).then(async res => {
						console.log(res);
						if (res.details.length > 0) {
							this.formData.wmsDrawOutDetailList = res.details.map(item => {
								item.storageLocationBarcode = item.whCode ? (item.storageAreaCode ? (
										item.shelvesCode ? (item.storageLocationCode ? (item
											.whCode + '-' + item.storageAreaCode + '-' + item
											.shelvesCode +
											'-' + item.storageLocationCode) : (item.whCode +
											'-' + item.storageAreaCode + '-' + item
											.shelvesCode
										)) : (item.whCode + '-' + item.storageAreaCode)) : item
									.whCode) : ''
								return item
							});
						}
					});
				} else {
					this.$modal.msg("请输入生产领料任务单！")
				}
			},
			//领料员
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.drawBy = res.result;
						// _this.scanBarCode(_this.formData.drawBy);
						console.log(res.result);
					}
				});
			},
			//出库员
			scanBar2() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.warehouseOutBy = res.result;
						// _this.scanBarCode(_this.formData.warehouseOutBy);
					}
				});
			},
			//仓库编码
			scanBar3() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.warehouseCode = res.result;
					}
				});
			},
			submit() {
				const _this = this;
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定出库该物料吗？',
						success: function(res) {
							if (res.confirm) {
								console.log(_this.formData)
								if (!_this.checkStorageLocationBarcode) {
									_this.$modal.msg("库位条码校验错误，请重新输入！")
									return;
								}
								_this.$modal.loading('提交中')
								addOut(_this.formData).then(async res => {
									_this.$modal.msgSuccess("出库成功!");
									_this.$modal.closeLoading();
									// _this.$refs.alertDialog.open()
									setTimeout(() => {
										_this.$tab.switchTab("/pages/work/index");
									}, 500);
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
			// dialogConfirm() {
			// 	uni.redirectTo({
			// 	  url: '/pages/target/?param1=xxx&param2=yyy'
			// 	});
			// 	this.$tab.navigateTo('/pages/wms/pdcMaterial/confirmNum');
			// },
			// dialogClose() {
			// 	this.$tab.switchTab('/pages/work/index');
			// },
		}
	}
</script>

<style>
</style>