export function setToken(token) {
    localStorage.setItem('token', token);
}

export function getToken() {
    return localStorage.getItem('token');
}

export function removeToken() {
    localStorage.removeItem('token');
}

export function setUser(user) {
    localStorage.setItem('user', JSON.stringify(user));
}

export function getUser() {
    return JSON.parse(localStorage.getItem('user'));
}

export function setNumData(numData) {
    localStorage.setItem('num', JSON.stringify(numData));
}
export function getNumData() {
    return JSON.parse(localStorage.getItem('num'));
}

// 导出一个函数，用于设置用户密码
export function setUserPass(userdata) {
    localStorage.setItem('userPass', JSON.stringify(userdata));
}
// 导出一个函数，用于获取用户密码
export function getUserPass() {
    return JSON.parse(localStorage.getItem('userPass'));
}

// 用于设置tk账户密码
export function setTkUser(userdata) {
    localStorage.setItem('tkuser', JSON.stringify(userdata));
}
// 用于获取tk账户密码
export function getTkUser() {
    return JSON.parse(localStorage.getItem('tkuser'));
}

// 用于列表筛选条件
export function setSerch(data) {
    localStorage.setItem('Serch', JSON.stringify(data));
}
// 用于获取列表筛选条件
export function getSerch() {
    return JSON.parse(localStorage.getItem('Serch'));
}

// ==================== 权限管理 ====================

const PERMISSIONS_KEY = 'user_permissions';

/**
 * 存储权限信息
 * @param {Object} permissions - 权限对象 { bigBrother, crawl, webAi, autotk }
 */
export function setPermissions(permissions) {
    const autotkValue = permissions.autotk ?? permissions.autoTK ?? 0;
    localStorage.setItem(PERMISSIONS_KEY, JSON.stringify({
        bigBrother: permissions.bigBrother ?? 0,
        crawl: permissions.crawl ?? 0,
        webAi: permissions.webAi ?? 0,
        autotk: autotkValue,
    }));
}

/**
 * 获取权限信息
 * @returns {Object} 权限对象 { bigBrother, crawl, webAi, autotk }
 */
export function getPermissions() {
    try {
        const permissions = JSON.parse(localStorage.getItem(PERMISSIONS_KEY));
        return permissions || { bigBrother: 0, crawl: 0, webAi: 0, autotk: 0 };
    } catch {
        return { bigBrother: 0, crawl: 0, webAi: 0, autotk: 0 };
    }
}

/**
 * 清除权限信息
 */
export function clearPermissions() {
    localStorage.removeItem(PERMISSIONS_KEY);
}

/**
 * 检查特定权限
 * @param {string} permissionKey - 'bigBrother' | 'crawl' | 'webAi'
 * @returns {boolean} 是否有权限
 */
export function hasPermission(permissionKey) {
    const permissions = getPermissions();
    return permissions[permissionKey] === 1;
}
