<template>
	<view class="scanQR">
		<view class="showTotal" v-if="fillOut">
			<view class="show">
				<view class="showTotal_title">
					出库信息查询
				</view>
				<view style="height: 100rpx;">
					<input class="uni-input" v-model="dataPass" placeholder="请输入密码" @focus="tip=''" />
					<text class="showTotal_tip">{{ tip }}</text>
				</view>
				<view class="showTotal_btn" @click="checkDataPassword">
					登录
				</view>
				</view>
			<view class="over"></view>
		</view>
		<view v-else class="nav">
			<view v-if="showImg" style="text-align: center;padding-top: 30rpx;">
				<image :src="images" mode="aspectFit" class="nav_saomiao" @click="chooseImgs()"></image>	
			</view>
			<view class="nav_info">
				<view class="infoItem">
					<view>商品名称</view>
					<text>{{ info.select_good && info.select_good.good_name }}</text>
				</view>
				<view class="infoItem">
					<view>发货人</view>
					<text>{{ info.select_good_log && info.select_good_log.op_name }}</text>
				</view>
				<view class="infoItem">
					<view>发货时间</view>
					<text>{{ info.select_good_log && info.select_good_log.created_at }}</text>
				</view>
				<view class="infoItem">
					<view>接收者</view>
					<text>{{ info.select_good_log && info.select_good_log.accept_name }}</text>
				</view>
				<view class="infoItem">
					<view>手机号</view>
					<text>{{ info.select_good_log && info.select_good_log.accept_phone }}</text>
				</view>
				<view class="infoItem">
					<view>日志</view>
					<text>{{ info.select_good_log && info.select_good_log.note }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataPass: '',
				fillOut: true,
				tip: '',
				showImg: true,
				images: require('../../static/img/up.png'),
				info: {}
			}
		},
		onLoad() {
			if (this.getCookie('dataPass') && this.getCookie('dataPass') === 'lulu666') {
			    this.fillOut = false
			}
		},
		methods: {
			checkDataPassword() {
			    if (this.dataPass === 'lulu666') {
			        // 密码存储日期 15天
			        this.setCookie('dataPass', this.dataPass, 'd15')
			        this.fillOut = false
					this.tip = ''
			    } else {
			        if (!this.dataPass) {
						this.tip = '请输入密码'
			        } else {
						this.tip = '密码错误'
						this.dataPass = ''
			        }
			    }
			},
			setCookie(name, value, time) {
			    var strsec = this.getsec(time)
			    var exp = new Date()
			    exp.setTime(exp.getTime() + strsec * 1)
			    document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString()
			},
			getsec(str) {
			    var str1 = str.substring(1, str.length) * 1
			    var str2 = str.substring(0, 1)
			    if (str2 === 's') {
			        return str1 * 1000
			    } else if (str2 === 'h') {
			        return str1 * 60 * 60 * 1000
			    } else if (str2 === 'd') {
			        return str1 * 24 * 60 * 60 * 1000
			    }
			},
			getCookie(name) {
			    var arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
			    var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
			    if (document.cookie.match(reg)) {
					arr = document.cookie.match(reg)
			        return unescape(arr[2])
			    } else {
			        return null
			    }
			},
			// 压缩图片
			compress(file, limit = 0.92, file_size = 50) {
				let _this = this
			  return new Promise((resolve, reject) => {
			    if (!file) {
			      reject(new Error('不存在文件'))
			    }
			    const type = file.type
			    const size = file.size
			    const whiteType = ['image/jpeg', 'image/png']
			    if (whiteType.indexOf(type) === -1) { // 判断文件类型
			      reject(new Error('错误的文件类型'))
			    }
			    if (Math.ceil(size / 1024) < file_size) { // 判断文件大小
			      resolve(file)
			    }
			    const reader = new FileReader()
			    reader.readAsDataURL(file)
			    reader.onload = e => {
			      const img = new Image()
			      img.src = e.target.result
			      img.onload = () => {
			        const ratio = img.naturalHeight / img.naturalWidth
			        const canvas = document.createElement('canvas')
			        const ctx = canvas.getContext('2d')
			        canvas.width = img.width > 750 ? 750 : img.width // 固定宽度
			        canvas.height = img.width * ratio
			        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
					// limit:  0到1之间的取值，主要用来选定图片的质量，默认值是0.92，超出范围也会选择默认值。
			        const newImg = canvas.toDataURL('image/jpeg', limit)
					// 将base64转换为filel流，
					let flie= _this.convertBase64UrlToFile({
						dataURL: newImg,
						type: 'image/jpeg',
						contentName: file.name
					})
					console.log('flie',flie)
			        _this.uploadImage(flie)
			      }
			    }
			  })
			},
			// 转base64
			convertBase64UrlToFile(base64) {
				let urlData = base64.dataURL
				let type = base64.type
				let contentName = base64.contentName
				let bytes = null
				if (urlData.split(',').length > 1) { //是否带前缀
					bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
				} else {
					bytes = window.atob(urlData)
				}
				// 处理异常,将ascii码小于0的转换为大于0
				let ab = new ArrayBuffer(bytes.length)
				let ia = new Uint8Array(ab)
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i)
				}
				let result = new Blob([ab], {
					type: type,
				})
				let result1 = new File([result], contentName, {
					type: type
				})
				result1.path = window.URL.createObjectURL(result)
				return result1
			},
			// 查询
			uploadImage(img) {
				let that = this
				uni.showLoading({
					title: '查询中...',
					mask: true
				})
				uni.uploadFile({
					url: 'http://fangw.jiuweiyun.cn/api/authenticity/CKSelect',
					filePath: img.path,
					name: 'image',
					success: (res) => {
						uni.hideLoading()
						const data = JSON.parse(res.data)
						if (data.code == 200 && data.data) {
							this.info = data.data
						} else {
							this.info = {}
							uni.showModal({
								content: data.msg || '查询失败',
								showCancel: false,
								success: function (res) {
									if (res.confirm) {
										that.images = require('../../static/img/up.png')
									}
								}
							})
						}
					},
					fail: function(err) {
						uni.hideLoading()
						uni.showToast({
							title: '失败',
							icon: 'none'
						})
					}
				});
			},
			// 选择图片
			chooseImgs() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					success: res => {
						this.images = res.tempFiles[0].path
						// 大于1M压缩
						console.log('压缩前', res.tempFiles[0])
						if (Math.ceil(res.tempFiles[0].size / 1024) > 1024) {
							let url = res.tempFiles[0]
							uni.showModal({
								title: '提示',
								content: '您选择的图片大于1M，有可能无法识别，是否继续？',
								confirmText: '继续',
								success: function (res) {
									if (res.confirm) {
										that.compress(url)
									} else if (res.cancel) {
										that.images = require('../../static/img/up.png')
									}
								}
							});
						} else {
							that.uploadImage(res.tempFiles[0])
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.nav {
		&_saomiao {
			width: 260rpx;
		}
		.infoItem {
			font-size: 32rpx;
			padding: 10rpx 20rpx;
			display: flex;
			justify-content: space-between;
			text {
				font-size: 26rpx;
				font-weight: 400;
				width: 70%;
			}
		}
	}
	.showTotal {
		.uni-input {
			margin: 100rpx 0 0rpx;
			padding: 20rpx;
			border-bottom: 1rpx solid #999;
		}
		&_btn {
			width: 430rpx;
			height: 88rpx;
			background: linear-gradient(93deg, #A080FF 0%, #5D6BFF 100%);
			opacity: 1;
			border-radius: 44rpx;
			font-size: 32rpx;
			font-weight: 400;
			line-height: 88rpx;
			color: #FFFFFF;
			text-align: center;
			margin: 200rpx auto 0;
		}
		&_tip {
			font-size: 24rpx;
			color: #f44545;
			font-weight: 400;
			padding-left: 10rpx;
		}
		.show {
			width: 620rpx;
			position: fixed;
			left: 0;
			right: 0;
			top: 180rpx;
			margin: auto;
			z-index: 10000;
			background: #fff;
			&-image {
				width: 620rpx;
				position: relative;
			}
			&-button {
				width: 400rpx;
				line-height: 96rpx;
				text-align: center;
				color: #fff;
				font-size: 32rpx;
				border-radius: 56rpx;
				background: linear-gradient(90deg, #f97c55 0%, #f44545 100%);
				position: absolute;
				bottom: -40rpx;
				left: 110rpx;
			}
		}
		.over {
			width: 100%;
			height: 100%;
			background-color: #fff;
			// opacity: 0.6;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 4;
		}
		.button {
			width: 400rpx;
			height: 96rpx;
			background: linear-gradient(90deg, #f97c55 0%, #f44545 100%);
		}
	}
</style>
