<template>
	<view>
		<uni-forms ref="form" :modelValue="formData" :rules="rules">
			<uni-row>
				<uni-col :span="24">
					<uni-forms-item label="工单" :labelWidth='90' name="workOrderCode">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBarPwo" v-model="formData.workOrderCode"
							@confirm="scanBarPwoCode" type="text" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="领料任务单" :labelWidth='90' name="drawTaskCode">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar" v-model="formData.drawTaskCode"
							@confirm="scanBarCode" type="text" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="拣货单" :labelWidth='90' name="pickCode">
						<uni-easyinput suffixIcon="scan" @confirm="scanBarCode" @iconClick="scanBar4"
							v-model="formData.pickCode" type="text" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="物料编码" :labelWidth='90' name="materialCode">
						<uni-easyinput disabled v-model="formData.materialCode" type="text" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="物料名称" :labelWidth='90' name="materialName">
						<uni-easyinput type="text" v-model="formData.materialName" disabled />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="物料批号" :labelWidth='90' name="materialBatchNo">
						<uni-easyinput disabled type="text" v-model="formData.materialBatchNo" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="库位编码" :labelWidth='90' name="storageLocationCode">
						<uni-easyinput disabled type="text" v-model="formData.storageLocationCode" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="原有数量" :labelWidth='90' name="originNumber">
						<uni-easyinput disabled type="number" v-model="formData.originNumber" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="拣货数量" :labelWidth='90' name="pickNumber">
						<uni-easyinput disabled type="number" v-model="formData.pickNumber" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="12">
					<uni-forms-item label="现有数量" :labelWidth='90' name="xyNum">
						<uni-easyinput disabled type="number" v-model="xyNum" />
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="拣货区" :labelWidth='90' :name="pickerData" :rules="[{'required': true,
						errorMessage: '请输入拣货区!'}]">
						<uni-data-picker popup-title="请选择所在货区" :localdata="dataTree" v-model="pickerData"
							@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
							@popupclosed="onpopupclosed">
						</uni-data-picker>
						<!-- <uni-easyinput type="text" v-model="formData.pickArea" /> -->
					</uni-forms-item>
				</uni-col>
				<uni-col :span="24">
					<uni-forms-item label="拣货时间" :labelWidth='90' name="pickTime">
						<!-- <view class="uni-list-cell-db"> -->
						<!-- 							<u-datetime-picker ref="datetimePicker" @cancel="close" @confirm="confirm" :show="show"
								v-model="value1" @change="bindDateChange" mode="datetime">
								<view class="uni-input" v-model="formData.pickTime">{{formData.pickTime}}</view>
							</u-datetime-picker> -->
						<!-- <picker style="padding-top: 10px;" mode="time" :value="formData.pickTime" :start="startDate"
								:end="endDate" @change="bindDateChange">
								<view class="uni-input" v-model="formData.pickTime">{{formData.pickTime}}</view>
							</picker> -->
						<!-- <uni-datetime-picker></uni-datetime-picker> -->
						<!-- 							<u-datetime-picker :show="show" v-model="value1" @change="bindDateChange"
								mode="datetime"></u-datetime-picker>
							<view class="uni-input" @click="show=true" v-model="formData.pickTime">
								{{formData.pickTime}}
							</view> -->
						<!-- </view> -->

						<view class="example-body">
							<uni-datetime-picker type="datetime" v-model="formData.pickTime" />
						</view>
					</uni-forms-item>
				</uni-col>
			</uni-row>
		</uni-forms>

		<u-button type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>
	import {
		addPick,
		getTask,
		updatePick,
		listPick
	} from "@/api/wms/pdcMaterial.js";
	import {
		listMaterial
	} from "@/api/wms/request.js";
	import {
		listArea
	} from "@/api/wms/area.js";
	import {
		listLocation
	} from "@/api/wms/location.js";
	import {
		listShelves
	} from "@/api/wms/shelves.js";
	import {
		listWarehouse
	} from "@/api/wms/warehouse.js";
	export default {
		onLoad: function(option) {
			// this.test();
			// this.getPickArea();
			// 获取当前时间
			var currentDate = new Date();
			// 格式化为字符串（YYYY-MM-DD HH:mm:ss）
			var year = currentDate.getFullYear();
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var hours = ("0" + currentDate.getHours()).slice(-2);
			var minutes = ("0" + currentDate.getMinutes()).slice(-2);
			var seconds = ("0" + currentDate.getSeconds()).slice(-2);
			var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
			// 将当前时间赋值给 formData.updateTime
			this.formData.pickTime = formattedDate;
		},
		data() {
			return {
				show: false,
				item: '',
				dataTree: [],
				pickerData: '',
				value1: Number(new Date()),
				xyNum: null,
				formData: {
					pickTime: null,
					workOrderCode: null,
					drawTaskCode: null,
					materialCode: null,
					materialName: null,
					materialBatchNo: null,
					whCode: null,
					areaCode: null,
					shelvesCode: null,
					storageLocationCode: null,
					originNumber: null,
					pickNumber: null,
					pickTime: null,
					pickCode: null,
					pickArea: null,
				},
				rules: {
					drawTaskCode: {
						rules: [{
							required: true,
							errorMessage: '请输入领料任务单!'
						}]
					},
					pickCode: {
						rules: [{
							required: true,
							errorMessage: '请输入拣货单!'
						}]
					},

				}
			}

		},
		computed: {
			// startDate() {
			// 	return this.getDate('start');
			// },
			// endDate() {
			// 	return this.getDate('end');
			// }
		},
		// onReady() {
		// 	// 微信小程序需要用此写法
		// 	this.$refs.datetimePicker.setFormatter(this.formatter)
		// },
		methods: {
			getPickArea() {
				let data = new Array();
				listWarehouse().then((response) => {
					let obj = response.rows.map(({
						warehouseName,
						warehouseCode,
						id
					}) => ({
						warehouseName,
						warehouseCode,
						id
					}));
					for (var i = 0; i < obj.length; i++) {
						this.dataTree.push({
							text: obj[i].warehouseName,
							value: obj[i].warehouseCode + '/' + obj[i].warehouseName + '/' + obj[i]
								.id,
						});
					}

					listArea().then((response) => {
						let aobj = response.rows.map(
							({
								storageAreaName,
								storageAreaCode,
								id,
								warehouseCode
							}) => ({
								storageAreaName,
								storageAreaCode,
								id,
								warehouseCode
							})
						);
						for (var i = 0; i < aobj.length; i++) {
							const atemp = this.dataTree.find(
								(item) => item.value.split('/')[0] == aobj[i].warehouseCode
							);
							if (atemp) {
								if (!atemp.children) {
									atemp.children = [];
								}
								atemp.children.push({
									text: aobj[i].storageAreaName,
									// value: aobj[i].storageAreaCode,
									value: aobj[i].storageAreaCode + '/' + aobj[i]
										.storageAreaName + '/' + aobj[i].id + '/' +
										aobj[i]
										.warehouseCode,
								});
							}
						}
						listShelves().then((response) => {
							let sobj = response.rows.map(
								({
									storageShelvesCode,
									storageShelvesName,
									id,
									storageAreaCode,
									warehouseCode
								}) => ({
									storageShelvesCode,
									storageShelvesName,
									id,
									storageAreaCode,
									warehouseCode
								})
							);
							const stemp = this.dataTree.filter((item) => item
								.children);
							for (var i = 0; i < sobj.length; i++) {
								for (var j = 0; j < stemp.length; j++) {
									const temp = stemp[j].children.find(
										(item) => item.value.split('/')[0] ==
										sobj[i]
										.storageAreaCode
									);
									if (temp) {
										if (!temp.children) {
											temp.children = [];
										}
										temp.children.push({
											text: sobj[i]
												.storageShelvesName,
											// value: sobj[i].storageShelvesCode,
											value: sobj[i]
												.storageShelvesCode +
												'/' +
												sobj[
													i].storageShelvesName +
												'/' +
												sobj[
													i]
												.id + '/' + sobj[i]
												.storageAreaCode +
												'/' +
												sobj[i].warehouseCode,
										});
									}
								}

							}
							listLocation().then((response) => {
								let lobj = response.rows.map(({
									storageLocationCode,
									storageLocationName,
									id,
									storageShelvesCode,
									storageAreaCode,
									warehouseCode
								}) => ({
									storageLocationCode,
									storageLocationName,
									id,
									storageShelvesCode,
									storageAreaCode,
									warehouseCode
								}));
								const lItem = this.dataTree.filter(
									(parentItem) =>
									parentItem.children &&
									parentItem.children.find((
											childItem) =>
										childItem
										.children)
								);
								for (var i = 0; i < lobj.length; i++) {
									for (var j = 0; j < lItem
										.length; j++) {
										for (var k = 0; k < lItem[j]
											.children
											.length; k++) {
											if (lItem[j].children[k]
												.children) {
												const temp = lItem[j]
													.children[k]
													.children
													.find(
														(item) => item
														.value.split(
															'/')[
															0] == lobj[
															i]
														.storageShelvesCode
													);
												if (temp) {
													if (!temp
														.children) {
														temp
															.children = [];
													}
													temp.children
														.push({
															text: lobj[
																	i
																]
																.storageLocationName,
															// value: lobj[i]
															// 	.storageLocationCode,
															value: lobj[
																	i
																]
																.storageLocationCode +
																'/' +
																lobj[
																	i
																]
																.storageLocationName +
																'/' +
																lobj[
																	i
																]
																.id +
																'/' +
																lobj[
																	i
																]
																.storageShelvesCode +
																'/' +
																lobj[
																	i
																]
																.storageAreaCode +
																'/' +
																lobj[
																	i
																]
																.warehouseCode,
														});
												}
											}
										}
									}
								}


								// if (this.formData.status == '2') {

								// }
								this.dataTree = JSON.parse(JSON
									.stringify(this
										.dataTree))
								//状态为拣货完成时，默认为原来的仓库，否则默认拣货仓
								if (this.formData.status != '2') {
									//默认进入拣货仓
									// if (!this.formData.whCode) {
									if (this.dataTree.find(item => item
											.text ==
											'拣货仓')) {
										let data = this.dataTree.find(
											item => item
											.text == '拣货仓')
										this.item = data
										this.pickerData = this.item.value;
										if (!this.item) return
										this.onchange(this.item)
										this.onpopupclosed();
									}
									// }

								} else {
									this.getDataPicker(this.formData
										.whCode, this
										.formData
										.areaCode, this.formData
										.shelvesCode, this.formData
										.storageLocationCode
									)
								}
							});
						});
					});
				});

			},
			onnodeclick(e) {
				this.item = e
			},
			onpopupopened(e) {
				console.log('popupopened');
			},
			onpopupclosed(e) {
				//处理不同步
				this.$nextTick(() => {
					this.pickerData = this.item.value;
					if (!this.item) return
					this.onchange(this.item)
				});
			},
			onpopupclosed2(e) {
				this.pickerData = this.item.value;
				if (!this.item) return
				this.onchange(this.item)
			},
			onchange(e) {
				let array = e.value.split('/');
				switch (array.length) {
					case 3:
						this.formData.storageLocationCode = null;
						this.formData.shelvesCode = null;
						this.formData.areaCode = null;
						this.formData.whCode = array[0];
						break;
					case 4:
						this.formData.storageLocationCode = null;
						this.formData.shelvesCode = null;
						this.formData.areaCode = array[0];
						this.formData.whCode = array[3];
						break;
					case 5:
						this.formData.storageLocationCode = null;
						this.formData.shelvesCode = array[0];
						this.formData.areaCode = array[3];
						this.formData.whCode = array[4];
						break;
					case 6:
						this.formData.storageLocationCode = array[0];
						this.formData.shelvesCode = array[3];
						this.formData.areaCode = array[4];
						this.formData.whCode = array[5];
						break;
					default:
						break;
				}
			},
			//如果已填写拣货仓，则回显到级联选择器上
			getDataPicker(wh, area, shelve, stoLot) {
				if (wh) {
					if (area) {
						if (shelve) {
							if (stoLot) {
								let data = this.dataTree.find(item => item.value.split('/')[0] == wh)
								if (data) {
									let areadata = data.children.find(item => item.value.split('/')[0] == area)
									if (areadata) {
										let shelvedata = areadata.children.find(item => item.value.split('/')[0] ==
											shelve)
										if (shelvedata) {
											let stoLotdata = shelvedata.children.find(item => item.value.split('/')[
												0] == stoLot)
											if (stoLotdata) {
												this.item = stoLotdata;
												this.onpopupclosed2();
											}

										}
									}
								}
							} else {
								//只有仓库，库区和货架
								let data = this.dataTree.find(item => item.value.split('/')[0] == wh)
								if (data) {
									let areadata = data.children.find(item => item.value.split('/')[0] == area)
									if (areadata) {
										let shelvedata = areadata.children.find(item => item.value.split('/')[
												0] ==
											shelve)
										if (shelvedata) {
											this.item = shelvedata;
											this.onpopupclosed2();
										}
									}
								}
							}
						} else {
							//只有仓库和库区
							let data = this.dataTree.find(item => item.value.split('/')[0] == wh)
							if (data) {
								let areadata = data.children.find(item => item.value.split('/')[0] == area)
								if (areadata) {
									this.item = areadata;
									this.onpopupclosed2()
								}
							}
						}
					} else {
						//只有仓库
						let data = this.dataTree.find(item => item.value.split('/')[0] == wh)
						if (data) {
							this.item = data;
							this.onpopupclosed2()
						}
					}
				}
			},

			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				if (type === 'second') {
					return `${value}秒`
				}
				return value
			},
			bindDateChange(e) {
				console.log(e)
				this.formData.pickTime = e.detail.value
			},
			close() {
				this.show = false;
			},
			confirm(e) {
				this.show = false;
				const date = new Date(e.value);
				console.log(date.toLocaleString()); // 使用 toLocaleString() 方法将时间戳转换为可读的日期和时间格式
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			scanBarCode() {
				// if (this.formData.pickCode) {
				let obj = {
					drawTaskCode: this.formData.drawTaskCode,
					pickCode: this.formData.pickCode
				}
				console.log(obj);
				this.$modal.loading('提交中')
				listPick(
					obj
				).then(async res => {
					this.$modal.closeLoading();
					console.log(res);
					if (res.rows.length != 0) {
						// arry = res.rows[0];
						// console.log(arry);
						this.formData = res.rows[0];
						// this.formData.wlBatchNum = res.rows[0].materialBatchNo,
						// this.formData.wlName = res.rows[0].materialName,
						// this.formData.wlCode = res.rows[0].materialCode,
						// this.formData.ckCode = res.rows[0].storageLocationCode,
						// this.formData.yyNum = res.rows[0].originNumber,
						// this.formData.jhNum = res.rows[0].pickNumber,
						this.xyNum = this.formData.originNumber - this.formData.pickNumber
						this.formData.pickTime = this.getDate();
						await this.getPickArea();
						console.log(this.formData.pickTime)
					} else {
						this.$modal.msgError("未检索到该拣货信息！");
					}
				});
				// } else if (!this.formData.drawTaskCode || this.formData.drawTaskCode == "" || this.formData.drawTaskCode ==
				// 	null) {
				// 	this.$modal.msg("请输入领料任务单！");
				// } else if (!this.formData.pickCode || this.formData.pickCode == "" || this.formData.pickCode == null) {
				// 	this.$modal.msg("请输入拣货单！");
				// }
			},
			// 			scanBarCode1(){
			// 				if(!this.formData.pickCode || this.formData.pickCode == "" || this.formData.pickCode == null){
			// 					this.$modal.msgError("请输入拣货单！");
			// 				}
			// },
			scanBarPwo() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.workOrderCode = res.result;
						_this.scanBarPwoCode();
					}
				});
			},
			scanBarPwoCode() {
				if (this.formData.workOrderCode) {
					listPick({
						workOrderCode: this.formData.workOrderCode
					}).then(response => {
						console.log(response);
						if (response.rows.length > 1) {
							this.$modal.msg("该工单检索到的拣货单超过1条，请去电脑端操作！");
						} else if (response.rows.length == 0) {
							this.$modal.msg("该工单未检索到拣货单！");
						} else if (response.rows.length == 1) {
							console.log("success");
							this.formData = response.rows[0];
							this.xyNum = this.formData.originNumber - this.formData.pickNumber;
							this.formData.pickTime = this.getDate();
							this.getPickArea();
							console.log(this.formData.pickTime)
						}
					});
				}
			},
			//领料任务单                
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.drawTaskCode = res.result;
						_this.scanBarCode();
					}
				});
			},
			//拣货单                 
			scanBar4() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.pickCode = res.result;
						_this.scanBarCode();
					}
				});
			},
			submit() {
				const _this = this;
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定拣货该物料吗？',
						success: function(res) {
							if (res.confirm) {
								_this.formData.status = '2';
								console.log(_this.formData);
								_this.$modal.loading('提交中')
								updatePick(_this.formData).then(async res => {
									_this.formData.inStatus = '2'
									updatePick(_this.formData).then(
										async res => {
											_this.$modal.msgSuccess(
												"拣货完成!");
											setTimeout(() => {
												_this.$modal
											.closeLoading();
												_this.$tab
													.switchTab(
														"/pages/work/index"
													);
											}, 500);
										});
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
		}
	}
</script>

<style>
</style>