// Toast 提示函数
function showToast(message, type = 'info', duration = 3000) {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;

    const icons = {
        success: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M20 6L9 17L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        error: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
        info: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/><path d="M12 16V12M12 8H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
    };

    toast.innerHTML = `
        <span class="toast-icon">${icons[type]}</span>
        <span>${message}</span>
    `;

    container.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('hiding');
        setTimeout(() => {
            container.removeChild(toast);
        }, 300);
    }, duration);
}

// MD5 哈希函数
function md5(string) {
    function rotateLeft(x, n) {
        return (x << n) | (x >>> (32 - n));
    }

    function addUnsigned(x, y) {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF);
        var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }

    function F(x, y, z) { return (x & y) | ((~x) & z); }
    function G(x, y, z) { return (x & z) | (y & (~z)); }
    function H(x, y, z) { return (x ^ y ^ z); }
    function I(x, y, z) { return (y ^ (x | (~z))); }

    function FF(a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    }

    function GG(a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    }

    function HH(a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    }

    function II(a, b, c, d, x, s, ac) {
        a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
        return addUnsigned(rotateLeft(a, s), b);
    }

    function convertToWordArray(string) {
        var wordArray = [];
        for (var i = 0; i < string.length * 8; i += 8) {
            wordArray[i >> 5] |= (string.charCodeAt(i / 8) & 0xFF) << (i % 32);
        }
        return wordArray;
    }

    function utf8Encode(string) {
        string = string.replace(/\r\n/g, '\n');
        var output = '';
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                output += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                output += String.fromCharCode((c >> 6) | 192);
                output += String.fromCharCode((c & 63) | 128);
            } else {
                output += String.fromCharCode((c >> 12) | 224);
                output += String.fromCharCode(((c >> 6) & 63) | 128);
                output += String.fromCharCode((c & 63) | 128);
            }
        }
        return output;
    }

    function wordToHex(value) {
        var hexTab = '0123456789abcdef';
        var str = '';
        for (var i = 0; i <= 3; i++) {
            str += hexTab.charAt((value >> (i * 8 + 4)) & 0x0F) + hexTab.charAt((value >> (i * 8)) & 0x0F);
        }
        return str;
    }

    function md5Core(x, len) {
        x[len >> 5] |= 0x80 << (len % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;

        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;

        for (var i = 0; i < x.length; i += 16) {
            var oldA = a;
            var oldB = b;
            var oldC = c;
            var oldD = d;

            a = FF(a, b, c, d, x[i + 0], 7, -680876936);
            d = FF(d, a, b, c, x[i + 1], 12, -389564586);
            c = FF(c, d, a, b, x[i + 2], 17, 606105819);
            b = FF(b, c, d, a, x[i + 3], 22, -1044525330);
            a = FF(a, b, c, d, x[i + 4], 7, -176418897);
            d = FF(d, a, b, c, x[i + 5], 12, 1200080426);
            c = FF(c, d, a, b, x[i + 6], 17, -1473231341);
            b = FF(b, c, d, a, x[i + 7], 22, -45705983);
            a = FF(a, b, c, d, x[i + 8], 7, 1770035416);
            d = FF(d, a, b, c, x[i + 9], 12, -1958414417);
            c = FF(c, d, a, b, x[i + 10], 17, -42063);
            b = FF(b, c, d, a, x[i + 11], 22, -1990404162);
            a = FF(a, b, c, d, x[i + 12], 7, 1804603682);
            d = FF(d, a, b, c, x[i + 13], 12, -40341101);
            c = FF(c, d, a, b, x[i + 14], 17, -1502002290);
            b = FF(b, c, d, a, x[i + 15], 22, 1236535329);

            a = GG(a, b, c, d, x[i + 1], 5, -165796510);
            d = GG(d, a, b, c, x[i + 6], 9, -1069501632);
            c = GG(c, d, a, b, x[i + 11], 14, 643717713);
            b = GG(b, c, d, a, x[i + 0], 20, -373897302);
            a = GG(a, b, c, d, x[i + 5], 5, -701558691);
            d = GG(d, a, b, c, x[i + 10], 9, 38016083);
            c = GG(c, d, a, b, x[i + 15], 14, -660478335);
            b = GG(b, c, d, a, x[i + 4], 20, -405537848);
            a = GG(a, b, c, d, x[i + 9], 5, 568446438);
            d = GG(d, a, b, c, x[i + 14], 9, -1019803690);
            c = GG(c, d, a, b, x[i + 3], 14, -187363961);
            b = GG(b, c, d, a, x[i + 8], 20, 1163531501);
            a = GG(a, b, c, d, x[i + 13], 5, -1444681467);
            d = GG(d, a, b, c, x[i + 2], 9, -51403784);
            c = GG(c, d, a, b, x[i + 7], 14, 1735328473);
            b = GG(b, c, d, a, x[i + 12], 20, -1926607734);

            a = HH(a, b, c, d, x[i + 5], 4, -378558);
            d = HH(d, a, b, c, x[i + 8], 11, -2022574463);
            c = HH(c, d, a, b, x[i + 11], 16, 1839030562);
            b = HH(b, c, d, a, x[i + 14], 23, -35309556);
            a = HH(a, b, c, d, x[i + 1], 4, -1530992060);
            d = HH(d, a, b, c, x[i + 4], 11, 1272893353);
            c = HH(c, d, a, b, x[i + 7], 16, -155497632);
            b = HH(b, c, d, a, x[i + 10], 23, -1094730640);
            a = HH(a, b, c, d, x[i + 13], 4, 681279174);
            d = HH(d, a, b, c, x[i + 0], 11, -358537222);
            c = HH(c, d, a, b, x[i + 3], 16, -722521979);
            b = HH(b, c, d, a, x[i + 6], 23, 76029189);
            a = HH(a, b, c, d, x[i + 9], 4, -640364487);
            d = HH(d, a, b, c, x[i + 12], 11, -421815835);
            c = HH(c, d, a, b, x[i + 15], 16, 530742520);
            b = HH(b, c, d, a, x[i + 2], 23, -995338651);

            a = II(a, b, c, d, x[i + 0], 6, -198630844);
            d = II(d, a, b, c, x[i + 7], 10, 1126891415);
            c = II(c, d, a, b, x[i + 14], 15, -1416354905);
            b = II(b, c, d, a, x[i + 5], 21, -57434055);
            a = II(a, b, c, d, x[i + 12], 6, 1700485571);
            d = II(d, a, b, c, x[i + 3], 10, -1894986606);
            c = II(c, d, a, b, x[i + 10], 15, -1051523);
            b = II(b, c, d, a, x[i + 1], 21, -2054922799);
            a = II(a, b, c, d, x[i + 8], 6, 1873313359);
            d = II(d, a, b, c, x[i + 15], 10, -30611744);
            c = II(c, d, a, b, x[i + 6], 15, -1560198380);
            b = II(b, c, d, a, x[i + 13], 21, 1309151649);
            a = II(a, b, c, d, x[i + 4], 6, -145523070);
            d = II(d, a, b, c, x[i + 11], 10, -1120210379);
            c = II(c, d, a, b, x[i + 2], 15, 718787259);
            b = II(b, c, d, a, x[i + 9], 21, -343485551);

            a = addUnsigned(a, oldA);
            b = addUnsigned(b, oldB);
            c = addUnsigned(c, oldC);
            d = addUnsigned(d, oldD);
        }

        return wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
    }

    function md5Hash(string) {
        string = utf8Encode(string);
        var x = convertToWordArray(string);
        return md5Core(x, string.length * 8);
    }

    return md5Hash(string);
}

// Base64 编码
function base64Encode(str) {
    return btoa(unescape(encodeURIComponent(str)));
}

// 登录功能
document.getElementById('login-btn').addEventListener('click', function() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const loginBtn = document.getElementById('login-btn');
    
    if (!username || !password) {
        showToast('请填写用户名和密码', 'error');
        return;
    }
    
    // 显示加载状态
    loginBtn.textContent = '登录中...';
    loginBtn.disabled = true;
    
    // 对密码进行base64编码，然后用md5生成固定32位小写字符
    const base64Password = base64Encode(password);
    const md5Password = md5(base64Password).toLowerCase();
    
    console.log('发送登录请求:', { username, md5Password });
    
    // 调用登录 API
    fetch('/ask/login.api', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: md5Password
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 登录成功，保存令牌
            localStorage.setItem('token', data.data.token);
            localStorage.setItem('user', JSON.stringify(data.data.user));
            showToast('登录成功！', 'success');
            // 延迟跳转到记账本主页，让用户看到提示
            setTimeout(() => {
                window.location.href = 'index.html';
            }, 1000);
        } else {
            // 登录失败
            showToast(data.msg || '登录失败', 'error');
            console.log('登录失败:', data.msg);
        }
    })
    .catch(error => {
        showToast('网络错误，请重试', 'error');
        console.error('登录错误:', error);
    })
    .finally(() => {
        // 恢复按钮状态
        loginBtn.textContent = '登录';
        loginBtn.disabled = false;
    });
});

// 回车登录
document.getElementById('password').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        document.getElementById('login-btn').click();
    }
});
