// 公共JavaScript函数库

// 显示提示信息
function showToast(message, duration = 2000) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, duration);
}

// 显示加载动画
function showLoading() {
    const loading = document.createElement('div');
    loading.className = 'loading';
    loading.id = 'pageLoading';
    loading.innerHTML = '<div class="spinner"></div>';
    document.body.appendChild(loading);
}

// 隐藏加载动画
function hideLoading() {
    const loading = document.getElementById('pageLoading');
    if (loading) {
        loading.remove();
    }
}

// 显示空状态
function showEmptyState(message = '暂无数据', icon = 'fa-inbox') {
    return `
        <div class="empty-state">
            <i class="fas ${icon}"></i>
            <p>${message}</p>
        </div>
    `;
}

// 格式化日期
function formatDate(date, format = 'Y-m-d') {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    
    return format
        .replace('Y', year)
        .replace('m', month)
        .replace('d', day)
        .replace('H', hours)
        .replace('i', minutes);
}

// 格式化周几
function formatWeekDay(weekDay) {
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weekDays[weekDay] || '';
}

// 节次转时间
function sectionToTime(section) {
    const times = {
        1: '08:00',
        2: '08:55',
        3: '09:55',
        4: '10:50',
        5: '11:45',
        6: '14:00',
        7: '14:55',
        8: '15:50',
        9: '16:50',
        10: '17:45',
        11: '19:00',
        12: '19:55',
        13: '20:50'
    };
    return times[section] || '';
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 获取URL参数
function getQueryParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 设置URL参数
function setQueryParam(name, value) {
    const url = new URL(window.location);
    url.searchParams.set(name, value);
    window.history.replaceState({}, '', url);
}

// AJAX请求封装
function ajax(options) {
    const defaults = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        },
        timeout: 10000
    };
    
    const config = { ...defaults, ...options };
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), config.timeout);
    
    return fetch(config.url, {
        method: config.method,
        headers: config.headers,
        body: config.body ? JSON.stringify(config.body) : null,
        signal: controller.signal
    })
    .then(response => {
        clearTimeout(timeoutId);
        return response.json();
    })
    .then(data => {
        if (data.code !== 200) {
            throw new Error(data.message || '请求失败');
        }
        return data.data;
    })
    .catch(error => {
        clearTimeout(timeoutId);
        showToast(error.message || '网络错误，请稍后重试');
        throw error;
    });
}

// 确认对话框
function confirmDialog(message, onConfirm) {
    if (confirm(message)) {
        onConfirm();
    }
}

// 下拉刷新
function initPullRefresh(callback) {
    let startY = 0;
    let isPulling = false;
    
    document.addEventListener('touchstart', (e) => {
        startY = e.touches[0].clientY;
    });
    
    document.addEventListener('touchmove', (e) => {
        const currentY = e.touches[0].clientY;
        const distance = currentY - startY;
        
        if (window.scrollY === 0 && distance > 50 && !isPulling) {
            isPulling = true;
            showLoading();
        }
    });
    
    document.addEventListener('touchend', () => {
        if (isPulling) {
            isPulling = false;
            callback();
        }
    });
}

// 点击波纹效果
function addRippleEffect(element) {
    element.addEventListener('click', function(e) {
        const ripple = document.createElement('span');
        const rect = element.getBoundingClientRect();
        const size = Math.max(rect.width, rect.height);
        const x = e.clientX - rect.left - size / 2;
        const y = e.clientY - rect.top - size / 2;
        
        ripple.style.cssText = `
            position: absolute;
            width: ${size}px;
            height: ${size}px;
            left: ${x}px;
            top: ${y}px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            transform: scale(0);
            animation: ripple 0.6s ease-out;
            pointer-events: none;
        `;
        
        element.style.position = 'relative';
        element.style.overflow = 'hidden';
        element.appendChild(ripple);
        
        setTimeout(() => ripple.remove(), 600);
    });
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes ripple {
        to {
            transform: scale(2);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// 本地存储封装
const storage = {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    
    get(key) {
        const item = localStorage.getItem(key);
        return item ? JSON.parse(item) : null;
    },
    
    remove(key) {
        localStorage.removeItem(key);
    },
    
    clear() {
        localStorage.clear();
    }
};
