var qrcode;
function creatqrcode(text) {
    var options = {
        text: text,
        width: 180,
        height: 180,
        correctLevel: QRCode.CorrectLevel.H,
        //logo: "img/logo.png",
        //logoWidth: 45,
        //logoHeight: 45,
    };
    if (qrcode == null) {
        qrcode = new QRCode(document.getElementById("qrcode"), options);
    } else {
        qrcode.clear();
        qrcode = new QRCode(document.getElementById("qrcode"), options);
    }
}

// ══════════ IO 音效系统 ══════════
var _audioCtx = null;
function _getAudioCtx() {
    if (!_audioCtx || _audioCtx.state === 'closed') {
        _audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    }
    if (_audioCtx.state === 'suspended') _audioCtx.resume();
    return _audioCtx;
}

// 音效类型持久化
function getSoundType() { return localStorage.getItem('io_sound_type') || '0'; }
function setSoundType(v) { localStorage.setItem('io_sound_type', v); }

function playClickSound(isOn) {
    var type = getSoundType();
    if (type === '0') return; // 无声
    try {
        var ctx = _getAudioCtx();
        var t = ctx.currentTime;
        switch (type) {
            case '1': _sndDualTone(ctx, t, isOn); break;
            case '2': _sndRelay(ctx, t, isOn); break;
            case '3': _sndBubble(ctx, t, isOn); break;
            case '4': _sndBeep(ctx, t, isOn); break;
            case '5': _sndWood(ctx, t, isOn); break;
            case '6': _sndDrop(ctx, t, isOn); break;
            case '7': _sndSpring(ctx, t, isOn); break;
            case '8': _sndLaser(ctx, t, isOn); break;
        }
    } catch (e) { }
}

// 试听当前音效
function previewSound(type, isOn) {
    var old = getSoundType();
    setSoundType(type);
    playClickSound(isOn);
    setSoundType(old);
}

// 1. iOS 双音 (do→mi / mi→do)
function _sndDualTone(ctx, t, isOn) {
    var f1 = isOn ? 523 : 659, f2 = isOn ? 659 : 523;
    _tone(ctx, t, f1, 'sine', 0.15, 0.06);
    _tone(ctx, t + 0.08, f2, 'sine', 0.15, 0.06);
}

// 2. 继电器咔嗒
function _sndRelay(ctx, t, isOn) {
    var dur = isOn ? 0.03 : 0.045;
    var buf = ctx.createBuffer(1, ctx.sampleRate * dur, ctx.sampleRate);
    var d = buf.getChannelData(0);
    for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
    var src = ctx.createBufferSource(); src.buffer = buf;
    var f = ctx.createBiquadFilter(); f.type = 'bandpass';
    f.frequency.value = isOn ? 4000 : 1800; f.Q.value = isOn ? 8 : 3;
    var g = ctx.createGain();
    g.gain.setValueAtTime(isOn ? 0.4 : 0.25, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + dur);
    src.connect(f); f.connect(g); g.connect(ctx.destination);
    src.start(t); src.stop(t + dur);
}

// 3. 气泡
function _sndBubble(ctx, t, isOn) {
    var o = ctx.createOscillator(); var g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = 'sine';
    o.frequency.setValueAtTime(isOn ? 400 : 800, t);
    o.frequency.exponentialRampToValueAtTime(isOn ? 900 : 350, t + 0.08);
    g.gain.setValueAtTime(0.2, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.12);
    o.start(t); o.stop(t + 0.12);
}

// 4. 电子蜂鸣
function _sndBeep(ctx, t, isOn) {
    _tone(ctx, t, isOn ? 1000 : 600, 'square', 0.1, 0.08);
    if (isOn) _tone(ctx, t + 0.1, 1000, 'square', 0.1, 0.05);
}

// 5. 木质敲击
function _sndWood(ctx, t, isOn) {
    var buf = ctx.createBuffer(1, ctx.sampleRate * 0.04, ctx.sampleRate);
    var d = buf.getChannelData(0);
    for (var i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
    var src = ctx.createBufferSource(); src.buffer = buf;
    var f = ctx.createBiquadFilter(); f.type = 'bandpass';
    f.frequency.value = isOn ? 2800 : 1200; f.Q.value = 15;
    var g = ctx.createGain();
    g.gain.setValueAtTime(0.5, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.04);
    src.connect(f); f.connect(g); g.connect(ctx.destination);
    src.start(t); src.stop(t + 0.04);
}

// 6. 水滴
function _sndDrop(ctx, t, isOn) {
    var o = ctx.createOscillator(); var g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = 'sine';
    o.frequency.setValueAtTime(isOn ? 1800 : 1200, t);
    o.frequency.exponentialRampToValueAtTime(isOn ? 600 : 400, t + 0.06);
    g.gain.setValueAtTime(0.2, t);
    g.gain.setValueAtTime(0.12, t + 0.01);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.15);
    o.start(t); o.stop(t + 0.15);
}

// 7. 弹簧
function _sndSpring(ctx, t, isOn) {
    var o = ctx.createOscillator(); var g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = 'sine';
    var base = isOn ? 300 : 600;
    for (var i = 0; i < 6; i++) {
        var tt = t + i * 0.02;
        o.frequency.setValueAtTime(base + (isOn ? i * 80 : -i * 60), tt);
    }
    g.gain.setValueAtTime(0.15, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.12);
    o.start(t); o.stop(t + 0.12);
}

// 8. 激光
function _sndLaser(ctx, t, isOn) {
    var o = ctx.createOscillator(); var g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = 'sawtooth';
    o.frequency.setValueAtTime(isOn ? 400 : 2000, t);
    o.frequency.exponentialRampToValueAtTime(isOn ? 2000 : 200, t + 0.1);
    g.gain.setValueAtTime(0.12, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + 0.12);
    o.start(t); o.stop(t + 0.12);
}

// 工具：快速创建单音
function _tone(ctx, t, freq, type, vol, dur) {
    var o = ctx.createOscillator(); var g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = type; o.frequency.value = freq;
    g.gain.setValueAtTime(vol, t);
    g.gain.exponentialRampToValueAtTime(0.001, t + dur);
    o.start(t); o.stop(t + dur);
}

// 动态定位悬浮窗（规避父级 overflow-hidden）
function positionDropdown(trigger, popup) {
    if (!trigger || !popup) return;
    var rect = trigger.getBoundingClientRect();
    // 计算屏幕剩余高度，防超出
    var spaceBelow = window.innerHeight - rect.bottom;
    var spaceAbove = rect.top;
    var popHeight = 224; // .max-h-56 的高度约 224px

    if (spaceBelow < popHeight && spaceAbove > spaceBelow) {
        // 向上展开
        popup.style.top = 'auto';
        popup.style.bottom = (window.innerHeight - rect.top + 4) + 'px';
        popup.style.transformOrigin = 'bottom';
    } else {
        // 向下展开
        popup.style.top = (rect.bottom + 4) + 'px';
        popup.style.bottom = 'auto';
        popup.style.transformOrigin = 'top';
    }

    popup.style.left = rect.left + 'px';
    popup.style.minWidth = rect.width + 'px';
}

// 下载文本文件
function downloadTextFile(fileName, content) {
    var blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

window.initExcelGridClipboard = function (element, dotNetHelper) {
    if (!element) return;
    element.addEventListener('paste', async function (e) {
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
        let text = (e.clipboardData || window.clipboardData).getData('text');
        if (text) {
            await dotNetHelper.invokeMethodAsync('OnPasteData', text);
            e.preventDefault();
        }
    });
    element.addEventListener('copy', async function (e) {
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
        let text = await dotNetHelper.invokeMethodAsync('OnCopyData');
        if (text) {
            e.clipboardData.setData('text', text);
            e.preventDefault();
        }
    });
};