var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pisellQRScanner/index.tsx
var pisellQRScanner_exports = {};
__export(pisellQRScanner_exports, {
  default: () => pisellQRScanner_default
});
module.exports = __toCommonJS(pisellQRScanner_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_library = require("@zxing/library");
var import_iconfont = __toESM(require("../iconfont"));
var import_index = require("./index.less");
var import_react_dom = require("react-dom");
var import_locales = require("../../locales");
var isQRCode = (format) => {
  return format === import_library.BarcodeFormat.QR_CODE;
};
var PisellQRScanner = ({
  visible,
  onClose,
  onScan,
  showUpload = true,
  // 默认显示上传图片按钮
  // 明确解构其他可能的属性，避免通过扩展运算符传递不必要的属性到DOM
  style,
  className,
  ...otherProps
  // 捕获其他可能的属性，但不使用它们
}) => {
  const videoRef = (0, import_react.useRef)(null);
  const fileInputRef = (0, import_react.useRef)(null);
  const codeReaderRef = (0, import_react.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("停止视频流...");
        const stream = videoRef.current.srcObject;
        stream.getTracks().forEach((track) => {
          console.log(`停止${track.kind}轨道`);
          track.stop();
        });
        videoRef.current.srcObject = null;
      }
    } catch (err) {
      console.error("停止视频流出错:", err);
    }
  };
  const handleUploadClick = () => {
    var _a;
    (_a = fileInputRef.current) == null ? void 0 : _a.click();
  };
  const handleFileChange = async (event) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;
    try {
      const file = files[0];
      if (!file.type.startsWith("image/")) {
        import_antd.message.error((0, import_locales.getText)("qrscanner-error-upload-image"));
        return;
      }
      try {
        const reader = new FileReader();
        reader.onload = async (e) => {
          if (!e.target || !e.target.result) {
            import_antd.message.error({ content: (0, import_locales.getText)("qrscanner-error-load-failed"), key: "qrProcessing" });
            return;
          }
          const img = new Image();
          img.onload = async () => {
            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) {
                import_antd.message.error({ content: "无法创建画布上下文", key: "qrProcessing" });
                return;
              }
              ctx.drawImage(img, 0, 0, img.width, img.height);
              const methods = [
                // 方法1: 原始图像
                async () => {
                  console.log("尝试方法1: 原始图像");
                  const decoder = new import_library.BrowserMultiFormatReader(void 0, 2e3);
                  return await decoder.decodeFromImage(img);
                },
                // 方法2: 绿色通道增强 (针对微信二维码) - 强级别
                async () => {
                  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 * 0.85 || green > blue * 0.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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 2e3);
                        const result2 = await decoder.decodeFromImage(greenImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    greenImg.onerror = reject;
                    greenImg.src = greenCanvas.toDataURL("image/png");
                  });
                },
                // 特殊处理：微信绿码专用增强（降低绿色阈值）
                async () => {
                  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;
                    const greenRatio = green / (red + green + blue + 1);
                    if (greenRatio > 0.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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 2500);
                        const result2 = await decoder.decodeFromImage(wechatImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    wechatImg.onerror = reject;
                    wechatImg.src = wechatCanvas.toDataURL("image/png");
                  });
                },
                // 方法3: 仅绿色通道
                async () => {
                  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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 1500);
                        const result2 = await decoder.decodeFromImage(greenOnlyImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    greenOnlyImg.onerror = reject;
                    greenOnlyImg.src = greenOnlyCanvas.toDataURL("image/png");
                  });
                },
                // 方法4: 自适应阈值二值化
                async () => {
                  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 = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
                    sum += gray;
                    count++;
                  }
                  const adaptiveThreshold = sum / count * 0.85;
                  console.log("自适应阈值:", adaptiveThreshold);
                  for (let i = 0; i < data.length; i += 4) {
                    const gray = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
                    const val = gray < 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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 1500);
                        const result2 = await decoder.decodeFromImage(adaptiveImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    adaptiveImg.onerror = reject;
                    adaptiveImg.src = adaptiveCanvas.toDataURL("image/png");
                  });
                },
                // 方法5: 高斯模糊后锐化
                async () => {
                  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 imageData = sharpenCtx.getImageData(0, 0, sharpenCanvas.width, sharpenCanvas.height);
                  const sharpenedData = applySharpen(imageData, sharpenCanvas.width, sharpenCanvas.height);
                  sharpenCtx.putImageData(sharpenedData, 0, 0);
                  const sharpenImg = new Image();
                  return new Promise((resolve, reject) => {
                    sharpenImg.onload = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 1500);
                        const result2 = await decoder.decodeFromImage(sharpenImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    sharpenImg.onerror = reject;
                    sharpenImg.src = sharpenCanvas.toDataURL("image/png");
                  });
                },
                // 方法6: 反色处理
                async () => {
                  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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 1500);
                        const result2 = await decoder.decodeFromImage(invertImg);
                        resolve(result2);
                      } catch (err) {
                        reject(err);
                      }
                    };
                    invertImg.onerror = reject;
                    invertImg.src = invertCanvas.toDataURL("image/png");
                  });
                },
                // 方法7: HSV色彩空间处理微信绿色
                async () => {
                  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;
                    const v = max;
                    const isGreen = h >= 90 && h <= 150;
                    if (isGreen && s > 0.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 = async () => {
                      try {
                        const decoder = new import_library.BrowserMultiFormatReader(void 0, 1500);
                        const result2 = await decoder.decodeFromImage(hsvImg);
                        resolve(result2);
                      } 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 = await 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 format = result.getBarcodeFormat();
                  const isQR = isQRCode(format);
                  console.log(`识别成功 - 类型: ${isQR ? "二维码" : "条形码"}, 内容:`, text);
                  import_antd.message.destroy("qrProcessing");
                  onScan(text);
                  handleScanClose();
                } else {
                  console.log("识别失败，所有方法都尝试过了");
                  import_antd.message.destroy("qrProcessing");
                  handleScanClose();
                  setTimeout(() => {
                    import_antd.message.error({
                      content: (0, import_locales.getText)("qrscanner-error-no-code"),
                      duration: 3
                    });
                  }, 100);
                }
              } catch (outerError) {
                console.error("识别过程发生意外错误:", outerError);
                import_antd.message.destroy("qrProcessing");
                handleScanClose();
                setTimeout(() => {
                  import_antd.message.error({
                    content: (0, import_locales.getText)("qrscanner-error-no-code"),
                    duration: 3
                  });
                }, 100);
              }
            } catch (processError) {
              console.error("图像处理错误:", processError);
              import_antd.message.destroy("qrProcessing");
              handleScanClose();
              setTimeout(() => {
                import_antd.message.error({
                  content: (0, import_locales.getText)("qrscanner-error-process-image"),
                  duration: 3
                });
              }, 100);
            }
          };
          img.onerror = () => {
            import_antd.message.destroy("qrProcessing");
            handleScanClose();
            import_antd.message.error((0, import_locales.getText)("qrscanner-error-load-failed"));
          };
          img.src = e.target.result.toString();
        };
        reader.onerror = () => {
          import_antd.message.destroy("qrProcessing");
          handleScanClose();
          import_antd.message.error((0, import_locales.getText)("qrscanner-error-load-failed"));
        };
        reader.readAsDataURL(file);
      } catch (error) {
        console.error("识别过程错误:", error);
        import_antd.message.destroy("qrProcessing");
        handleScanClose();
        import_antd.message.error((0, import_locales.getText)("qrscanner-error-process-image"));
      }
    } catch (error) {
      console.error("处理图片出错", error);
      import_antd.message.destroy("qrProcessing");
      handleScanClose();
      import_antd.message.error((0, import_locales.getText)("qrscanner-error-process-image"));
    } finally {
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };
  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;
  };
  (0, import_react.useEffect)(() => {
    if (visible) {
      const initCamera = async () => {
        try {
          if (codeReaderRef.current) {
            try {
              codeReaderRef.current.reset();
            } catch (err) {
              console.log("重置之前的实例出错", err);
            }
          }
          codeReaderRef.current = new import_library.BrowserMultiFormatReader(void 0, 300);
          console.log("创建二维码阅读器实例成功");
          codeReaderRef.current.decodeFromVideoDevice(
            null,
            // 使用默认设备
            videoRef.current,
            (result, err) => {
              if (result) {
                const text = result.getText();
                const format = result.getBarcodeFormat();
                const isQR = isQRCode(format);
                console.log(`扫描成功 - 类型: ${isQR ? "二维码" : "条形码"}, 内容:`, text);
                onScan(text);
                handleScanClose();
              }
              if (err && !(err instanceof import_library.NotFoundException)) {
                console.error("扫描过程中出错:", err);
              }
            }
          );
        } catch (err) {
          console.error("摄像头初始化错误", err);
          handleScanClose();
          setTimeout(() => {
            import_antd.message.error({
              content: (0, import_locales.getText)("qrscanner-error-camera-init"),
              duration: 3
            });
          }, 100);
        }
      };
      initCamera();
    }
  }, [visible]);
  (0, import_react.useEffect)(() => {
    return () => {
      if (codeReaderRef.current) {
        try {
          codeReaderRef.current.reset();
        } catch (err) {
          console.error("清理资源时出错", err);
        }
      }
    };
  }, []);
  if (!visible) return null;
  return (0, import_react_dom.createPortal)(
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "pisell-qr-scanner-fullscreen",
        style: {
          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__ */ import_react.default.createElement(
        "div",
        {
          className: "scan-container",
          style: {
            position: "relative",
            width: "100%",
            height: "100%",
            overflow: "hidden"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "video",
          {
            ref: videoRef,
            className: "scan-video",
            style: {
              width: "100%",
              height: "100%",
              objectFit: "cover"
            },
            autoPlay: true,
            playsInline: true,
            muted: true
          }
        )
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_iconfont.default,
        {
          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__ */ import_react.default.createElement(
        import_iconfont.default,
        {
          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__ */ import_react.default.createElement(
        "input",
        {
          type: "file",
          ref: fileInputRef,
          onChange: handleFileChange,
          accept: "image/*",
          className: "scan-file-input",
          style: { display: "none" }
        }
      )
    ),
    document.body
  );
};
var pisellQRScanner_default = PisellQRScanner;
