<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="backTaskCode">
						<uni-combox :candidates="backTaskCodeList" emptyTips="无" @input="scanBarCode"
							v-model="formData.backTaskCode"></uni-combox>
					</uni-forms-item>
					<uni-forms-item label="生产退料任务明细单" :labelWidth='90' name="backTaskDetailCode">
						<uni-easyinput v-model="formData.backTaskDetailCode" type="text" />
					</uni-forms-item>
					<uni-forms-item label="生产退料收货单" :labelWidth='90' name="backReceiveCode">
						<uni-easyinput v-model="formData.backReceiveCode" 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-forms-item>
					<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
						<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarwarehouseCode"
							v-model="formData.warehouseCode" />
					</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.wmsBackReceiveDetailList.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.wmsBackReceiveDetailList" :key="index"
							@click="(data) => clickDetail(index,data)" :right-options="rightOptions">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="物料编码" :labelWidth='90'>
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'>
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'>
								<uni-easyinput disabled type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="物料箱号" :labelWidth='90'>
								<uni-easyinput disabled type="text" v-model="item.materialLotNo" />
							</uni-forms-item>
							<uni-forms-item label="退料原因" :labelWidth='90'>
								<uni-easyinput disabled type="text" v-model="item.reason" />
							</uni-forms-item>
							<uni-forms-item label="应收数量" :labelWidth='90'>
								<uni-easyinput disabled type="number" v-model="item.theoryNumber" />
							</uni-forms-item>
							<uni-forms-item label="已收数量" :labelWidth='90' v-if="item.receivedNumber"
								:name="'wmsBackReceiveDetailList.'+ index +'.receivedNumber'">
								<uni-easyinput disabled type="number" v-model="item.receivedNumber" />
							</uni-forms-item>
							<uni-forms-item label="到货数量" :labelWidth='90'>
								<u-number-box inputWidth="120" button-size="36" v-model="item.arriveNumber"
									:max="item.theoryNumber" min="0"></u-number-box>
							</uni-forms-item>
							<uni-forms-item label="实收数量" :labelWidth='90'>
								<u-number-box inputWidth="120" button-size="36" v-model="item.actualNumber"
									:max="item.theoryNumber" 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 {
		listReceive,
		getReceive,
		delReceive,
		addReceive,
		updateReceive,
		exportReceive,
		getRcvByTask,
		listReceiveDetail,
		updateReceiveDetail,
		listDetail
	} from "@/api/wms/pdcBack/receive";
	import {
		listTask,
		getTask,
		delTask,
		addTask,
		updateTask,
		exportTask,
		mergePrintDetailPdfs,
	} from "@/api/wms/pdcBack/task";
	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() {},
		data() {
			return {
				isSupplierCode: false,
				isReceive: false,
				backTaskCodeList: [],
				value: '正常',
				show: false,
				materialLabel: null,
				workOrderCode: null,
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				formData: {
					backTaskCode: '',
					backReceiveCode: null,
					backTaskDetailCode: null,
					wmsBackReceiveDetailList: [],
					arriveTime: null,
					warehouseCode: null,
					//任务单状态=1=‘新建’
					status: '1'
				},
				rules: {
					// backTaskCode: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入生产退料任务单!'
					// 	}]
					// },
				}
			}
		},
		methods: {
			deleteDetail(index) {
				this.formData.wmsBackReceiveDetailList.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) {
					//判断是否已收货
					console.log(data)
					listReceiveDetail({
						backTaskDetailCode: data.backTaskDetailCode
					}).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.backTaskCode = res.data[0].backTaskCode
								this.formData.backTaskDetailCode = data.backTaskDetailCode
								this.formData.backReceiveCode = res.data[0].backReceiveCode
								this.formData.deptCode = res.data[0].deptCode
								this.formData.warehouseCode = res.data[0].warehouseCode

								// 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,
									unitId: res.data[0].unitId,
									receivedNumber: num,
									backTaskDetailCode: data.backTaskDetailCode,
									type: res.data[0].type,
									id: res.data[0].id
								}
								this.formData.wmsBackReceiveDetailList.push(obj);
								this.isReceive = true;
								this.materialLabel = null;
								this.show = false;
							}
						} else {
							// this.workOrderCode = data.pwoCode
							listDetail({
								backTaskDetailCode: data.backTaskDetailCode
							}).then((res) => {
								console.log(res)
								if (res.rows.length > 0) {
									this.formData.backTaskDetailCode = data.backTaskDetailCode
									this.formData.wmsBackReceiveDetailList = []
									let obj = res.rows[0]
									obj.theoryNumber = obj.number;
									obj.unitId = obj.unitId;
									obj.id = null
									this.formData.backTaskCode = obj.backTaskCode
									this.formData.deptCode = obj.deptCode
									this.formData.warehouseCode = obj.warehouseCode
									this.formData.wmsBackReceiveDetailList.push(obj);
									this.isReceive = false;
									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);
					}
				});
			},
			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.backTaskCodeList = [];
				if (this.workOrderCode) {
					listTask({
						workOrderCode: this.workOrderCode
					}).then(async response => {
						this.backTaskCodeList = response.rows.map(item => {
							return item.backTaskCode
						});
					});
				}
			},
			selectTypeList() {
				listTask().then(async res => {
					this.backTaskCodeList = res.rows.map(item => {
						return item.backTaskCode
					});
				})
			},
			scanBarCode() {
				if (this.formData.backTaskCode) {
					// let data = {
					// 	backTaskDetailCode: this.formData.backTaskDetailCode
					// }
					getRcvByTask(this.formData).then(res => {
						this.formData.wmsBackReceiveDetailList = res.wmsBackReceive.wmsBackReceiveDetailList;
					})
				} else {
					this.$modal.msg("请输入生产退料任务单！")
				}
			},
			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}`;
			},
			//仓库编码
			scanBarwarehouseCode() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.warehouseCode = res.result;
					}
				});
			},
			//签收员编码
			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) {
								console.log(_this.formData)
								_this.formData.wmsBackReceiveDetailList.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.wmsBackReceiveDetailList) {
										if (_this.formData.wmsBackReceiveDetailList[i]
											.actualNumber > _this.formData.wmsBackReceiveDetailList[
												i].theoryNumber) {
											_this.$modal.msg("实收数量超出应收数量，请检查！");
											isNumOver = true;
										}
									}
									if (isNumOver == false) {
										_this.$modal.loading('提交中')

										addReceive(_this.formData).then(async res => {
											_this.$modal.closeLoading();
											_this.$modal.msgSuccess("收货成功!");
											setTimeout(() => {
												_this.$tab.switchTab(
													"/pages/work/index");
											}, 500);
										});
									}
								} else {
									console.log(1)
									let isNumOver = false;
									for (var i in _this.formData.wmsBackReceiveDetailList) {
										if (_this.formData.wmsBackReceiveDetailList[i]
											.actualNumber > (_this.formData
												.wmsBackReceiveDetailList[i].theoryNumber - _this
												.formData.wmsBackReceiveDetailList[i].receivedNumber
											)) {
											_this.$modal.msg("实收数量超出应收数量，请检查！");
											isNumOver = true;
										}
									}
									if (isNumOver == false) {
										console.log(_this.formData.wmsBackReceiveDetailList)
										_this.formData.wmsBackReceiveDetailList[0].actualNumber +=
											_this.formData.wmsBackReceiveDetailList[0]
											.receivedNumber;
										_this.formData.wmsBackReceiveDetailList[0].arriveNumber +=
											_this.formData.wmsBackReceiveDetailList[0]
											.receivedNumber;
										_this.$modal.loading('提交中')
										updateReceiveDetail(_this.formData.wmsBackReceiveDetailList[
												0])
											.then(async res => {
												_this.$modal.closeLoading();
												_this.$modal.msgSuccess("收货成功!");
												setTimeout(() => {
													_this.$tab.switchTab(
														"/pages/work/index");
												}, 500);
											});
									}
								}
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				});
			},
		}
	}
</script>

<style>
</style>