/**
 * 设置 Cookie
 * @param {string} name - Cookie 名称
 * @param {any} value - Cookie 值
 * @param {number} days - 过期天数，默认7天
 */
export const setCookie = (name, value, days = 7) => {
    const expires = new Date();
    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(JSON.stringify(value))};expires=${expires.toUTCString()};path=/`;
};

/**
 * 获取 Cookie
 * @param {string} name - Cookie 名称
 * @returns {any|null} Cookie 值或 null
 */
export const getCookie = (name) => {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) {
            try {
                return JSON.parse(decodeURIComponent(c.substring(nameEQ.length, c.length)));
            } catch (e) {
                return null;
            }
        }
    }
    return null;
};

/**
 * 删除 Cookie
 * @param {string} name - Cookie 名称
 */
export const removeCookie = (name) => {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
};

/**
 * 检查 Cookie 是否存在
 * @param {string} name - Cookie 名称
 * @returns {boolean} 是否存在
 */
export const hasCookie = (name) => {
    return getCookie(name) !== null;
};

export default {
    setCookie,
    getCookie,
    removeCookie,
    hasCookie
};