<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>
					<uni-forms-item label="产品任务单" :labelWidth='90' name="productInTaskCode">
						<uni-combox :candidates="productInTaskCodeList" emptyTips="无" @input="scanBarCode"
							v-model="formData.productInTaskCode"></uni-combox>
					</uni-forms-item>
					<uni-forms-item label="签收员" :labelWidth='90' name="drawBy">
						<uni-easyinput suffixIcon="scan" @iconClick="scanBar1" v-model="formData.drawBy" type="text" />
					</uni-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
						<uni-easyinput v-model="formData.warehouseCode" type="text" />
					</uni-forms-item>
					<uni-forms-item label="到货时间" :labelWidth='90' name="arriveTime">
						<view class="example-body">
							<uni-datetime-picker type="datetime" v-model="formData.arriveTime" />
						</view>
					</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.wmsProductReceiveDetailList.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 :key="index"
							v-for="(item, index) in formData.wmsProductReceiveDetailList"
							@click="(data) => clickDetail(index,data)" :right-options="rightOptions">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="物料编码" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.materialCode'">
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.materialName'">
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.materialBatchNo'">
								<uni-easyinput disabled type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="物料箱号" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.materialLotNo'">
								<uni-easyinput disabled type="number" v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="类型" :labelWidth='90'
								name="'wmsProductReceiveDetailList.'+ 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-forms-item>
							<uni-forms-item label="应收数量" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.theoryNumber'">
								<uni-easyinput disabled type="number" v-model="item.theoryNumber" />
							</uni-forms-item>
							<uni-forms-item label="已收数量" :labelWidth='90' v-if="item.receivedNumber"
								:name="'wmsProductReceiveDetailList.'+ index +'.receivedNumber'">
								<uni-easyinput disabled type="number" v-model="item.receivedNumber" />
							</uni-forms-item>
							<uni-forms-item label="到货数量" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.arriveNumber'">
								<u-number-box inputWidth="120" button-size="36" v-model="item.arriveNumber"
									min="0"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="实收数量" :labelWidth='90'
								:name="'wmsProductReceiveDetailList.'+ index +'.actualNumber'">
								<u-number-box inputWidth="120" button-size="36" v-model="item.actualNumber"
									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>
</template>

<script>
	import {
		addReceive,
		listReceive,
		getReceive,
		listTask,
		getTask,
		getReceiveDetails,
		listReceiveDetail,
		updateReceiveDetail,
	} from "@/api/wms/pdcIn.js";
	import {
		listMaterial
	} from "@/api/wms/request.js";
	export default {
		onLoad: function() {
			// 获取当前时间
			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.endTime
			this.formData.arriveTime = formattedDate;
		},
		mounted() {
			//判断是否已收货
			listReceiveDetail({
				productInTaskDetailId: 846
			}).then(res => {
				console.log(res)
			})
		},
		data() {
			return {
				isReceive: false,
				value: '正常',
				show: false,
				materialLabel: null,
				workOrderCode: null,
				productInTaskCodeList: [],
				formData: {
					productInTaskCode: '',
					drawBy: null,
					warehouseCode: null,
					wmsProductReceiveDetailList: [],
					arriveTime: null,
				},
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					productInTaskCode: {
						rules: [{
							required: true,
							errorMessage: '请输入产品任务单!'
						}]
					},
					actualNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入实收数量!'
						}]
					},
				}
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			deleteDetail(index) {
				this.formData.wmsProductReceiveDetailList.splice(index, 1);
			},
			clickDetail(itemIndex, {
				position,
				index
			}) {
				if (index == 0) {
					this.deleteDetail(itemIndex);
				}
			},
			addMaterialLabel() {
				this.show = true;
			},
			cancelMaterialLabel() {
				this.materialLabel = null;
				this.show = false;
			},
			confirmMaterialLabel(data) {
				data = JSON.parse(data)
				if (data) {
					//判断是否已收货
					listReceiveDetail({
						productInTaskDetailId: data.id
					}).then(res => {
						console.log(res)
						//若已有收货单
						if (res.data.length > 0) {
							let num = 0;
							//统计所有实收数量
							for (var i in res.data) {
								num += res.data[i].actualNumber
							}
							//若所有收货单的实际收货数量与应收数量一致
							if (num == res.data[0].theoryNumber) {
								this.$modal.msg("该条物料明细已完成收货！")
							} else {
								// this.workOrderCode = data.pwoCode
								this.formData.productInTaskCode = data.productInTaskCode
								// this.formData.id
								let obj = {
									materialCode: res.data[0].materialCode,
									materialName: res.data[0].materialName,
									materialBatchNo: res.data[0].materialBatchNo,
									theoryNumber: res.data[0].theoryNumber,
									receivedNumber: num,
									productInTaskDetailId: data.id,
									type: res.data[0].type,
									id: res.data[0].id
								}
								this.formData.wmsProductReceiveDetailList.push(obj);
								this.isReceive = true;
								this.materialLabel = null;
								this.show = false;
							}
						} else {
							// this.workOrderCode = data.pwoCode
							getReceiveDetails({
								productInTaskCode: data.productInTaskCode
							}).then((res) => {
								if (res.details.length > 0) {
									this.formData = res.rcv;
									this.formData.productInTaskCode = data.productInTaskCode
									this.formData.wmsProductReceiveDetailList = []
									this.formData.wmsProductReceiveDetailList.push(res.details
										.find(item =>
											item.productInTaskDetailId == data.id));
									this.isReceive = false;
									this.materialLabel = null;
									this.show = false;
								} else {
									this.$modal.msg("任务单里未查到该条明细！")
								}

							});
							// let obj = {
							// 	materialCode: data.materialCode,
							// 	materialName: data.materialName,
							// 	materialBatchNo: data.materialBatchNo,
							// 	theoryNumber: data.number,
							// 	productInTaskDetailId: data.id,
							// 	type: data.type
							// }
							// this.formData.wmsProductReceiveDetailList.push(obj);

						}
					})
				}
			},
			scanBarMaterialLabel() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.materialLabel = res.result;
						// console.log(materialLabel)
						_this.confirmMaterialLabel(_this.materialLabel);
					}
				});
			},
			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.productInTaskCodeList = [];
				if (this.workOrderCode) {
					listTask({
						workOrderCode: this.workOrderCode
					}).then(async response => {
						for (var i = 0; i < response.rows.length; i++) {
							this.productInTaskCodeList.push(response.rows[i].productInTaskCode);
						}
					});
				}
			},
			selectTypeList() {
				listTask().then(async res => {
					// console.log(res);
					for (var i in res.rows) {
						this.productInTaskCodeList.push(res.rows[i].productInTaskCode);
					}
					// console.log(this.drawTaskCodeList)
				});
			},
			bindDateChange(e) {
				this.formData.arriveTime = e.detail.value
			},
			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.productInTaskCode) {
					let data = {
						productInTaskCode: this.formData.productInTaskCode
					}
					getReceiveDetails(this.formData).then(res => {
						this.formData.wmsProductReceiveDetailList = res.details;
					})
				} else {
					this.$modal.msg("请输入产品任务单！")
				}
			},
			//产品任务单
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.productInTaskCode = res.result;
						_this.scanBarCode();
					}
				});
			},
			//签收员编码
			scanBar1() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.drawBy = 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.wmsProductReceiveDetailList.map(item => {
									item.secondTheoryNumber = item.number;
									item.secondUnitId = item.unitId;
									item.secondArriveNumber = item.arriveNumber;
									item.secondActualNumber = item.actualNumber;
									item.secondActualUnitId = item.unitId;
									return item
								})
								if (_this.isReceive == false) {
									//判断实收数量是否超出应收数量	
									let isNumOver = false;
									for (var i in _this.formData.wmsProductReceiveDetailList) {
										if (_this.formData.wmsProductReceiveDetailList[i]
											.actualNumber > _this.formData.wmsProductReceiveDetailList[
												i].theoryNumber) {
											_this.$modal.msg("实收数量超出应收数量，请检查！");
											isNumOver = true;
										}
									}
									if (isNumOver == false) {
										_this.$modal.loading('提交中')
										addReceive(_this.formData).then(async res => {
											_this.$modal.msgSuccess("收货成功!");
											_this.$modal.closeLoading();
											setTimeout(() => {
												_this.$tab.switchTab(
													"/pages/work/index");
											}, 500);
										});
									}
								} else {
									let isNumOver = false;
									for (var i in _this.formData.wmsProductReceiveDetailList) {
										if (_this.formData.wmsProductReceiveDetailList[i]
											.actualNumber > (_this.formData
												.wmsProductReceiveDetailList[i].theoryNumber - _this
												.formData.wmsProductReceiveDetailList[i].receivedNumber
											)) {
											_this.$modal.msg("实收数量超出应收数量，请检查！");
											isNumOver = true;
										}
									}
									if (isNumOver == false) {
										console.log(_this.formData.wmsProductReceiveDetailList)
										_this.formData.wmsProductReceiveDetailList[0].actualNumber +=
											_this.formData.wmsProductReceiveDetailList[0]
											.receivedNumber;
										_this.formData.wmsProductReceiveDetailList[0].arriveNumber +=
											_this.formData.wmsProductReceiveDetailList[0]
											.receivedNumber;
										_this.$modal.loading('提交中')
										updateReceiveDetail(_this.formData.wmsProductReceiveDetailList[
												0])
											.then(async res => {
												_this.$modal.msgSuccess("收货成功!");
												_this.$modal.closeLoading();
												setTimeout(() => {
													_this.$tab.switchTab(
														"/pages/work/index");
												}, 500);
											});
									}
								}

							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
		}
	}
</script>

<style>
</style>