<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="purchaseReceiveCode">
					<uni-easyinput suffixIcon="scan" @iconClick="scanBar" @confirm="scanBarCode"
						v-model="formData.purchaseReceiveCode" type="text" />
				</uni-forms-item>
				<uni-forms-item label="质检单" :labelWidth='90' name="purchaseQualityCode"
					v-show="formData.purchaseQualityCode">
					<uni-easyinput v-model="formData.purchaseQualityCode" type="text" disabled />
				</uni-forms-item>
				<uni-forms-item label="附件" :labelWidth='90' name="enclosure">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10"></u-upload>
				</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.wmsPurchaseQualityDetailList.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 :rightOptions="rightOptions" :key="index"
							v-for="(item, index) in formData.wmsPurchaseQualityDetailList"
							@click="(data) => clickDetail(index,data)">
							<uni-badge :text="index+1" type="primary"></uni-badge>
							<uni-forms-item label="物料编码" :labelWidth='90'
								:name="'wmsPurchaseQualityDetailList.'+ index +'.materialCode'">
								<uni-easyinput type="text" disabled v-model="item.materialCode"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料名称" :labelWidth='90'
								:name="'wmsPurchaseQualityDetailList.'+ index +'.materialName'">
								<uni-easyinput type="text" disabled v-model="item.materialName"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item label="物料批号" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'.materialBatchNo'">
								<uni-easyinput disabled type="text" v-model="item.materialBatchNo" />
							</uni-forms-item>
							<uni-forms-item label="实收数量" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'.secondActualNumber'">
								<uni-easyinput disabled type="number" v-model="item.secondActualNumber" />
							</uni-forms-item>
							<uni-forms-item label="质检数量" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'secondNumber'">
								<second-number-change-to-convert :materialCode="item.materialCode"
									:secondNumber.sync="item.secondNumber" :secondUnitId="item.secondUnitId"
									:number.sync="item.number" :unitId="item.unitId"></second-number-change-to-convert>
								<!-- 								<u-number-box inputWidth="120" button-size="36" v-model="item.number" min="0"
									@change="getBackNumber(index)"></u-number-box> -->
								<!-- 								<uni-easyinput type="number" v-model="item.number"
									@change="(data) => getBackNumber(index,data)" /> -->
							</uni-forms-item>
							<uni-forms-item label="合格数量" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList'+ index +'.secondPassNumber'">
								<second-number-change-to-convert :materialCode="item.materialCode"
									:secondNumber.sync="item.secondPassNumber" :secondUnitId="item.secondUnitId"
									:number.sync="item.passNumber"
									:unitId="item.unitId"></second-number-change-to-convert>
								<!-- <u-number-box inputWidth="120" button-size="36" v-model="item.passNumber" min="0"
									@change="getBackNumber(index)"></u-number-box> -->
							</uni-forms-item>
							<uni-forms-item label="应入数量" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'.secondInNumber'">
								<second-number-change-to-convert :materialCode="item.materialCode"
									:secondNumber.sync="item.secondInNumber" :secondUnitId="item.secondUnitId"
									:number.sync="item.inNumber" :unitId="item.unitId"
									@change="(data) => getBackNumber(item,data)"></second-number-change-to-convert>
								<!-- 								<u-number-box inputWidth="120" button-size="36" v-model="item.secondInNumber" min="0"
									@change="(data) => getBackNumber(index,data)"
									:max="item.actualNumber"></u-number-box> -->
								<!-- <uni-row style="margin-top: 10px;">
									<uni-col :span="12">
										<button size="mini" type="primary" style="font-size: 16px;"
											@click="item.inNumber = item.actualNumber">全部入库</button>
									</uni-col>
									<uni-col :span="12">
										<button size="mini" type="primary" style="font-size: 16px;"
											@click="item.inNumber = 0">全部退回</button>
									</uni-col>
								</uni-row> -->
							</uni-forms-item>
							<uni-forms-item label="退回数量" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'.backNumber'">
								<uni-easyinput disabled type="number" v-model="item.backNumber" />
							</uni-forms-item>
							<uni-forms-item label="不良原因" :labelWidth='90'
								name="'wmsPurchaseQualityDetailList.'+ index +'.failReason'">
								<uni-easyinput type="textarea" v-model="item.failReason" />
							</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 {
		uploadImage,
		getStandardList,
		addQualityHistoryList,
		listQualityHistory,
		updateQualityHistory
	} from "@/api/qc/qc.js";
	import {
		addReceive,
		listReceive,
		listQuality,
		getReceive,
		addQuality,
		updateQuality,
		getReceiveDetail,
		getQualityDetail,
		getQualityReceiveDetail,
		getDetailListsBySRM
	} from "@/api/wms/purchase.js";
	import {
		listMaterial
	} from "@/api/wms/request.js";
	import SecondNumberChangeToConvert from "@/components/SecondNumberChangeToConvert/index.vue";
	export default {
		mounted() {},
		data() {
			return {
				isSupplierCode: false,
				isQualited: false,
				value: '正常',
				show: false,
				materialLabel: null,
				fileList1: [],
				formData: {
					purchaseReceiveCode: null,
					purchaseQualityCode: null,
					wmsPurchaseQualityDetailList: []
				},
				rightOptions: [{
					text: '删除',
					style: {
						backgroundColor: '#ff2a17'
					}
				}, ],
				rules: {
					passNumber: {
						rules: [{
							required: true,
							errorMessage: '请输入质检数量!'
						}]
					},
					purchaseReceiveCode: {
						rules: [{
							required: true,
							errorMessage: '请输入采购收货单!'
						}]
					},
				},
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						style: 'dashed',
						radius: 2
					}
				},
			}
		},
		components: {
			SecondNumberChangeToConvert
		},
		methods: {
			//获取退回数量
			getBackNumber(item, e) {
				if (e > item.actualNumber) {
					this.$message.error("退料数量不能大于实收数量")
				}
				item.backNumber = item.secondActualNumber - e
			},
			// getBackNumber(index, data) {
			// 	if (data) {
			// 		this.formData.wmsPurchaseQualityDetailList[index].backNumber = this.formData
			// 			.wmsPurchaseQualityDetailList[
			// 				index]
			// 			.actualNumber - data.value

			// 	} else {
			// 		this.formData.wmsPurchaseQualityDetailList[index].backNumber = this.formData
			// 			.wmsPurchaseQualityDetailList[
			// 				index]
			// 			.actualNumber - this.formData
			// 			.wmsPurchaseQualityDetailList[
			// 				index]
			// 			.inNumber
			// 	}

			// },
			deleteDetail(index) {
				this.formData.wmsPurchaseQualityDetailList.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];
					getDetailListsBySRM({
						u9SourceBillCode: new_u9SourceBillCode,
						erpDocCode1: new_erpDocCode1,
						erpDocLineKey1: new_erpDocLineKey1
					}).then(res => {
						console.log(res)
						//判断有没有质检(先查质检-再查收货)
						if (res.qualityList.length == 0) {
							//没有质检
							//判断有没有收货
							// if (res.receiveDetailList.length == 0) {
							// 	this.$modal.msg("该条物料还未收货！")
							// } else {
							// 	//判断有没有完成收货
							// 	if (res.receiveDetailList[0].theoryNumber == res.receiveDetailList[0]
							// 		.actualNumber) {
							// 		getQualityReceiveDetail({
							// 			purchaseReceiveCode: res.receiveDetailList[0].purchaseReceiveCode,
							// 			status: '1'
							// 		}).then((res) => {
							// 			console.log(res);
							// 			this.formData = res.qualityBill;
							// 			this.formData.purchaseQualityDetailList = res.qualityBill
							// 				.wmsPurchaseQualityDetailList;
							// 		});
							// 	} else {
							this.$modal.msg("该条物料还未完成收货！")
							// 	}
							// }
						} else {
							this.isQualited = true;
							//判断检验有无完成
							if (res.qualityList[0].status == 3) {
								console.log(1)
								this.$modal.msg("该条物料已完成检验！")
							} else {
								this.formData = res.qualityList[0];
								this.formData.wmsPurchaseQualityDetailList = res.qualityList[0]
									.purchaseQualityDetailList
							}
						}
					})
					this.materialLabel = null;
					this.show = false;
				} else {
					data = JSON.parse(data)
					if (data) {
						getQualityDetail({
							purchaseReceiveDetailId: data.id
						}).then(res => {
							console.log(res.data)
							//判断有没有质检
							if (res.data.length > 0) {
								console.log(1)
								this.formData.purchaseReceiveCode = res.data[0].purchaseReceiveCode;
								this.formData.purchaseQualityCode = res.data[0].purchaseQualityCode;
								this.formData.supplierCode = res.data[0].supplierCode;
								this.formData.supplierName = res.data[0].supplierName;
								//代入主表id
								this.formData.id = res.data[0].purchaseQualityId;
								this.formData.wmsPurchaseQualityDetailList.push(res.data[0]);
								this.materialLabel = null;
								this.show = false;
								// this.$modal.msg("该条物料已质检！");
							} else {
								console.log(2)
								getReceiveDetail(data.id).then(res => {
									console.log(res)
									//判断有没有收货
									if (res.data.actualNumber != null) {
										console.log(res.data)
										let obj = {
											materialCode: res.data.materialCode,
											materialName: res.data.materialName,
											materialBatchNo: res.data.materialBatchNo,
											actualNumber: res.data.actualNumber,
											number: res.data.number,
											purchaseReceiveDetailId: data.id,
											passNumber: 0,
											unitId: res.data.unitId,
											secondNumber: res.data.secondActualNumber,
											secondUnitId: res.data.secondActualUnitId,
											secondInNumber: res.data.secondInNumber,
										}
										this.formData.supplierCode = res.data.supplierCode;
										this.formData.supplierName = res.data.supplierName;
										this.formData.purchaseReceiveCode = res.data.purchaseReceiveCode;
										this.formData.wmsPurchaseQualityDetailList.push(obj);
										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);
					}
				});
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(event)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					// console.log(item)
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uploadImage({
						filePath: url
					}).then(response => {
						uni.showToast({
							title: "上传成功",
							icon: 'success'
						});
						console.log(response)
						resolve(response.fileName)
					});
				})
			},

			reset(code) {
				this.formData = {
					purchaseReceiveCode: code,
					wmsPurchaseQualityDetailList: [],
				};
			},
			scanBarCode(code) {
				// if (code){
				// 	this.reset(code);
				// }
				if (code) {
					let q = {
						purchaseReceiveCode: code
					}
					listReceive(q).then(async res => {
						console.log(res);
						if (res.rows != null && res.rows.length > 0) {
							let did = res.rows[0].id
							getReceive(did).then(async res => {
								for (let i in res.data
										.wmsPurchaseReceiveDetailList) {
									let obj = {};
									obj.materialBatchNo = res.data
										.wmsPurchaseReceiveDetailList[i]
										.materialBatchNo;
									obj.materialCode = res.data
										.wmsPurchaseReceiveDetailList[i]
										.materialCode;
									obj.materialName = res.data
										.wmsPurchaseReceiveDetailList[i]
										.materialName;
									obj.actualNumber = res.data
										.wmsPurchaseReceiveDetailList[i]
										.actualNumber;
									obj.number = res.data
										.wmsPurchaseReceiveDetailList[i]
										.actualNumber
									this.formData.wmsPurchaseQualityDetailList.push(
										obj);
								}
							});
						} else {
							this.$modal.msg("未检索到收货明细！");
						}

					});
				}
			},
			//采购任务单
			scanBar() {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.formData.purchaseReceiveCode = res.result;
						_this.scanBarCode(_this.formData.purchaseReceiveCode);
					}
				});
			},
			submit() {
				const _this = this;
				_this.$refs.form.validate().then(res => {
					uni.showModal({
						title: '提示',
						content: '您确定完成该质检吗？',
						success: function(res) {
							if (res.confirm) {
								console.log(_this.formData)
								if (_this.formData.id != null) {
									console.log(1)
									console.log(_this.formData)
									_this.$modal.loading('提交中')
									updateQuality(_this.formData).then(res => {
										_this.$modal.msgSuccess("质检成功!");
										setTimeout(() => {
											_this.$modal.closeLoading();
											_this.$tab.switchTab(
												"/pages/work/index");
										}, 500);
									})
								} else {
									let wmsPurchaseQualityDetailList = [];
									for (let i in _this.formData
											.wmsPurchaseQualityDetailList) {
										let obj = {};
										obj.materialCode = _this.formData
											.wmsPurchaseQualityDetailList[i]
											.materialCode;
										obj.materialName = _this.formData
											.wmsPurchaseQualityDetailList[i]
											.materialName;
										obj.materialBatchNo = _this.formData
											.wmsPurchaseQualityDetailList[i]
											.materialBatchNo;
										obj.number = _this.formData
											.wmsPurchaseQualityDetailList[i].number;
										obj.passNumber = Number(_this.formData
											.wmsPurchaseQualityDetailList[i]
											.passNumber);
										obj.failReason = _this.formData
											.wmsPurchaseQualityDetailList[i]
											.failReason;
										wmsPurchaseQualityDetailList.push(obj);
									}
									let enclosure = null;
									if (_this.fileList1.length > 0) {
										enclosure = _this.fileList1.map(obj => obj.url)
											.join(', ');
									}
									console.log(enclosure)
									let data = {
										purchaseReceiveCode: _this.formData
											.purchaseReceiveCode,
										status: '1',
										wmsPurchaseQualityDetailList: _this.formData
											.wmsPurchaseQualityDetailList,
										enclosure: enclosure
									}
									console.log(data)
									_this.$modal.loading('提交中')
									addQuality(data).then(response => {
										_this.$modal.msgSuccess("质检成功!");
										setTimeout(() => {
											_this.$modal.closeLoading();
											_this.$tab.switchTab(
												"/pages/work/index");
										}, 500);
									});
								}

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

<style>
</style>