<template>
	<view class="upload-car-img">
		<view class="picture-wrapper" @click="cardImageOcr">
			<view class="bg">
				<view class="">
					<view class="name">{{ dataList.title }}</view>
					<view class="value">{{ dataList.hint }}</view>
				</view>
				<image v-if="!uploadimges" class="icon" :src="handleImg(dataList.placeholderImg)"></image>
				<image v-else class="icon" :src="uploadimges" @load='handleLoad'></image>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onBeforeMount, nextTick, onBeforeUnmount } from 'vue';
	import { handleToTypes, getUserMedia } from '@/utils/utils';
	import { translate } from '@/utils/getLessLimitSizeImage';
	import { fileURL } from '@/utils/network/api.js';
	import { apiUrl } from '@/utils/network/api';
	import imageCompression from 'browser-image-compression'
	const props = defineProps({
		dataList: {
			type: Object,
			default: () => {
				return {};
			}
		},
		imgUrl: {
			type: String,
			default: ''
		},
	});
	onBeforeMount(() => {
		if (props.imgUrl) {
			uploadimges.value = props.imgUrl
		}
	})
	const handleImg = (url) => {
		// 判断如果头部为http开头
		const reg = /^https?:\/\/.*$/;
		if (reg.test(url)) {
			return url;
		} else {
			return fileURL + url;
		}
	};

	const emits = defineEmits(['uploadImgHandle']);
	let uploadimges = ref('');
	let uploadObj = { scall: 1, name: "", size: "" }
	const cardImageOcr = () => {
		uni.chooseImage({
			count: 1, //只能选取一张照片
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera', 'album'], //从相机查询选择
			success: (res) => {
				// console.log(res.tempFiles[0]);
				console.time('translate')
				uni.showLoading({
					title: '正在识别图片',
					mask: true
				});
				console.log(res, '图片地址');
				if (!res.tempFiles[0].path) {
					console.log(res, '没有图片地址');
					uni.hideLoading()
					return;
				}
				uploadimges.value = res.tempFiles[0].path;
				let size = res.tempFiles[0].size;
				let name = res.tempFiles[0].name;
				let scall = (2 * 1024 * 1024) / size;
				// let scall = (2048 * 1024) / size;
				console.log(size / 1024 / 1024 + 'M', size, name, '图片所有信息');
				console.log(res.tempFiles[0], '图片', res.tempFiles);
				console.log('压缩比', scall, uploadimges.value);
				if (scall >= 1) {
					scall = 1;
					ocrUpload(res.tempFiles[0].path)
					return
				} else if (scall < 0.2) {
					scall = 0.2
				}
				uploadObj.scall = scall
				uploadObj.name = name
				uploadObj.size = size
				// else {
				// 	translate(uploadimges.value, scall, name, (imgURL, file) => {
				// 		uploadimges.value = imgURL;
				// 		console.log(file, '压缩后的图片');
				// 		uploadUrl(file, name, imgURL);
				// 	});
				// }

				// uni.showLoading({
				// 	title: '正在进行识别',
				// 	mask: true
				// });
				// ocrUpload(res.tempFiles[0].path)
			}
		});
	};
	let timer = null
	function handleTimer() {
		clearTimeout(timer)
		timer = setTimeout(() => {
			console.log('运行定时器');
			uni.hideLoading()
		}, 10 * 1000)
	}
	onBeforeUnmount(() => {
		clearTimeout(timer)
	})
	const handleLoad = () => {
		console.log('onload了');
		let scall = uploadObj.scall
		let name = uploadObj.name
		handleTimer()
		setTimeout(() => {
			translate(uploadimges.value, scall, name, (imgURL, file) => {
				let twoScall = 2 * 1024 * 1024 - file.size;
				console.log(twoScall, 'twoScalltwoScall');
				if (twoScall > 0) {
					twoScall = twoScall / (300 * 1024) * 0.1 + scall

				} else if (file.size > 2 * 1024 * 1024) {
					twoScall = scall - 0.1
				}

				console.log(file, file.size / 1024 / 1024 + 'M', scall, '压缩后的图片1', twoScall,);
				if (file.size < 1.5 * 1024 * 1024 || file.size > 2 * 1024 * 1024) {
					if (twoScall > 1) {
						twoScall = 0.95
					}
					console.log('压缩后的图片1twoScall', twoScall,);
					translate(uploadimges.value, twoScall, name, (imgURL, file) => {
						console.timeEnd('translate')
						uploadUrl(file, name, imgURL);
						clearTimeout(timer)
						console.log(file, file.size / 1024 / 1024 + 'm', '压缩后的图片');
					})
				} else {
					uploadUrl(file, name, imgURL);
					console.timeEnd('translate')
				}
			});
		}, 120)

	}
	const ocrUpload = (filePath) => {
		// uni.showLoading({
		// 	title: '文件上传中',
		// 	mask: true
		// })
		// let url = 'https://wayetc.com/upload/v1/file/uploadFile'
		let urls = ''
		if (import.meta.env.DEV) {
			urls = '/minIo/upload'
		} else {
			urls = apiUrl + 'minIo/upload'
		}
		uni.uploadFile({
			url: urls, //仅为示例，非真实的接口地址 accountNum=  secretKey
			filePath: filePath,
			name: 'file',
			formData: {
				'user': 'test',
				"bucket": 'default-bucket'
			},
			success: (uploadFileRes) => {
				const data = JSON.parse(uploadFileRes.data)
				let url = data.data.ossFilePath
				const fileName = data.data.originalFileName
				console.log(uploadFileRes, data, url, fileName, 'uploadFileRes');
				uni.hideLoading()
				let pathDomain = url;
				if (import.meta.env.VITE_APP_TYPE === 'production' || true) {
					url = 'http://100.64.2.113:9000/default-bucket/' + url;
					pathDomain = 'https://qtzl.etcjz.cn/default-bucket/' + pathDomain;
				} else {
					url = 'http://192.168.101.145:9000/default-bucket/' + url;
				}
				console.log(url, '图片上传完地址');
				// uni.hideLoading()
				emits('uploadImgHandle', {
					path: '',
					url,
					fileName,
					pathDomain
				});
			},
			fail(err) {
				console.log(err);
				uni.hideLoading()
			}
		});


	}
	// h5 下载图片
	const plusDownloadImg = (opts) => {
		let {
			url,
			token,
			fileName // 文件名需要传入并且带上后缀
		} = opts;
		if (!fileName) fileName = '未命名.jpg';
		if (url) {
			let dtask = plus.downloader.createDownload(
				url,
				{
					filename: '_downloads/' + fileName
				},
				(d, status) => {
					if (status === 200) {
						console.log('下载成功：' + d.filename);
						// 需要转换成绝对路径
						let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
						plusSaveImg(fileSaveUrl);
					} else {
						console.log('下载失败：' + status);
					}
				}
			);
			dtask.setRequestHeader('token', token);
			dtask.start();
		}
	};
	// h5+ 保存图片到相册
	const plusSaveImg = (filename) => {
		plus.gallery.save(
			filename,
			() => {
				console.log(filename);
				// this.$showToast.ok('已保存到系统相册');
			},
			(e) => {
				// this.$showToast.error('图片保存失败');
				console.log(e.message);
			}
		);
	};

	const uploadUrl = (files, fileName, imgURL) => {
		// WARNING: For POST requests, body is set to null by browsers.
		var data = new FormData();
		data.append('bucket', 'default-bucket');
		data.append('file', files);
		var xhr = new XMLHttpRequest();
		console.log(xhr, 'xhr请求');
		xhr.withCredentials = true;
		xhr.timeout = 60000; // 超时时间，单位是毫秒
		xhr.addEventListener('readystatechange', function () {
			if (this.readyState === 4) {
				uni.hideLoading()
				const data = JSON.parse(this.responseText).data;
				let url = data.ossFilePath;
				let pathDomain = data.ossFilePath;
				if (import.meta.env.VITE_APP_TYPE === 'production' || true) {
					url = 'http://100.64.2.113:9000/default-bucket/' + url;
					pathDomain = 'https://qtzl.etcjz.cn/default-bucket/' + pathDomain;
				} else {
					url = 'http://192.168.101.145:9000/default-bucket/' + url;
				}
				console.log(url, '图片上传完地址');
				// uni.hideLoading()
				emits('uploadImgHandle', {
					path: imgURL,
					url,
					fileName,
					pathDomain
				});
			}
		});

		if (import.meta.env.DEV) {
			xhr.open('POST', '/minIo/upload');
		} else {
			xhr.open('POST', apiUrl + 'minIo/upload');
		}
		xhr.send(data);
	};
</script>

<style lang="scss" scoped>
	.picture-wrapper {
		margin: 10rpx 30rpx;

		.bg {
			background: #ffffff;
			box-shadow: 0rpx 4rpx 13rpx 3rpx rgba(223, 223, 223, 0.8);
			border-radius: 20rpx;
			padding: 40rpx;
			display: flex;
			// align-items: center;
			justify-content: space-between;

			.name {
				font-size: 34rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #000000;
				line-height: 34rpx;
			}

			.value {
				margin-top: 20rpx;
				font-size: 24rpx;
				font-family: Microsoft YaHei;
				font-weight: 400;
				color: #999999;
				line-height: 24rpx;
			}

			.tip {
				margin-top: 20rpx;
				text-align: center;
				width: 110rpx;
				height: 40rpx;
				background: rgba(33, 190, 177, 0.2);
				border-radius: 6rpx;

				.tip-value {
					font-size: 20rpx;
					font-family: Microsoft YaHei;
					font-weight: 400;
					color: #0a8f8a;
					line-height: 40rpx;
					opacity: 1;
				}
			}
		}

		.icon {
			width: 294rpx;
			height: 188rpx;
		}
	}

	.upload-car-bottom {
		font-size: 28rpx;
	}
</style>