import { getText } from "../../locales/index.js";
import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import IconFont from "../iconfont/index.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import React, { useEffect, useRef } from "react";
import { message } from "antd";
import { createPortal } from "react-dom";
import { BarcodeFormat, BrowserMultiFormatReader, NotFoundException } from "@zxing/library";
import "./index.less";
//#region src/components/pisellQRScanner/index.tsx
const _excluded = [
	"visible",
	"onClose",
	"onScan",
	"showUpload",
	"style",
	"className"
];
/**
* 判断是否是二维码
* @param format 条码格式
* @returns 是否是二维码
*/
const isQRCode = (format) => {
	return format === BarcodeFormat.QR_CODE;
};
/**
* 二维码扫描组件
*/
const PisellQRScanner = (_ref) => {
	let { visible, onClose, onScan, showUpload = true, style, className } = _ref;
	_objectWithoutProperties(_ref, _excluded);
	const videoRef = useRef(null);
	const fileInputRef = useRef(null);
	const codeReaderRef = useRef(null);
	const handleScanClose = () => {
		console.log("关闭扫码界面，释放摄像头资源");
		onClose();
		try {
			if (codeReaderRef.current) {
				console.log("重置codeReader...");
				codeReaderRef.current.reset();
			}
		} catch (err) {
			console.error("重置codeReader出错:", err);
		}
		try {
			if (videoRef.current && videoRef.current.srcObject) {
				console.log("停止视频流...");
				videoRef.current.srcObject.getTracks().forEach((track) => {
					console.log(`停止${track.kind}轨道`);
					track.stop();
				});
				videoRef.current.srcObject = null;
			}
		} catch (err) {
			console.error("停止视频流出错:", err);
		}
	};
	const handleUploadClick = () => {
		var _fileInputRef$current;
		(_fileInputRef$current = fileInputRef.current) === null || _fileInputRef$current === void 0 || _fileInputRef$current.click();
	};
	const handleFileChange = function() {
		var _ref3 = _asyncToGenerator(function* (event) {
			const files = event.target.files;
			if (!files || files.length === 0) return;
			try {
				const file = files[0];
				if (!file.type.startsWith("image/")) {
					message.error(getText("qrscanner-error-upload-image"));
					return;
				}
				try {
					const reader = new FileReader();
					reader.onload = function() {
						var _ref2 = _asyncToGenerator(function* (e) {
							if (!e.target || !e.target.result) {
								message.error({
									content: getText("qrscanner-error-load-failed"),
									key: "qrProcessing"
								});
								return;
							}
							const img = new Image();
							img.onload = _asyncToGenerator(function* () {
								try {
									console.log("图片加载完成，尺寸:", img.width, "x", img.height);
									const canvas = document.createElement("canvas");
									canvas.width = img.width;
									canvas.height = img.height;
									const ctx = canvas.getContext("2d");
									if (!ctx) {
										message.error({
											content: "无法创建画布上下文",
											key: "qrProcessing"
										});
										return;
									}
									ctx.drawImage(img, 0, 0, img.width, img.height);
									const methods = [
										_asyncToGenerator(function* () {
											console.log("尝试方法1: 原始图像");
											return yield new BrowserMultiFormatReader(void 0, 2e3).decodeFromImage(img);
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法2: 绿色通道强增强");
											const greenCanvas = document.createElement("canvas");
											greenCanvas.width = img.width;
											greenCanvas.height = img.height;
											const greenCtx = greenCanvas.getContext("2d");
											if (!greenCtx) throw new Error("无法创建画布上下文");
											greenCtx.drawImage(img, 0, 0);
											const imageData = greenCtx.getImageData(0, 0, greenCanvas.width, greenCanvas.height);
											const data = imageData.data;
											for (let i = 0; i < data.length; i += 4) {
												const red = data[i];
												const green = data[i + 1];
												const blue = data[i + 2];
												if (green > red * .85 || green > blue * .85) if (green > 100) {
													data[i] = 0;
													data[i + 1] = 0;
													data[i + 2] = 0;
												} else {
													data[i] = 255;
													data[i + 1] = 255;
													data[i + 2] = 255;
												}
											}
											greenCtx.putImageData(imageData, 0, 0);
											const greenImg = new Image();
											return new Promise((resolve, reject) => {
												greenImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 2e3).decodeFromImage(greenImg));
													} catch (err) {
														reject(err);
													}
												});
												greenImg.onerror = reject;
												greenImg.src = greenCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试微信绿码专用优化方法");
											const wechatCanvas = document.createElement("canvas");
											wechatCanvas.width = img.width;
											wechatCanvas.height = img.height;
											const wechatCtx = wechatCanvas.getContext("2d");
											if (!wechatCtx) throw new Error("无法创建画布上下文");
											wechatCtx.drawImage(img, 0, 0);
											const imageData = wechatCtx.getImageData(0, 0, wechatCanvas.width, wechatCanvas.height);
											const data = imageData.data;
											for (let i = 0; i < data.length; i += 4) {
												const red = data[i];
												const green = data[i + 1];
												const blue = data[i + 2];
												const brightness = (red + green + blue) / 3;
												if (green / (red + green + blue + 1) > .35 && green > 80 && brightness < 200) {
													data[i] = 0;
													data[i + 1] = 0;
													data[i + 2] = 0;
												} else {
													data[i] = 255;
													data[i + 1] = 255;
													data[i + 2] = 255;
												}
											}
											wechatCtx.putImageData(imageData, 0, 0);
											const wechatImg = new Image();
											return new Promise((resolve, reject) => {
												wechatImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 2500).decodeFromImage(wechatImg));
													} catch (err) {
														reject(err);
													}
												});
												wechatImg.onerror = reject;
												wechatImg.src = wechatCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法3: 仅使用绿色通道");
											const greenOnlyCanvas = document.createElement("canvas");
											greenOnlyCanvas.width = img.width;
											greenOnlyCanvas.height = img.height;
											const greenOnlyCtx = greenOnlyCanvas.getContext("2d");
											if (!greenOnlyCtx) throw new Error("无法创建画布上下文");
											greenOnlyCtx.drawImage(img, 0, 0);
											const imageData = greenOnlyCtx.getImageData(0, 0, greenOnlyCanvas.width, greenOnlyCanvas.height);
											const data = imageData.data;
											for (let i = 0; i < data.length; i += 4) {
												data[i] = 0;
												data[i + 2] = 0;
											}
											greenOnlyCtx.putImageData(imageData, 0, 0);
											const greenOnlyImg = new Image();
											return new Promise((resolve, reject) => {
												greenOnlyImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 1500).decodeFromImage(greenOnlyImg));
													} catch (err) {
														reject(err);
													}
												});
												greenOnlyImg.onerror = reject;
												greenOnlyImg.src = greenOnlyCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法4: 自适应阈值二值化");
											const adaptiveCanvas = document.createElement("canvas");
											adaptiveCanvas.width = img.width;
											adaptiveCanvas.height = img.height;
											const adaptiveCtx = adaptiveCanvas.getContext("2d");
											if (!adaptiveCtx) throw new Error("无法创建画布上下文");
											adaptiveCtx.drawImage(img, 0, 0);
											const imageData = adaptiveCtx.getImageData(0, 0, adaptiveCanvas.width, adaptiveCanvas.height);
											const data = imageData.data;
											let sum = 0;
											let count = 0;
											for (let i = 0; i < data.length; i += 4) {
												const gray = .299 * data[i] + .587 * data[i + 1] + .114 * data[i + 2];
												sum += gray;
												count++;
											}
											const adaptiveThreshold = sum / count * .85;
											console.log("自适应阈值:", adaptiveThreshold);
											for (let i = 0; i < data.length; i += 4) {
												const val = .299 * data[i] + .587 * data[i + 1] + .114 * data[i + 2] < adaptiveThreshold ? 0 : 255;
												data[i] = val;
												data[i + 1] = val;
												data[i + 2] = val;
											}
											adaptiveCtx.putImageData(imageData, 0, 0);
											const adaptiveImg = new Image();
											return new Promise((resolve, reject) => {
												adaptiveImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 1500).decodeFromImage(adaptiveImg));
													} catch (err) {
														reject(err);
													}
												});
												adaptiveImg.onerror = reject;
												adaptiveImg.src = adaptiveCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法5: 高斯模糊后锐化");
											const sharpenCanvas = document.createElement("canvas");
											sharpenCanvas.width = img.width;
											sharpenCanvas.height = img.height;
											const sharpenCtx = sharpenCanvas.getContext("2d");
											if (!sharpenCtx) throw new Error("无法创建画布上下文");
											sharpenCtx.drawImage(img, 0, 0);
											sharpenCtx.filter = "blur(1px)";
											sharpenCtx.drawImage(img, 0, 0);
											sharpenCtx.filter = "none";
											const sharpenedData = applySharpen(sharpenCtx.getImageData(0, 0, sharpenCanvas.width, sharpenCanvas.height), sharpenCanvas.width, sharpenCanvas.height);
											sharpenCtx.putImageData(sharpenedData, 0, 0);
											const sharpenImg = new Image();
											return new Promise((resolve, reject) => {
												sharpenImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 1500).decodeFromImage(sharpenImg));
													} catch (err) {
														reject(err);
													}
												});
												sharpenImg.onerror = reject;
												sharpenImg.src = sharpenCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法6: 反色处理");
											const invertCanvas = document.createElement("canvas");
											invertCanvas.width = img.width;
											invertCanvas.height = img.height;
											const invertCtx = invertCanvas.getContext("2d");
											if (!invertCtx) throw new Error("无法创建画布上下文");
											invertCtx.drawImage(img, 0, 0);
											const imageData = invertCtx.getImageData(0, 0, invertCanvas.width, invertCanvas.height);
											const data = imageData.data;
											for (let i = 0; i < data.length; i += 4) {
												data[i] = 255 - data[i];
												data[i + 1] = 255 - data[i + 1];
												data[i + 2] = 255 - data[i + 2];
											}
											invertCtx.putImageData(imageData, 0, 0);
											const invertImg = new Image();
											return new Promise((resolve, reject) => {
												invertImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 1500).decodeFromImage(invertImg));
													} catch (err) {
														reject(err);
													}
												});
												invertImg.onerror = reject;
												invertImg.src = invertCanvas.toDataURL("image/png");
											});
										}),
										_asyncToGenerator(function* () {
											console.log("尝试方法7: HSV色彩空间处理");
											const hsvCanvas = document.createElement("canvas");
											hsvCanvas.width = img.width;
											hsvCanvas.height = img.height;
											const hsvCtx = hsvCanvas.getContext("2d");
											if (!hsvCtx) throw new Error("无法创建画布上下文");
											hsvCtx.drawImage(img, 0, 0);
											const imageData = hsvCtx.getImageData(0, 0, hsvCanvas.width, hsvCanvas.height);
											const data = imageData.data;
											for (let i = 0; i < data.length; i += 4) {
												const r = data[i] / 255;
												const g = data[i + 1] / 255;
												const b = data[i + 2] / 255;
												const max = Math.max(r, g, b);
												const min = Math.min(r, g, b);
												const diff = max - min;
												let h = 0;
												if (max === min) h = 0;
												else if (max === r) h = (60 * ((g - b) / diff) + 360) % 360;
												else if (max === g) h = 60 * ((b - r) / diff) + 120;
												else h = 60 * ((r - g) / diff) + 240;
												const s = max === 0 ? 0 : diff / max;
												if (h >= 90 && h <= 150 && s > .2) {
													data[i] = 0;
													data[i + 1] = 0;
													data[i + 2] = 0;
												} else {
													data[i] = 255;
													data[i + 1] = 255;
													data[i + 2] = 255;
												}
											}
											hsvCtx.putImageData(imageData, 0, 0);
											const hsvImg = new Image();
											return new Promise((resolve, reject) => {
												hsvImg.onload = _asyncToGenerator(function* () {
													try {
														resolve(yield new BrowserMultiFormatReader(void 0, 1500).decodeFromImage(hsvImg));
													} catch (err) {
														reject(err);
													}
												});
												hsvImg.onerror = reject;
												hsvImg.src = hsvCanvas.toDataURL("image/png");
											});
										})
									];
									let success = false;
									let result = null;
									try {
										for (let i = 0; i < methods.length; i++) try {
											console.log(`尝试方法${i + 1}...`);
											result = yield methods[i]();
											if (result) {
												success = true;
												console.log(`方法${i + 1}成功!`);
												break;
											}
										} catch (err) {
											console.error(`方法${i + 1}失败:`, err);
										}
										if (success && result) {
											const text = result.getText();
											const isQR = isQRCode(result.getBarcodeFormat());
											console.log(`识别成功 - 类型: ${isQR ? "二维码" : "条形码"}, 内容:`, text);
											message.destroy("qrProcessing");
											onScan(text);
											handleScanClose();
										} else {
											console.log("识别失败，所有方法都尝试过了");
											message.destroy("qrProcessing");
											handleScanClose();
											setTimeout(() => {
												message.error({
													content: getText("qrscanner-error-no-code"),
													duration: 3
												});
											}, 100);
										}
									} catch (outerError) {
										console.error("识别过程发生意外错误:", outerError);
										message.destroy("qrProcessing");
										handleScanClose();
										setTimeout(() => {
											message.error({
												content: getText("qrscanner-error-no-code"),
												duration: 3
											});
										}, 100);
									}
								} catch (processError) {
									console.error("图像处理错误:", processError);
									message.destroy("qrProcessing");
									handleScanClose();
									setTimeout(() => {
										message.error({
											content: getText("qrscanner-error-process-image"),
											duration: 3
										});
									}, 100);
								}
							});
							img.onerror = () => {
								message.destroy("qrProcessing");
								handleScanClose();
								message.error(getText("qrscanner-error-load-failed"));
							};
							img.src = e.target.result.toString();
						});
						return function(_x) {
							return _ref2.apply(this, arguments);
						};
					}();
					reader.onerror = () => {
						message.destroy("qrProcessing");
						handleScanClose();
						message.error(getText("qrscanner-error-load-failed"));
					};
					reader.readAsDataURL(file);
				} catch (error) {
					console.error("识别过程错误:", error);
					message.destroy("qrProcessing");
					handleScanClose();
					message.error(getText("qrscanner-error-process-image"));
				}
			} catch (error) {
				console.error("处理图片出错", error);
				message.destroy("qrProcessing");
				handleScanClose();
				message.error(getText("qrscanner-error-process-image"));
			} finally {
				if (fileInputRef.current) fileInputRef.current.value = "";
			}
		});
		return function handleFileChange(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	const applySharpen = (imageData, width, height) => {
		const data = imageData.data;
		const temp = new Uint8ClampedArray(data);
		const kernel = [
			0,
			-1,
			0,
			-1,
			5,
			-1,
			0,
			-1,
			0
		];
		for (let y = 1; y < height - 1; y++) for (let x = 1; x < width - 1; x++) {
			const idx = (y * width + x) * 4;
			for (let c = 0; c < 3; c++) {
				let val = 0;
				for (let ky = -1; ky <= 1; ky++) for (let kx = -1; kx <= 1; kx++) {
					const kidx = ((y + ky) * width + (x + kx)) * 4 + c;
					val += temp[kidx] * kernel[(ky + 1) * 3 + (kx + 1)];
				}
				data[idx + c] = Math.min(255, Math.max(0, val));
			}
		}
		return imageData;
	};
	useEffect(() => {
		if (visible) (function() {
			var _ref4 = _asyncToGenerator(function* () {
				try {
					if (codeReaderRef.current) try {
						codeReaderRef.current.reset();
					} catch (err) {
						console.log("重置之前的实例出错", err);
					}
					codeReaderRef.current = new BrowserMultiFormatReader(void 0, 300);
					console.log("创建二维码阅读器实例成功");
					codeReaderRef.current.decodeFromVideoDevice(null, videoRef.current, (result, err) => {
						if (result) {
							const text = result.getText();
							const isQR = isQRCode(result.getBarcodeFormat());
							console.log(`扫描成功 - 类型: ${isQR ? "二维码" : "条形码"}, 内容:`, text);
							onScan(text);
							handleScanClose();
						}
						if (err && !(err instanceof NotFoundException)) console.error("扫描过程中出错:", err);
					});
				} catch (err) {
					console.error("摄像头初始化错误", err);
					handleScanClose();
					setTimeout(() => {
						message.error({
							content: getText("qrscanner-error-camera-init"),
							duration: 3
						});
					}, 100);
				}
			});
			return function initCamera() {
				return _ref4.apply(this, arguments);
			};
		})()();
	}, [visible]);
	useEffect(() => {
		return () => {
			if (codeReaderRef.current) try {
				codeReaderRef.current.reset();
			} catch (err) {
				console.error("清理资源时出错", err);
			}
		};
	}, []);
	if (!visible) return null;
	return createPortal(/* @__PURE__ */ React.createElement("div", {
		className: "pisell-qr-scanner-fullscreen",
		style: _objectSpread2({
			zIndex: 99999,
			position: "fixed",
			top: 0,
			left: 0,
			right: 0,
			bottom: 0,
			width: "100vw",
			height: "100vh",
			backgroundColor: "#000",
			margin: 0,
			padding: 0,
			overflow: "hidden",
			display: "flex",
			justifyContent: "center",
			alignItems: "center",
			boxSizing: "border-box"
		}, style)
	}, /* @__PURE__ */ React.createElement("div", {
		className: "scan-container",
		style: {
			position: "relative",
			width: "100%",
			height: "100%",
			overflow: "hidden"
		}
	}, /* @__PURE__ */ React.createElement("video", {
		ref: videoRef,
		className: "scan-video",
		style: {
			width: "100%",
			height: "100%",
			objectFit: "cover"
		},
		autoPlay: true,
		playsInline: true,
		muted: true
	})), /* @__PURE__ */ React.createElement(IconFont, {
		type: "pisell2-arrow-left",
		className: "scan-close-left",
		style: {
			zIndex: 1e5,
			position: "fixed",
			top: "20px",
			left: "20px",
			fontSize: "24px",
			color: "#fff",
			backgroundColor: "rgba(255, 255, 255, 0.15)",
			width: "44px",
			height: "44px",
			display: "flex",
			alignItems: "center",
			justifyContent: "center",
			borderRadius: "50%",
			cursor: "pointer"
		},
		onClick: handleScanClose
	}), showUpload && /* @__PURE__ */ React.createElement(IconFont, {
		type: "pisell2-image-01",
		className: "scan-upload",
		style: {
			zIndex: 1e5,
			position: "fixed",
			right: "30px",
			bottom: "60px",
			fontSize: "48px",
			color: "#fff",
			backgroundColor: "rgba(255, 255, 255, 0.15)",
			width: "88px",
			height: "88px",
			display: "flex",
			alignItems: "center",
			justifyContent: "center",
			borderRadius: "50%",
			cursor: "pointer"
		},
		onClick: handleUploadClick
	}), /* @__PURE__ */ React.createElement("input", {
		type: "file",
		ref: fileInputRef,
		onChange: handleFileChange,
		accept: "image/*",
		className: "scan-file-input",
		style: { display: "none" }
	})), document.body);
};
//#endregion
export { PisellQRScanner as default };
