<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<uni-popup ref="receiptCheckPopup" class="nopadpop camera_pop">
			<view class="uni-list popuni_list camera_list">
				<view class="list_cell uni-flex uni-row space-between">
					<view class="title">零件号</view>
					<text class="info">{{dataContent.itemCode}}</text>
				</view>
				<view class="list_cell uni-flex uni-row space-between">
					<view class="title">名称</view>
					<text class="info">{{dataContent.itemName}}</text>
				</view>
				<view class="list_cell uni-flex uni-row space-between">
					<view class="title">箱码</view>
					<text class="info">{{dataContent.recommendPackingCode}}</text>
				</view>

				<view class="list_cell uni-flex uni-row space-between">
					<view class="title">不合格原因</view>
					<view class="info" style="padding: 0;">
						<uni-data-picker :class="disabled===true?'disabled':''" :border="false" placeholder="请选择原因"
							popup-title="不合格原因" :localdata="failedReasonArray" v-model="dataContent.failedReason">
						</uni-data-picker>
						<!-- <view v-else style="margin-right: 20rpx;">
							{{dataContent.failedReason}}
						</view> -->

					</view>
				</view>

				<view class="list_cell quality_cell">
					<view class="title">质量缺陷</view>
					<view class="check_textarea">
						<textarea placeholder="请输入内容" :inputBorder="true" v-model="dataContent.massDefect"
							:disabled="disabled" maxlength="100">
						</textarea>
					</view>
				</view>

				<upload-camera ref="uploadImage" style="margin: 10rpx;" :disabled="disabled"></upload-camera>

			</view>
			<view class="pop_btn uni-flex uni-row space-between" v-if="!disabled">
				<button class="cancel" @click="back">返回</button>
				<button class="save" @click="save">保存</button>
			</view>
		</uni-popup>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		showConfirmMsg,
	} from '@/common/basic.js';
	import {
		getFileByCode,
		saveReceiptResult,
		getDictByCode
	} from '@/api/index.js';
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import uploadCamera from '@/mycomponents/uploadCamera.vue'
	export default {
		components: {
			comMessage,
			uploadCamera
		},
		name: 'receipt_check',
		emits :['getReceiptResult'],
		data() {
			return {
				id: '',
				failedReasonIndex: 0,
				failedReasonArray: [],
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
			}
		},
		props: {
			dataContent: {
				type: Object,
				value: null
			},

			disabled: {
				type: Boolean,
				value: true
			},
		},

		filters: {

		},

		mounted: function() {
			this.getUnFildReason();
		},

		onLoad() {
		},

		created() {

		},
		methods: {
			openReceiptCheckPopup(inspectPhotoJson) {
				let that = this;
				that.$refs['receiptCheckPopup'].open("bottom");
				that.getImageInfo(inspectPhotoJson);
			},

			seeReceiptCheckResult(files) {
				this.$refs['receiptCheckPopup'].open("bottom");
				this.$nextTick(function() {
					this.$refs.uploadImage.setFiles(files);
				})
			},

			getImageInfo(inspectPhotoJson) {
				if (inspectPhotoJson != "") //加载照片
				{
					let files = JSON.parse(inspectPhotoJson);
					if (files == null) return;
					uni.showLoading({
						title: '加载中...',
						mask: true
					})
					let imageFiles = [];
					for (var i = 0; i < files.length; i++) {
						let file = files[i];
						let fileKey = file.FileKey;
						let fileName = file.FileName;
						getFileByCode(fileKey).then(res => {
							let result = res;
							var byteString = atob(res.bytes)
							var arrayBuffer = new ArrayBuffer(byteString.length) // 创建缓冲数组
							var intArray = new Uint8Array(arrayBuffer) // 创建视图
							for (var i = 0; i < byteString.length; i++) {
								intArray[i] = byteString.charCodeAt(i)
							}
							const blob = new Blob([intArray], {
								type: 'image/png'
							})
							let url = window.URL.createObjectURL(blob);
							let image = this.createImage(url, fileName, blob.size)
							imageFiles.push(image);
							if (imageFiles.length === files.length) {
								uni.hideLoading();
								this.setImages(imageFiles);
							}
						}).catch(err => {
							this.showMessage(err.message);
							uni.hideLoading();
						})
					}
				}
			},

			createImage(url, fileName, size) {
				let image = {
					name: fileName,
					extname: "png",
					fileType: "image",
					url: url,
					size: size,
					image: {
						width: 175,
						height: 175,
						location: url
					},
					path: url,
					progress: 100,
					status: "ready"
				}
				return image;
			},

			setImages(files) {
				this.$nextTick(function() {
					this.$refs.uploadImage.setFiles(files);
				})
			},

			//保存
			save() {
				let files = this.$refs.uploadImage.getFiles();
				if (files.length > 0) {
					// this.readImageBuffer(files);
					if (this.dataContent.failedReason || this.dataContent.failedReason.length > 0) {
						showConfirmMsg('是否将【' + this.dataContent.recommendPackingCode + '】箱,标记为不合格?', confirm => {
							if (confirm) {
								this.saveResultNotPass(files)
							} else {
								this.$refs.uploadImage.clearFiles()
							}
						});
					} else {
						this.showMessage('请选择不合格原因')

					}
				} else //零件保存为合格
				{
					if (this.dataContent.purchaseReceiptInspectStatus == 3) {
						showConfirmMsg('是否要将零件的状态改为合格?', confirm => {
							if (confirm) {
								this.saveResultPass();
							}
						})
					} else {
						this.$refs['receiptCheckPopup'].close();
					}
				}
			},

			//不合格
			saveResultNotPass(files) {
				uni.showLoading({
					title: '扫描中...',
					mask: true
				})
				// let imgFiles = this.getFileBlob(files);
				this.getFileBlob(files, imgFiles => {
					let item = {
						id: this.dataContent.masterID,
						detailId: this.dataContent.id,
						failedReason: this.dataContent.failedReason,
						massDefect: this.dataContent.massDefect,
						purchaseReceiptInspectStatus: 3,
						filesList: imgFiles
					};
					let param = JSON.stringify(item);
					console.log('param', param);
					//保存目检
					saveReceiptResult(this.dataContent.masterID, param).then(res => {
						if (res != null) {
							console.log('param', param);
							this.afterSave();
						}
						uni.hideLoading();
					}).catch(err => {
						this.showMessage(err.message)
						uni.hideLoading();
					})
				});
			},

			//合格
			saveResultPass() {
				uni.showLoading({
					title: '保存中...',
					mask: true
				})

				let item = {
					id: this.dataContent.masterID,
					detailId: this.dataContent.id,
					failedReason: '',
					massDefect: '',
					purchaseReceiptInspectStatus: 2,
					fileList: []
				};
				let param = JSON.stringify(item);
				//保存目检
				saveReceiptResult(this.dataContent.masterID, param).then(res => {
					if (res != null) {
						this.afterSave();
					}
					uni.hideLoading();
				}).catch(err => {
					this.showMessage(err.message)
					uni.hideLoading();
				})
			},

			afterSave() {
				this.$emit('getReceiptResult')
				this.$refs['receiptCheckPopup'].close();
			},

			getFileBlob(files, callBack) {
				let fileParam = [];
				for (var i = 0; i < files.length; i++) {
					let r = files[i];
					let filePath = r.path;
					let fileName = r.name;
					let rd = new FileReader(); // 创建文件读取对象
					this.objectURLToBlob((filePath), (blob) => {
						const winFile = new window.File([blob], fileName, {
							type: blob.type
						});

						rd.readAsDataURL(winFile)
						rd.onloadend = function() {
							var arrayBuffer = rd.result
							let file = {
								fileName: fileName,
								bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1,
									arrayBuffer
									.length)
							}
							fileParam.push(file);
							if (fileParam.length == files.length) {
								callBack(fileParam);
							}
						}
					})
				}
			},

			readImageBuffer(file, callBack) {
				// let fileParam = [];
				let filePath = file.path;
				let fileName = file.name;
				let rd = new FileReader(); // 创建文件读取对象
				this.objectURLToBlob((filePath), (blob) => {
					const file = new window.File([blob], fileName, {
						type: blob.type
					});

					rd.readAsDataURL(file)
					rd.onloadend = function() {
						var arrayBuffer = rd.result
						let file = {
							fileName: fileName,
							bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1,
								arrayBuffer
								.length)
						}
						// fileParam.push(file);
						callBack(file);
					}
				})

			},

			readImageBuffer(files) {
				let fileParam = [];
				let rd = new FileReader(); // 创建文件读取对象
				for (var i = 0; i < files.length; i++) {
					let filePath = files[i].path;
					let fileName = files[i].name;
					this.objectURLToBlob((filePath), (blob) => {
						const file = new window.File([blob], fileName, {
							type: blob.type
						});

						rd.readAsDataURL(file)
						rd.onloadend = function() {
							var arrayBuffer = rd.result
							let param = {
								fileName: fileName,
								bytes: arrayBuffer.substring(arrayBuffer.indexOf(',') + 1,
									arrayBuffer
									.length)
							}
							fileParam.push(param);
						}
					})
				}
				return fileParam;
			},

			/**
			 * BlobUrl转blob数据  
			 * @param {Object} url blob URL
			 * @param {Object} callback 回调函数
			 */
			objectURLToBlob(url, callback) {
				const http = new XMLHttpRequest();
				http.open("GET", url, true);
				http.responseType = "blob";
				http.onload = function(e) {
					if (this.status == 200 || this.status === 0) {
						callback(this.response);
					}
				};
				http.send();
			},

			back() {
				this.$refs['receiptCheckPopup'].close();
			},

			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			getUnFildReason() {
				let that = this;
				let reasonCode = this.$receiptCheckReason;
				if (!reasonCode) {
					that.showMessage("请在配置文件中配置不合格原因【receiptCheckReason】");
				} else {
					uni.showLoading({
						title: "加载中....",
						mask: true
					});
					getDictByCode(reasonCode).then(res => {
						uni.hideLoading();
						if (res && res.items && res.items.length > 0) {
							res.items.forEach(res => {
								res.text = res.name;
								res.value = res.code;
							})
							that.failedReasonArray = res.items;
						} else {
							that.failedReasonArray = [];
							that.showMessage('不合格原因为空,请在字典中添加字典编号为【receiptCheckReason】的不合格原因');
						}
					}).catch(error => {
						uni.hideLoading();
						that.showMessage(error.message);
					});
				}
			},

		}
	}
</script>

<style scoped lang="scss">
	.disabled {
		pointer-events: none;
	}
</style>
