import {
	ref
} from 'vue';
import ossUploadFile from '../../utils/oss-upload-file.js';

// 图片处理
export function useImageProcessor() {
	const photos = ref([]) //照片数组
	const farmsNumber = ref(0) // 帧数计数器
	const isBegin = ref(false) //是否处在扫码中状态
	const isUploading = ref(false) // 防止重复处理


	// 初始化相机数据
	const resetScanData = () => {
		isBegin.value = false; // 重置扫码状态
		farmsNumber.value = 0; // 重置帧计数器
		photos.value = []; // 清空照片数组
		isUploading.value = false; // 重置处理状态
	}

	// 上传图片到oss
	const processAndUploadImages = async (imageIndexes) => {
		if (isUploading.value) {
			console.log('正在上传中，请稍候...');
			return;
		}

		isUploading.value = true;

		try {
			// 处理图片为临时文件路径
			const filePaths = await processImages(imageIndexes);

			// 上传图片
			const uploadResults = [];

			for (const filePath of filePaths) {
				console.log('准备上传oss图片:', filePath)
				const ossFiles = await ossUploadFile(filePath)
				if (ossFiles) uploadResults.push(ossFiles);
			}

			return uploadResults;

		} catch (error) {
			console.error('图片上传失败:', error);
		} finally {
			isUploading.value = false;
		}
	}

	// 扫码数据源处理
	const processImages = async (imageIndexes) => {
		const requestPhotos = []

		// 处理指定索引的照片
		for (let index = 0; index < imageIndexes; index++) {
			const photo = photos.value[index]
			if (!photo) continue
			console.log('处理图片前循环:', photo)
			try {
				// 换为临时文件
				const imageInfo = await getImageTempFilePath(photo)
				if (imageInfo) {
					requestPhotos.push(imageInfo)
				}
			} catch (error) {
				console.error(`处理图片 ${index} 失败:`, error)
			}
		}
		return requestPhotos
	}

	// 处理图片格式
	const getImageTempFilePath = (photo) => {
		return new Promise((resolve, reject) => {
			const data = new Uint8Array(photo.data);
			const clamped = new Uint8ClampedArray(data);
			const {
				width,
				height
			} = photo;

			wx.createSelectorQuery()
				.select("#myCanvas")
				.fields({
					size: true,
					dataset: true
				}, (data) => {
					// 直接转换为临时文件路径
					wx.canvasPutImageData({
						canvasId: "myCanvas",
						x: 0,
						y: 0,
						width: width,
						height: height,
						data: clamped,
						success: () => {
							wx.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: width,
								height: height,
								destWidth: width * 2, // 放大图片提高质量
								destHeight: height * 2,
								quality: 1, // 最高质量
								canvasId: "myCanvas",
								fileType: "jpg",
								success: (data) => {
									console.log('微信临时文件:',data.tempFilePath)
									resolve(data.tempFilePath)
								},
								fail: (e) => {
									reject({
										code: "1",
										msg: "画布转临时文件失败",
										error: e
									});
								},
							});
						},
						fail: (e) => {
							reject({
								code: "1",
								msg: "canvas 画布写入图片错误",
								error: e,
							});
						},
					});
				}).exec();
		})
	}

	return {
		photos,
		isBegin,
		farmsNumber,
		resetScanData,
		processAndUploadImages
	}
}