
const inputname = document.getElementById('inputname');
const inputpassword = document.getElementById('inputpassword');
const inputremember = document.getElementById('inputremember');
const phoneInput = document.getElementById('reg-input-tel');
const regInputCode = document.getElementById('reg-input-code');
const myModal = document.getElementById('myModal');

// let mainApiUrl = 'http://127.0.0.1:10000';
let mainApiUrl = 'https://api.78bar.cn/';

let doingTimeId = null;

document.addEventListener('contextmenu', function(e){
    e.preventDefault();
    return false;
})

document.addEventListener('click', function(e){
    const dropdown = document.getElementById('customDropdown');
    const usernameInput = document.getElementById('inputname');
    const dropdownArrow = document.getElementById('dropdownArrow');
    
    if (!usernameInput.contains(e.target) && !dropdown.contains(e.target) && !dropdownArrow.contains(e.target)) {
        dropdown.classList.remove('show');
    }

})


if (window.electronAPI) {
    window.electronAPI.on('login-err',(errInfo)=>{
        tips(errInfo);
        document.getElementById('loading').style.display = 'none';
    })

    window.electronAPI.on('register-err',(errInfo)=>{
        tips(errInfo);
        document.getElementById('loading').style.display = 'none';
    })
}

function closeDialog() {
    myModal.style.display = 'none';
}

function tips(str) {
    if (doingTimeId) {
        clearTimeout(doingTimeId);
        doingTimeId = null;
    }
    if (str == '0'){
        str = "登录用户名或密码不正确!";
    } else if (str == '1'){
        str = "该账号正在被人使用!";
    } else if (str == '2') {
        str = "该账号被禁止使用!";
    } else if (str == '3') {
        str = "网络繁忙!";
    } else if (str == '4') {
        str = '昵称已经被使用!';
    } else if (str == '5') {
        str = '邮箱已经被使用!';
    } else if (str == '6') {
        str = '你的网络连接不通,请检查你的网络或者稍后再试!'
    }
    var dlgtext = document.getElementById("dlgtext");
    document.querySelector('.dialog-overlay').style.display = 'flex';
    dlgtext.textContent=str
}

function validatePhone(input) {
    input.value = input.value.replace(/[^0-9]/g, '').slice(0, 11);

    const isValid = /^1[3-9]\d{9}$/.test(input.value);
    document.getElementById('getCodeBtn').disabled = !isValid;

}


// 发送验证码的 API 函数
async function sendVerificationCode(phone) {
    try {
        // 构建请求 URL（根据你的测试接口）
        const apiUrl = `${mainApiUrl}/api/sms/getRegCode?mobile=${encodeURIComponent(phone)}`;
        
        console.log('发送验证码请求:', apiUrl);
        
        // 使用 fetch API 发送 GET 请求
        const response = await fetch(apiUrl, {
            method: 'GET',
            mode: 'cors', // 如果跨域需要处理 CORS
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP 错误! 状态码: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('验证码发送响应:', data);
        
        // 根据实际 API 响应结构调整
        if (data.code === 0 || data.success) {
            // 发送成功，返回验证码（实际应用中应该由服务器存储）
            return {
                success: true,
                message: '验证码发送成功'
            };
        } else {
            return {
                success: false,
                message: data.message || '验证码发送失败'
            };
        }
        
    } catch (error) {
        console.error('发送验证码失败:', error);
        return {
            success: false,
            message: `网络错误: ${error.message}`
        };
    }
}

// 验证验证码
async function verifyVerificationCode(phone, code) {
    try {
        // 构建请求 URL（根据你的测试接口）
        const apiUrl = `${mainApiUrl}/api/sms/verifyRegCode?mobile=${encodeURIComponent(phone)}&code=${code}&action=reg`;
        
        console.log('发送验证码请求:', apiUrl);
        
        // 使用 fetch API 发送 GET 请求
        const response = await fetch(apiUrl, {
            method: 'GET',
            mode: 'cors', // 如果跨域需要处理 CORS
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP 错误! 状态码: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('验证码验证发送响应:', data);
        
        // 根据实际 API 响应结构调整
        if (data.code === 0 || data.success) {
            // 发送成功，返回验证码（实际应用中应该由服务器存储）
            return {
                success: true,
                message: '验证码验证成功'
            };
        } else {
            return {
                success: false,
                message: data.message || '验证码验证失败'
            };
        }
        
    } catch (error) {
        console.error('验证码验证失败:', error);
        return {
            success: false,
            message: `网络错误: ${error.message}`
        };
    }
}

let countdown = 0;
async function handleGetCode() {
    if (countdown > 0) return;

    const phone = phoneInput.value;
    if (!/^1[3-9]\d{9}$/.test(phone)) {
        return;
    }

    countdown = 180;
    const btn = document.getElementById('getCodeBtn');
    btn.disabled = true;
    btn.textContent = `${countdown}秒重发`;
    phoneInput.disabled = true;
    regInputCode.disabled = false;
    
    const timer = setInterval(() => {
        countdown--;
        btn.textContent = `${countdown}秒重发`;
        
        if (countdown <= 0) {
            clearInterval(timer);
            btn.textContent = '点击获取';
            btn.disabled = !/^1[3-9]\d{9}$/.test(phone);
            phoneInput.disabled = false;
            regInputCode.disabled = true;
        }
    }, 1000);

    console.log('发送验证码到:', phone);
    let result = await sendVerificationCode(phone);
    console.log('result', result)
    if (!result.success){
        tips(result.message);
    }
}

function onClose() {
    if (window.electronAPI){
        window.electronAPI.send('login-btn-close');
    }
}
function onMin() {
    if (window.electronAPI){
        window.electronAPI.send('login-btn-min');
    }
}
function onSubmit(){
    if (window.electronAPI) {
        document.getElementById('loading').style.display = 'block';
        document.getElementById('loading-login').style.display = 'block';
        document.getElementById('loading-reg').style.display = 'none';
        window.electronAPI.send('login', {account:inputname.value,password:inputpassword.value,remember:inputremember.checked?1:0});

        //设置10秒超时
        doingTimeId = setTimeout(() => {
            tips('你的网络连接不通,请检查你的网络或者稍后再试');
            document.getElementById('loading').style.display = 'none';
        }, 20000);
    }
}
function onBtnEnterRegPage() {
    document.getElementById('regpage').style.display = 'block';
}
function onBtnRegCanel() {
    document.getElementById('regpage').style.display = 'none';
}
async function btnRegConfrim() {
    const regInputName = document.getElementById('reg-input-name');
    const regInputPass = document.getElementById('reg-input-pass');
    const regInputPassConfrim = document.getElementById('reg-input-pass-confirm');
    const regInputSex = document.querySelector('input[name="sex"]:checked');

    
    if (regInputName.value.length  == 0){
        tips("请输入昵称！");
        return;
    }
    
    if (regInputPass.value.length < 6) {
        tips("密码小于6位");
        return;
    }

    
    if (regInputPass.value != regInputPassConfrim.value){
        tips("两次输入密码不相同");
        return;
    }

    
    if (!regInputSex||!regInputSex.value) {
        tips("请选择性别")
        return;
    }

    if(!/^1[3-9]\d{9}$/.test(phoneInput.value)) {
        tips("请输入手机号")
        return;
    }
    
    if (regInputCode.value < 6) {
        tips("请输入验证码")
        return;
    }

    // 验证验证码
    let result = await verifyVerificationCode(phoneInput.value, regInputCode.value);
    if (!result.success) {
        tips(result.message);
        return;
    }


    if (window.electronAPI){
        document.getElementById('loading').style.display = 'block';
        document.getElementById('loading-login').style.display = 'none';
        document.getElementById('loading-reg').style.display = 'block';

        window.electronAPI.send('register', {
            account: regInputName.value,
            password: regInputPass.value,
            male: regInputSex.value,
            tel: phoneInput.value,
            code: regInputCode.value
        })

        //设置10秒超时
        doingTimeId = setTimeout(() => {
            tips('你的网络连接不通,请检查你的网络或者稍后再试');
            document.getElementById('loading').style.display = 'none';
        }, 20000);
    }
}
function onOpenUrl(url, width, height) {
    if (window.electronAPI){
        window.electronAPI.send('login-btn-openurl', {url, width, height});
    }
}
function onOpenUrlOri(url) {
    if (window.electronAPI){
        window.electronAPI.send('login-btn-openurl-ori', url);
    }
}

function updateDatalist(items) {
    const dropdown = document.getElementById('customDropdown');
    dropdown.innerHTML = '';
    
    if (items && items.length > 0) {
        // 反转数组，让最新的账号显示在最上面
        items.forEach(item => {
            const div = document.createElement('div');
            div.className = 'dropdown-item';
            div.textContent = item;
            div.onclick = function() {
                inputname.value = item;
                dropdown.classList.remove('show');
                inputpassword.focus();
            };
            dropdown.appendChild(div);
        });
        
        // 默认显示第一个账号
        inputname.value = items[0];
    }

}

function toggleDropdown() {
    const dropdown = document.getElementById('customDropdown');
    
    // 如果没有下拉项，则不显示
    if (dropdown.children.length === 0) {
        return;
    }
    
    // 使用 toggle 方法切换 show 类
    dropdown.classList.toggle('show');
}

// 添加输入框事件监听
inputname.addEventListener('focus', function() {
    // const dropdown = document.getElementById('customDropdown');
    // if (dropdown.children.length > 0) {
    //     dropdown.classList.add('show');
    // }

});

inputname.addEventListener('input', function() {
    // 输入时不隐藏下拉列表
    // const dropdown = document.getElementById('customDropdown');
    // if (dropdown.children.length > 0) {
    //     dropdown.classList.add('show');
    // }
});

inputname.addEventListener('blur', function() {
    // 延迟隐藏，以便点击选项
    // setTimeout(() => {
    //     const dropdown = document.getElementById('customDropdown');
    //     dropdown.classList.remove('show');
    // }, 200);
});


if (window.electronAPI){
    window.electronAPI.send("accountlistReq");
    window.electronAPI.on('accountlistResponse',(message)=>{
        console.log(message)
        updateDatalist(message.accounts);
        inputname.value = message.accounts[0];
        if (message.password !='') {
            inputpassword.value = message.password;
            inputremember.checked = true;
        }
    })
}
