<template>
	<view>
		<uni-collapse>
			<uni-forms ref="form" :modelValue="formData" :rules="rules">
				<!-- <uni-collapse-item title="采购收货单" :open="true"> -->
				<uni-forms-item v-if="value=='正常' && !formData.u9SourceBillCode" label="采购任务单" :labelWidth='90'
					name="purchaseTaskCode">
					<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarTaskCode"
						v-model="formData.purchaseTaskCode" type="text" />
				</uni-forms-item>
				<uni-forms-item v-if="value=='扫物料标签'" label="采购收货单" :labelWidth='90' name="purchaseReceiveCode">
					<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarTaskCode"
						v-model="formData.purchaseReceiveCode" type="text" />
				</uni-forms-item>
				<uni-forms-item v-if="!formData.u9SourceBillCode" label="采购订单号" :labelWidth='90' name="purchaseCode">
					<uni-combox :candidates="purchaseCodeList" emptyTips="无" @input="scanBarPurchaseCode"
						v-model="formData.purchaseCode"></uni-combox>
				</uni-forms-item>
				<uni-forms-item v-if="formData.supplierCode" label="供应商代码" :labelWidth='90' name="supplierCode">
					<uni-easyinput v-model="formData.supplierCode" type="text" disabled />
				</uni-forms-item>
				<uni-forms-item v-if="formData.u9SourceBillCode" label="采购订单号" :labelWidth='90' name="u9SourceBillCode">
					<uni-easyinput v-model="formData.u9SourceBillCode" type="text" disabled />
				</uni-forms-item>
				<uni-forms-item v-if="formData.remark" label="备注" :labelWidth='90' name="remark">
					<uni-easyinput v-model="formData.remark" type="text" disabled />
				</uni-forms-item>
				<uni-forms-item label="仓库编码" :labelWidth='90' name="warehouseCode">
					<uni-easyinput type="text" suffixIcon="scan" @iconClick="scanBarwarehouseCode"
						v-model="formData.warehouseCode" />
					<uni-data-select v-model="formData.warehouseCode" :localdata="wcList"
						style="margin-top: 10px;"></uni-data-select>
				</uni-forms-item>
				<!-- <uni-forms-item label="收货方式" :labelWidth='90' name="receiveWay"> -->
				<u-radio-group v-model="value" iconPlacement="left" style="font-size: 14px;margin-bottom: 20px;">收货方式
					<u-radio label="正常" name="正常" style="margin-left: 40px;"></u-radio>
					<u-radio label="扫物料标签" name="扫物料标签" style="margin-left: 10px;"></u-radio>
				</u-radio-group>
				<!-- </uni-forms-item> -->
				<button size="mini" v-if="value=='扫物料标签'" type="primary"
					style="text-align: center;margin-left: 30%;font-size: 18px;margin-top: 15px;"
					@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> -->
				<view v-for="(item, index) in formData.wmsPurchaseReceiveDetailList" :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' v-if="item.remark">
						<uni-easyinput disabled type="text" v-model="item.remark" />
					</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'>
						<uni-easyinput disabled type="number" v-model="item.rcvNum" />
					</uni-forms-item>
					<uni-forms-item label="入库数量" :labelWidth='90'>
						<uni-easyinput disabled type="number" v-model="item.quaInNum" />
					</uni-forms-item>
					<uni-forms-item label="退回数量" :labelWidth='90'>
						<uni-easyinput disabled type="number" v-model="item.backNum" />
					</uni-forms-item>
					<uni-forms-item label="到货数量" :labelWidth='90'>
						<uni-easyinput type="number" v-model="item.arriveNumber" />
						<!-- 						<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'>
						<uni-row>
							<uni-col :span="12">
								<second-number-change-to-convert :materialCode="item.materialCode"
									:secondNumber.sync="item.secondActualNumber" :secondUnitId="item.secondActualUnitId"
									:number.sync="item.actualNumber"
									:unitId="item.unitId"></second-number-change-to-convert>
							</uni-col>
							<uni-col :span="12">
								<select-unit-convertible v-model="item.secondActualUnitId"
									:materialCode="item.materialCode" :secondNumber.sync="item.secondActualNumber"
									:number="item.actualNumber" :unitId="item.unitId"></select-unit-convertible>
							</uni-col>
						</uni-row>
					</uni-forms-item>
				</view>
				<!-- </uni-swipe-action-item> -->
				<!-- </uni-swipe-action> -->
				<!-- </uni-collapse-item> -->
			</uni-forms>
			<u-button type="primary" @click="submit">提交</u-button>
		</uni-collapse>
	</view>
</template>

<script>
	import {
		addReceive,
		getTask,
		listTask,
		getDetail,
		updateReceive,
		updateReceiveDetail,
		getDetailByPoCode,
		getReceiveDetailJoin,
		getDetailListsBySRM,
		listSupplier
	} from "@/api/wms/purchase.js";
	import {
		values
	} from "lodash";
	import {
		listWarehouse
	} from "@/api/wms/warehouse";
	import selectUnitConvertible from "@/components/selectUnitConvertible/index.vue";
	import SecondNumberChangeToConvert from "@/components/SecondNumberChangeToConvert/index.vue";
	export default {
		mounted() {
			listTask().then((response) => {
				for (var i = 0; i < response.rows.length; i++) {
					this.purchaseCodeList.push(response.rows[i].purchaseCode);
				}
			});
			listWarehouse().then((res) => {
				this.wcList = res.rows.map(item => {
					let obj = {
						text: item.warehouseName,
						value: item.warehouseCode
					}
					return obj
				})
			})

		},
		components: {
			selectUnitConvertible,
			SecondNumberChangeToConvert
		},
		data() {
			return {
				wcList: [],
				isSupplierCode: false,
				isReceived: false,
				purchaseCodeList: [],
				value: '正常',
				show: false,
				materialLabel: null,
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				formData: {
					purchaseTaskCode: null,
					purchaseReceiveCode: null,
					wmsPurchaseReceiveDetailList: [],
					warehouseCode: null,
					//任务单状态=1=‘新建’
					status: '1'
				},
				rules: {
					// purchaseTaskCode: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入采购任务单!'
					// 	}]
					// },
					warehouseCode: {
						rules: [{
							required: true,
							errorMessage: '请输入仓库编码!'
						}]
					},
				}
			}
		},
		methods: {
			scanBarPurchaseCode() {
				if (this.formData.purchaseCode) {
					getDetailByPoCode(this.formData.purchaseCode).then(res => {
						console.log(res)
						let purchaseCode = this.formData.purchaseCode
						this.formData = res.receiveBill
						this.formData.purchaseCode = purchaseCode
					})
				} else {
					this.$modal.msg("请输入采购订单号！");
				}
			},
			deleteDetail(index) {
				this.formData.wmsPurchaseReceiveDetailList.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) {
				//判断是否供应商扫码
				if (data.includes('@')) {
					this.isSupplierCode = true;
					let array = data.split('@');
					let new_supplierCode = array[0];
					let new_u9SourceBillCode = array[3].split('|')[0];
					let new_erpDocCode1 = array[4].split('|')[0];
					let new_erpDocLineKey1 = array[4].split('|')[1];
					let lotNo = array[4].split('|')[2];
					let supplierCode = null;
					console.log(new_erpDocLineKey1, lotNo);
					getDetailListsBySRM({
						u9SourceBillCode: new_u9SourceBillCode,
						erpDocCode1: new_erpDocCode1,
						erpDocLineKey1: new_erpDocLineKey1
					}).then(res => {
						console.log(res)
						//查供应商编码
						listSupplier({
							remark: new_supplierCode
						}).then(res => {
							if (res.rows.length > 0) {
								supplierCode = res.rows[0].supplierCode
							}
						})
						//判断有没有进行收货
						//未收货
						if (res.receiveDetailList.length == 0) {
							//判断是总码还是外箱，外箱码是多加一个箱数量
							if (array.length < 7) {
								//总码
								let obj = {
									materialCode: array[1],
									materialBatchNo: array[2],
									theoryNumber: Number(array[5]),
									arriveNumber: Number(array[5]),
									actualNumber: Number(array[5]),
									//ASN行号
									erpDocLineKey1: new_erpDocLineKey1,
								}
								//供应商代码
								this.formData.supplierCode = supplierCode;
								//采购订单号
								this.formData.u9SourceBillCode = new_u9SourceBillCode;
								//ASN单号
								this.formData.erpDocCode1 = new_erpDocCode1;
								this.formData.wmsPurchaseReceiveDetailList.push(obj);
							} else {
								//外箱，会出现多次扫码的情况
								//判断当前单据下是否已扫描添加过明细
								if (this.formData.wmsPurchaseReceiveDetailList.length > 0) {
									//有明细
									//判断是否为同一个主表下的同一物料
									if (this.formData.u9SourceBillCode == new_u9SourceBillCode && this.formData
										.erpDocCode1 == new_erpDocCode1 && this.formData
										.wmsPurchaseReceiveDetailList[0].erpDocLineKey1 == new_erpDocLineKey1) {
										//判断箱号有无重复
										if (this.formData.wmsPurchaseReceiveDetailList.find(item => item.remark
												.includes(lotNo))) {
											this.$modal.msg("该条物料已添加！")
										} else {
											this.formData.wmsPurchaseReceiveDetailList[0].remark = this.formData
												.wmsPurchaseReceiveDetailList[0].remark + ',' + lotNo
											this.formData.wmsPurchaseReceiveDetailList[0].arriveNumber += Number(
												array[
													5]);
											this.formData.wmsPurchaseReceiveDetailList[0].actualNumber += Number(
												array[
													5]);
										}
									} else {
										this.$modal.msg("该条物料与现有明细不在同一ASN行号下！")
									}
								} else {
									//没明细
									let obj = {
										materialCode: array[1],
										materialBatchNo: array[2],
										theoryNumber: Number(array[6]),
										arriveNumber: Number(array[5]),
										actualNumber: Number(array[5]),
										//ASN行号
										erpDocLineKey1: array[4].split('|')[1],
										remark: lotNo
									}
									//供应商代码
									this.formData.supplierCode = supplierCode;
									//采购订单号
									this.formData.u9SourceBillCode = new_u9SourceBillCode;
									//ASN单号
									this.formData.erpDocCode1 = new_erpDocCode1;
									this.formData.wmsPurchaseReceiveDetailList.push(obj);
								}
							}
						} else {
							//已收货存在收货明细
							this.isReceived = true;
							//判断收货有无完成
							if (res.receiveDetailList[0].actualNumber == res.receiveDetailList[0]
								.theoryNumber) {
								this.$modal.msg("该条物料已完成收货！")
							} else {
								//判断当前表单是否已有明细
								if (this.formData.wmsPurchaseReceiveDetailList.length > 0) {
									//判断是否为同一个主表下的同一物料
									if (this.formData.u9SourceBillCode == new_u9SourceBillCode && this.formData
										.erpDocCode1 == new_erpDocCode1 && this.formData
										.wmsPurchaseReceiveDetailList[0].erpDocLineKey1 == new_erpDocLineKey1) {
										//判断箱号有无重复
										if (this.formData.wmsPurchaseReceiveDetailList.find(item => item.remark
												.includes(lotNo))) {
											this.$modal.msg("该条物料已添加！")
										} else {
											this.formData.wmsPurchaseReceiveDetailList[0].remark = this.formData
												.wmsPurchaseReceiveDetailList[0].remark + ',' + lotNo
											this.formData.wmsPurchaseReceiveDetailList[0].arriveNumber += Number(
												array[
													5]);
											this.formData.wmsPurchaseReceiveDetailList[0].actualNumber += Number(
												array[
													5]);
										}
									} else {
										this.$modal.msg("该条物料与现有明细不在同一ASN单号下！")
									}
								} else {
									//判断箱号有无重复
									if (res.receiveDetailList.find(item => item.remark
											.includes(lotNo))) {
										this.$modal.msg("该条物料已添加！")
									} else {
										//供应商代码
										this.formData.supplierCode = supplierCode;
										//采购订单号
										this.formData.u9SourceBillCode = new_u9SourceBillCode;
										//ASN单号
										this.formData.erpDocCode1 = new_erpDocCode1;
										res.receiveDetailList[0].remark = res.receiveDetailList[0].remark + ',' +
											lotNo
										res.receiveDetailList[0].arriveNumber += Number(array[5]);
										res.receiveDetailList[0].actualNumber += Number(array[5]);
										this.formData.wmsPurchaseReceiveDetailList = res.receiveDetailList;
									}

								}
							}
						}
					})
					this.materialLabel = null;
					this.show = false;
				} else {
					data = JSON.parse(data)
					if (data) {
						//判断后续输入的物料明细是否与第一条绑定的收货单一致
						if (this.formData.purchaseReceiveCode) {
							//添加过物料标签，加入判断
							getReceiveDetailJoin(data.id).then(res => {
								if (res.data) {
									if (res.data.purchaseReceiveCode !== this.formData
										.purchaseReceiveCode) {
										this.$modal.msg("与上一条输入的物料标签编码的收货单不一致！")
									} else {
										//若与上一条输入的物料标签编码的收货单一致，则进行物料id判断
										let a = this.formData.wmsPurchaseReceiveDetailList.find(item => item.id ==
											data
											.id)
										//id添加过
										if (typeof(this.formData.wmsPurchaseReceiveDetailList.find(item => item
												.id ==
												data
												.id)) ===
											'object') {
											this.$modal.msg("该条物料标签已添加！")
										} else {
											this.formData.wmsPurchaseReceiveDetailList.push(res.data);
											this.materialLabel = null;
											this.show = false;
										}
									}
								} else {
									this.$modal.msg("未查询到该明细！")
								}
							})
						} else {
							//没有添加过物料标签，则跳过判断直接添加
							getReceiveDetailJoin(data.id).then(res => {
								if (res.data) {
									this.formData.purchaseReceiveCode = res.data.purchaseReceiveCode
									this.formData.wmsPurchaseReceiveDetailList.push(res.data);
									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);
					}
				});
			},
			//采购任务单
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.purchaseTaskCode = res.result;
						_this.scanBarTaskCode(res.result);
					}
				});
			},
			scanBarTaskCode(code) {
				// let obj = {
				//         purchaseTaskCode: this.formData.purchaseTaskCode,
				//       };
				//       listReceive(obj).then((response) => {
				//         this.taskReceiveList = response.rows;
				//       });
				getDetail(this.formData).then((res) => {
					// console.log(res);
					this.formData = res.receiveBill;
					// this.formData.wmsPurchaseReceiveDetailList = res.receiveBill.wmsPurchaseReceiveDetailList;
				});
				// getDetail(this.formData).then((res) => {
				// 	this.formData.wmsPurchaseReceiveDetailList = res.details;
				// });
			},
			//仓库编码
			scanBarscanBarwarehouseCode() {
				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) {
								if (_this.value == '正常' || _this.value == '扫物料标签' && _this
									.isSupplierCode && !_this.isReceived) {
									console.log(_this.formData)
									_this.$modal.loading('提交中')
									addReceive(_this.formData).then(async res => {
										_this.$modal.msgSuccess("收货成功!");
										setTimeout(() => {
											_this.$modal.closeLoading();
											_this.$tab.switchTab(
												"/pages/work/index"
											);
										}, 500);
									});
								} else if (_this.value == '扫物料标签' || _this.value ==
									'扫物料标签' &&
									_this
									.isSupplierCode && _this.isReceived) {
									console.log(2)
									_this.$modal.loading('提交中')
									updateReceiveDetail(_this.formData
											.wmsPurchaseReceiveDetailList)
										.then(async res => {
											_this.$modal.msgSuccess("收货成功!");
											setTimeout(() => {
												_this.$modal.msgSuccess("收货成功!");
												_this.$tab.switchTab(
													"/pages/work/index"
												);
											}, 500);
										});
								}

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

<style>
</style>