class BarcodeScanner {
    constructor(options = {}) {
        this.options = {
            endChar: 'Enter', // 默认结束符为回车
            minLength: 3,     // 最小条码长度
            timeout: 100,     // 输入超时（毫秒）
            ...options
        };
        this.barcode = '';
        this.timer = null;
        this.init();

        this.handleKeyDown = this.handleKeyDown.bind(this); // 固定this指向
    }

    init() {
        // document.addEventListener('keydown', this.handleKeyDown.bind(this));
        document.addEventListener('keydown', this.handleKeyDown);
    }

    handleKeyDown(event) {
        // 忽略组合键和结束符之前的处理
        if (event.ctrlKey || event.altKey || event.metaKey || event.keyCode === 229) return;

        const { key } = event;

        // 检测到结束符
        if (key === this.options.endChar) {
            event.preventDefault(); // 阻止默认回车行为
            if (this.barcode.length >= this.options.minLength) {
                this.processBarcode(this.barcode);
            }
            this.reset();
            return;
        }

        // 处理有效字符
        if (key.length === 1 && !event.repeat) {
            this.barcode += key;
            this.resetTimer();
        }
    }

    resetTimer() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
            if (this.barcode.length >= this.options.minLength) {
                this.processBarcode(this.barcode);
            }
            this.reset();
        }, this.options.timeout);
    }

    

    reset() {
        this.barcode = '';
        clearTimeout(this.timer);
    }

    processBarcode(barcode) {
        console.log('Scanned barcode:', barcode);
        // 触发自定义事件或回调函数
        const event = new CustomEvent('barcodeScanned', { detail: barcode });
        document.dispatchEvent(event);
    }

    // 保持之前的类实现，但增加销毁方法
    destroy() {
        // document.removeEventListener('keydown', this.handleKeyDown);
        document.removeEventListener('keydown', this.handleKeyDown);
    }
}
export default BarcodeScanner

/*
// 使用示例
const scanner = new BarcodeScanner();

// 监听扫描事件
document.addEventListener('barcodeScanned', (e) => {
    console.log('Received barcode:', e.detail);
});
*/

//本代码为1.0 版本