// 登录请求参数
interface LoginRequest {
    Account: string;
    Password: string;
}

// 登录响应数据
interface LoginResponse {
    IsNeedSendSMS: boolean;
    Token: string;
    Cookies: Array<{ Key: string, Value: string }>;
}

// API 响应类型
interface ApiResponse<T = any> {
    status: number;
    code: number;
    msg: string;
    data: T;
}


// 设置Cookie的示例
const setCookies = async (cookieString: string) => {
  try {
    await window.electronAPI.setCookie(cookieString);
    console.log('Cookies设置成功');
  } catch (error) {
    console.error('设置Cookies失败:', error);
  }
};

// 使用示例
// setCookies('key1=value1; key2=value2; key3=value3'); 

// 登录处理函数
async function handleLogin(account: string, password: string): Promise<void> {
    const errorMessage = document.getElementById('errorMessage') as HTMLDivElement;

    if (!account || !password) {
        errorMessage.style.display = 'block';
        errorMessage.textContent = '请输入账号和密码';
        return;
    }

    try {
        const response = await fetch('http://1.12.73.211:8848/EIAC_Desktop_Api/api/Auth/Login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                Account: account,
                Password: password
            } as LoginRequest)
        });

        const rspBody = await response.json() as ApiResponse<LoginResponse>;

        if (rspBody.status !== 0) {
            errorMessage.style.display = 'block';
            errorMessage.textContent = rspBody.msg || '登录失败';
        } else {
            // 登录成功，将data.Cookies拼接为字符串，存储cookie
            const cookies = rspBody.data.Cookies.map(cookie => `${cookie.Key.trim()}=${cookie.Value.trim()}`).join('; ');
            await setCookies(cookies);
            // 跳转到主页面
            window.location.href = 'index.html';
        }
    } catch (error) {
        errorMessage.style.display = 'block';
        errorMessage.textContent = '网络错误，请稍后重试';
    }
}

// 页面加载完成后绑定事件
document.addEventListener('DOMContentLoaded', () => {
    const loginButton = document.getElementById('btnLogin');
    if (loginButton) {
        loginButton.addEventListener('click', () => {
            const account = (document.getElementById('txtAccount') as HTMLInputElement).value;
            const password = (document.getElementById('txtPassword') as HTMLInputElement).value;
            handleLogin(account, password);
        });
    }
}); 