<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>
					<!-- <view class="example-body"> -->
					<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="'wmsDrawOutDetailList.'+ index +'.storageLocationBarcode'">
								<uni-easyinput suffixIcon="scan" @iconClick="scanBarstorageLocationBarcode(index)"
									@change="(data) => splitStlBarcode(index,data)" type="text"
									v-model="item.storageLocationBarcode" />
							</uni-forms-item>
							<uni-forms-item label="出库数量" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'secondNumber'">
								<u-number-box inputWidth="120" button-size="36" v-model="item.secondNumber"
									min="0"></u-number-box>
									
							</uni-forms-item>
							<uni-forms-item label="单位" :labelWidth='90'
								:name="'wmsDrawOutDetailList.'+ index +'unitText'">
								<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 {
		listTask,
		listPick,
		addOut,
		getDetails,
		getDrawOutDirectlyByTaskCode
	} from "@/api/wms/pdcMaterial.js";
	import {
		listEmployee
	} from "@/api/mes/jobIn.js";
	import {
		listUnit,
		convertBySecondUnitOrNum,
	} from "@/api/basic/unit";
	import {
		listDepartment
	} from "@/api/basic/department";
	export default {
		mounted() {
			// this.test();
			listUnit().then((res) => {
				this.unitList = res.rows.map(item => {
					let obj = {
						text: item.unitCode + ":" + item.unitName,
						value: item.id
					}
					return obj
				})
			})
			this.selectTypeList();
			listEmployee().then((res) => {
				this.empList = res.rows
			})
			listDepartment().then((res) => {
				this.dptList = res.rows
			})

		},
		data() {
			return {
				dptList: [],
				unitList: [],
				empList: [],
				item: '',
				dataTree: [],
				pickerData1: '',
				pickerData2: '',
				workOrderCode: '',
				drawTaskCodeList: [],
				checkStorageLocationBarcode: true,
				formData: {
					drawTaskCode: '',
					billType: '2',
					status: '1',
					wmsDrawOutDetailList: [],
					drawBy: null,
					warehouseCode: null,
					warehouseOutBy: null
				},
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					drawTaskCode: {
						rules: [{
							required: true,
							errorMessage: '请输入生产领料任务单!'
						}]
					},
					drawBy: {
						rules: [{
							required: false,
							errorMessage: '请输入领料员编码!'
						}]
					},
					warehouseOutBy: {
						rules: [{
							required: false,
							errorMessage: '请输入出库员编码!'
						}]
					},
					// warehouseCode:{
					// 	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])
				// }
			},
			clickDetail(e, index) {
				console.log('返回：', e);
				this.formData.wmsDrawOutDetailList.splice(e, 1);
			},
			splitStlBarcode(i) {
				// this.formData.wmsDrawOutDetailList[i].whCode = null;
				// this.formData.wmsDrawOutDetailList[i].storageAreaCode = null;
				// this.formData.wmsDrawOutDetailList[i].shelvesCode = null;
				// this.formData.wmsDrawOutDetailList[i].storageLocationCode = null;

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

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

				// const checkAndSetField = (obj, field, value, msg) => {
				// 	if (!value) {
				// 		_this.$modal.msg(msg);
				// 		_this.$set(obj, field, null);
				// 		_this.$nextTick(() => {
				// 			_this.$set(obj, "storageLocationBarcode", null);
				// 		});
				// 		obj.storageLocationBarcode = null
				// 		return false;
				// 	}
				// 	return true;
				// };
				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.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.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 => {
					for (var i in res.rows) {
						this.drawTaskCodeList.push(res.rows[i].drawTaskCode);
					}
				});
			},
			test() {

			},
			scanBarCode() {

				if (this.formData.drawTaskCode) {
					let data = {
						drawTaskCode: this.formData.drawTaskCode
					}
					//换成直接出库调用的明细接口
					getDrawOutDirectlyByTaskCode(this.formData).then((res) => {
						console.log(res);
						this.formData = res.wmsDrawOut;
						this.formData.wmsDrawOutDetailList = res.wmsDrawOut.wmsDrawOutDetailList.map(
							item => {
								let unitobj = this.unitList.find(i => i.value == item.secondUnitId)
								if (unitobj) {
									item.unitText = unitobj.text
								}
								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("请输入生产领料任务单！")
				}
			},
			//生产领料任务单
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.drawTaskCode = res.result;
						_this.scanBarCode(_this.formData.drawTaskCode);
					}
				});
			},
			//领料员
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.drawBy = res.result;
						console.log(res.result);
					}
				});
			},
			//出库员
			scanBar2() {
				const _this = this;
				uni.scanCode({
					scanType: ['qrCode', 'barCode'],
					success: function(res) {
						_this.formData.warehouseOutBy = res.result;
					}
				});
			},
			//仓库编码
			scanBar3() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.warehouseCode = res.result;
					}
				});
			},
			/**第二数量（数量改变）
			 * 要求基本单位和数量不为空
			 * */
			async secondNumberChange(item) {
				if (item.secondNumber == null || item.secondNumber == "") {
					// this.$emit("update:number", 0);
					item.number=0
				}
				if (item.unitId == null || item.unitId == "") {
					// this.$emit("update:number", this.secondNumber);
					item.number=item.secondNumber
				} else if (
					item.secondNumber &&
					item.materialCode &&
					item.materialCode != "" &&
					item.unitId &&
					item.secondUnitId
				) {
					console.log('secondNumber',item.secondNumber)
					let params = {
						materialCode: item.materialCode,
						number: null,
						unitId: item.unitId,
						secondUnitId: item.secondUnitId,
						secondNumber: item.secondNumber,
					};
					await convertBySecondUnitOrNum(params).then((response) => {
						console.log('第一数量',response.data.number)
						// this.$emit("update:number", response.data.number);
						item.number=response.data.number;
					});
				} else { //其它所有异常情况，都将第二数量同步传给第一数量
				// this.$emit("update:number", this.inputNumber);
					item.number=item.secondNumber;
				}
				return item
			},
			submit() {
				const _this = this;
				this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定完成直接出库吗？',
						success: async function(res) {
							if (res.confirm) {
								// _this.formData.wmsDrawOutDetailList.map(item => {
								// 	item.number = item.secondNumber;
								// 	item.unitId = item.secondUnitId;
								// 	return item
								// })
								await Promise.all(_this.formData.wmsDrawOutDetailList.map(async item => {
									return await _this.secondNumberChange(item)
								}))
								
								if (!_this.checkStorageLocationBarcode) {
									_this.$modal.msg("库位条码校验错误，请重新输入！")
									return;
								}
								_this.$modal.loading('提交中')
								console.log(_this.formData);
								addOut(_this.formData).then(res => {
									_this.$modal.closeLoading();
									_this.$modal.msgSuccess("直接出库成功!");
									setTimeout(() => {
										_this.$tab.switchTab(
											"/pages/work/index");
									}, 500);
								});
								
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			}
		}
	}
</script>

<style>
</style>