package com.backendsys.modules.common.utils;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class CookieUtil {

    private static HttpServletResponse getCurrentResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取 Cookie 的值
     */
    public static String getCookie(String name, HttpServletRequest request) {
        String value = null;
        if (!StringUtils.isEmpty(name)) {
            //ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Cookie[] cks = request.getCookies();
            if (null != cks) {
                for (Cookie cookie : cks) {
                    if (name.equals(cookie.getName())) {
                        value = cookie.getValue();
                    }
                }
            }
        }
        return value;
    }

    /**
     * [Cookie] 获取/设置默认语言 (默认是：中文)
     */
    public static String getCurrentLang(HttpServletRequest request) {
        String lang = CookieUtil.getCookie("lang", request);
        String default_lang = "zh";
        if (StrUtil.isEmpty(lang)) {
            lang = default_lang;
            CookieUtil.setCookie("lang", lang);
        }
        request.setAttribute("lang", lang);
        return lang;
    }

    /**
     * 设置 Cookie 的值
     * @param name Cookie 名称
     * @param value Cookie 值
     */
    public static void setCookie(String name, String value) {
        HttpServletResponse response = getCurrentResponse();
        if (!StringUtils.isEmpty(name) && value != null) {
            Cookie cookie = new Cookie(name, value);
            cookie.setMaxAge(-1);
            cookie.setPath("/"); // 设置路径为根路径，使 Cookie 在整个域名下有效
            response.addCookie(cookie);
        }
    }

    /**
     * 删除 cookie
     */
    public static void delCookie(String name, HttpServletRequest request) {
        if (!StringUtils.isEmpty(name)) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Cookie[] cks = request.getCookies();
            if (null != cks) {
                for (Cookie cookie : cks) {
                    if (name.equals(cookie.getName())) {
                        Cookie c = new Cookie(name, null);
                        c.setPath("/");
                        c.setMaxAge(0);
                        HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                        res.addCookie(c);
                    }
                }
            }
        }
    }
}
