/**
 * Admin Console - Auth
 * 认证模块（登录、Token 管理、权限检查）
 */

const Auth = {
    /**
     * 获取 Token
     * @returns {string|null}
     */
    getToken() {
        return Utils.storage.get(CONFIG.STORAGE_KEYS.TOKEN);
    },

    /**
     * 设置 Token
     * @param {string} token
     */
    setToken(token) {
        Utils.storage.set(CONFIG.STORAGE_KEYS.TOKEN, token);
    },

    getRefreshToken() {
        return Utils.storage.get(CONFIG.STORAGE_KEYS.REFRESH_TOKEN);
    },

    setRefreshToken(refreshToken) {
        Utils.storage.set(CONFIG.STORAGE_KEYS.REFRESH_TOKEN, refreshToken);
    },

    /**
     * 清除 Token
     */
    clearToken() {
        Utils.storage.remove(CONFIG.STORAGE_KEYS.TOKEN);
    },

    clearRefreshToken() {
        Utils.storage.remove(CONFIG.STORAGE_KEYS.REFRESH_TOKEN);
    },

    /**
     * 获取用户信息
     * @returns {Object|null}
     */
    getUserInfo() {
        return Utils.storage.get(CONFIG.STORAGE_KEYS.USER_INFO);
    },

    /**
     * 设置用户信息
     * @param {Object} userInfo
     */
    setUserInfo(userInfo) {
        Utils.storage.set(CONFIG.STORAGE_KEYS.USER_INFO, userInfo);
    },

    /**
     * 清除用户信息
     */
    clearUserInfo() {
        Utils.storage.remove(CONFIG.STORAGE_KEYS.USER_INFO);
    },

    /**
     * 获取权限
     * @returns {Array}
     */
    getPermissions() {
        return Utils.storage.get(CONFIG.STORAGE_KEYS.PERMISSIONS) || [];
    },

    /**
     * 设置权限
     * @param {Array} permissions
     */
    setPermissions(permissions) {
        Utils.storage.set(CONFIG.STORAGE_KEYS.PERMISSIONS, permissions);
    },

    /**
     * 清除权限
     */
    clearPermissions() {
        Utils.storage.remove(CONFIG.STORAGE_KEYS.PERMISSIONS);
    },

    /**
     * 同步清理本地会话
     */
    clearSession() {
        this.clearToken();
        this.clearRefreshToken();
        this.clearUserInfo();
        this.clearPermissions();
    },

    /**
     * 检查是否已登录
     * @returns {boolean}
     */
    isLoggedIn() {
        return !!this.getToken();
    },

    /**
     * 检查本地会话是否可用
     * 只存在 token 不代表会话完整，必须同时有用户信息。
     * @returns {boolean}
     */
    isSessionUsable() {
        return !!this.getToken() && !!this.getUserInfo();
    },

    /**
     * 会话失效处理：不弹确认框，立即清理并跳登录页
     */
    expireSession() {
        if (this._expiringSession) return;
        this._expiringSession = true;
        this.clearSession();

        if (typeof Components !== 'undefined' && Components.showToast) {
            Components.showToast('登录已过期，请重新登录', 'warning', 1500);
        }

        if (window.location.pathname !== CONFIG.ROUTES.LOGIN) {
            window.location.replace(CONFIG.ROUTES.LOGIN);
        }
    },

    /**
     * 检查是否是管理员
     * @returns {boolean}
     */
    isAdmin() {
        return this.hasRole('ADMIN');
    },

    /**
     * 检查是否是授权用户
     * @returns {boolean}
     */
    isAuthorized() {
        return this.hasRole(['ADMIN', 'AUTHORIZED']);
    },

    isSales() {
        return this.hasRole('SALES');
    },

    isDelivery() {
        return this.hasRole('DELIVERY');
    },

    getUserRoles() {
        const userInfo = this.getUserInfo();
        if (!userInfo) return [];
        if (Array.isArray(userInfo.roles) && userInfo.roles.length > 0) {
            return userInfo.roles;
        }
        return userInfo.role ? [userInfo.role] : [];
    },

    hasRole(roles) {
        const userRoles = this.getUserRoles();
        if (userRoles.length === 0) return false;

        if (Array.isArray(roles)) {
            return roles.some(role => userRoles.includes(role));
        }
        return userRoles.includes(roles);
    },

    can(permissionName) {
        const roles = CONFIG.PERMISSIONS && CONFIG.PERMISSIONS[permissionName];
        if (!roles) return false;
        return this.hasRole(roles);
    },

    /**
     * 检查是否有权限访问菜单项
     * @param {Object} menuItem
     * @returns {boolean}
     */
    canAccessMenu(menuItem) {
        if (!menuItem.roles || menuItem.roles.length === 0) {
            return true;
        }
        return this.hasRole(menuItem.roles);
    },

    /**
     * 登录
     * @param {string} username
     * @param {string} password
     * @returns {Promise}
     */
    async login(username, password) {
        try {
            const response = await API.auth.login(username, password);

            if (response.success && response.data) {
                const { token, refreshToken, userInfo, permissions } = response.data;

                // 保存登录信息
                this.setToken(token);
                if (refreshToken) {
                    this.setRefreshToken(refreshToken);
                }
                this.setUserInfo(userInfo);
                if (permissions) {
                    this.setPermissions(permissions);
                }

                return {
                    success: true,
                    data: response.data
                };
            } else {
                return {
                    success: false,
                    message: response.message || '登录失败'
                };
            }
        } catch (error) {
            // 将网络错误转换为中文提示
            let errorMessage = error.message || '登录失败，请检查网络连接';
            if (errorMessage === 'Failed to fetch') {
                errorMessage = '无法连接到服务器，请检查网络连接';
            } else if (errorMessage.includes('NetworkError')) {
                errorMessage = '网络错误，请检查网络连接';
            } else if (errorMessage.includes('timeout')) {
                errorMessage = '请求超时，请稍后重试';
            }
            return {
                success: false,
                message: errorMessage
            };
        }
    },

    /**
     * 登出
     * @param {HTMLElement} btnElement - 触发退出的按钮元素（可选，用于显示加载状态）
     * @param {boolean} showConfirm - 是否显示确认对话框（默认为true）
     */
    logout(btnElement, showConfirm = true) {
        // 显示确认对话框
        if (showConfirm && typeof Components !== 'undefined' && Components.confirm) {
            Components.confirm({
                title: '退出登录',
                message: '确定要退出登录吗？',
                onConfirm: () => {
                    this._performLogout(btnElement);
                }
            });
        } else {
            this._performLogout(btnElement);
        }
    },

    /**
     * 执行登出操作（内部方法）
     * @param {HTMLElement} btnElement - 触发退出的按钮元素
     */
    _performLogout(btnElement) {
        // 如果提供了按钮元素，显示加载状态
        if (btnElement) {
            btnElement.disabled = true;
            btnElement.classList.add('loading');
            const originalText = btnElement.innerHTML;
            // 使用更简洁的文字，配合更宽的按钮
            btnElement.innerHTML = '<span class="btn-spinner"></span>退出中';
            btnElement.dataset.originalText = originalText;
        }

        // 显示退出提示
        if (typeof Components !== 'undefined' && Components.showToast) {
            Components.showToast('正在退出登录...', 'info', 1500);
        }

        // 添加页面淡出动画
        document.body.style.transition = 'opacity 0.5s ease-out';
        document.body.style.opacity = '0.5';

        // 延迟执行登出操作，让用户看到动画效果
        setTimeout(async () => {
            try {
                await API.auth.logout();
            } catch (error) {
                console.warn('登出接口调用失败，已继续清理本地会话', error);
            } finally {
                this.clearSession();
                window.location.href = CONFIG.ROUTES.LOGIN;
            }
        }, 500);
    },

    /**
     * 页面权限检查
     * 在页面加载时调用，检查用户是否有权限访问当前页面
     * @param {Array} requiredRoles - 需要的角色
     */
    checkPermission(requiredRoles = []) {
        // 未登录，跳转到登录页
        if (!this.isLoggedIn()) {
            this.clearSession();
            window.location.replace(CONFIG.ROUTES.LOGIN);
            return false;
        }

        // 获取当前用户信息
        const userInfo = this.getUserInfo();
        if (!userInfo) {
            // 用户信息不存在，清除登录状态并跳转
            this.clearSession();
            window.location.replace(CONFIG.ROUTES.LOGIN);
            return false;
        }

        // 需要特定角色
        const roleList = Array.isArray(requiredRoles) ? requiredRoles : (requiredRoles ? [requiredRoles] : []);
        if (roleList.length > 0 && !this.hasRole(roleList)) {
            // 无权限，显示提示并跳转到无权限页面或首页
            Components.showToast('您没有权限访问此页面', 'error');
            setTimeout(() => {
                window.location.href = CONFIG.ROUTES.DASHBOARD;
            }, 1500);
            return false;
        }

        return true;
    },

    /**
     * 初始化认证状态
     * 在页面加载时调用
     */
    init() {
        // 检查是否在登录页（支持 index.html 和 login.html）
        const pathname = window.location.pathname;
        const isLoginPage = pathname.includes('index.html') ||
                           pathname.includes('login.html') ||
                           pathname.endsWith('/admin/');

        if (isLoginPage) {
            // 登录页，如果已登录则跳转到首页
            if (this.isSessionUsable()) {
                window.location.replace(CONFIG.ROUTES.DASHBOARD);
            } else if (this.isLoggedIn()) {
                this.clearSession();
            }
            return;
        }

        // 非登录页，检查是否已登录
        if (!this.isSessionUsable()) {
            this.clearSession();
            window.location.replace(CONFIG.ROUTES.LOGIN);
            return;
        }

        // 更新页面上的用户信息
        this.updateUserInfoUI();
    },

    /**
     * 更新页面上的用户信息 UI
     */
    updateUserInfoUI() {
        const userInfo = this.getUserInfo();
        if (!userInfo) return;

        const userName = userInfo.nickName || userInfo.username || '管理员';
        const roleConfig = CONFIG.ROLES[userInfo.role];
        const roleName = roleConfig ? roleConfig.label : userInfo.role;

        // 更新侧边栏用户名
        const userNameElements = document.querySelectorAll('.user-name');
        userNameElements.forEach(el => {
            el.textContent = userName;
        });

        // 更新侧边栏角色标签
        const userRoleElements = document.querySelectorAll('.user-role');
        userRoleElements.forEach(el => {
            el.textContent = roleName;
        });

        // 更新侧边栏角色标签（role-tag）
        const roleTagElements = document.querySelectorAll('.role-tag');
        roleTagElements.forEach(el => {
            el.textContent = roleName;

            // 根据角色添加不同的样式类
            el.className = 'role-tag';
            if (userInfo.role === 'ADMIN') {
                el.classList.add('admin');
            } else if (userInfo.role === 'AUTHORIZED') {
                el.classList.add('authorized');
            } else if (userInfo.role === 'SALES') {
                el.classList.add('sales');
            } else if (userInfo.role === 'DELIVERY') {
                el.classList.add('delivery');
            }
        });

        // 更新侧边栏用户头像
        const userAvatarElements = document.querySelectorAll('.user-avatar');
        userAvatarElements.forEach(el => {
            el.textContent = userName.charAt(0).toUpperCase();
        });

        // 更新顶部栏用户信息
        const headerUserName = document.getElementById('headerUserName');
        if (headerUserName) {
            headerUserName.textContent = userName;
        }

        const headerUserRole = document.getElementById('headerUserRole');
        if (headerUserRole) {
            headerUserRole.textContent = roleName;
            // 根据角色添加不同的样式类
            headerUserRole.className = 'header-role-tag';
            if (userInfo.role === 'ADMIN') {
                headerUserRole.classList.add('admin');
            } else if (userInfo.role === 'AUTHORIZED') {
                headerUserRole.classList.add('authorized');
            } else if (userInfo.role === 'SALES') {
                headerUserRole.classList.add('sales');
            } else if (userInfo.role === 'DELIVERY') {
                headerUserRole.classList.add('delivery');
            }
        }

        // 绑定侧边栏退出登录按钮事件
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.logout(logoutBtn);
            });
        }

        // 绑定顶部栏退出登录按钮事件
        const headerLogoutBtn = document.getElementById('headerLogoutBtn');
        if (headerLogoutBtn) {
            headerLogoutBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.logout(headerLogoutBtn);
            });
        }
    },

    /**
     * 获取当前用户信息（兼容方法，等同于 getUserInfo）
     * @returns {Object|null}
     */
    getCurrentUser() {
        return this.getUserInfo();
    }
};

// 导出 Auth
window.Auth = Auth;
