package com.sckw.product.service;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.product.dao.KwpSearchLogMapper;
import com.sckw.product.model.KwpSearchLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author xucaiqin
 * @date 2025-11-13 14:19:42
 */
@Service
@RequiredArgsConstructor
public class KwpSearchLogService {

    private final KwpSearchLogMapper kwpSearchLogMapper;

    private String parseUserAgent(HttpServletRequest request) {
        String userAgentStr = request.getHeader("User-Agent");

        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);

        // 3. 提取关键信息
        String browser = userAgent.getBrowser().getName(); // 浏览器名称（如 Chrome、Edge）
        String browserVersion = userAgent.getVersion(); // 浏览器版本
        String os = userAgent.getOs().getName(); // 操作系统（如 Windows 10、macOS、iOS）
        String device = userAgent.getPlatform().getName(); // 设备类型（如 PC、iPhone、Android）

        // 输出示例：Chrome 120.0.0.0 / Windows 10 / PC
        return String.format("%s %s / %s / %s", browser, browserVersion, os, device);
    }

    public void saveLog(String keywords, Integer source, HttpServletRequest request) {
        KwpSearchLog kwpSearchLog = new KwpSearchLog();
        kwpSearchLog.setId(new IdWorker(1).nextId());
        kwpSearchLog.setEntId(LoginUserHolder.getEntId());
        kwpSearchLog.setUserId(LoginUserHolder.getUserId());
        kwpSearchLog.setKeywords(keywords);
        kwpSearchLog.setSource(source);
        kwpSearchLog.setUserAgent(parseUserAgent(request));
        kwpSearchLog.setIpAddress(JakartaServletUtil.getClientIP(request));
        kwpSearchLog.setSearchTime(LocalDateTime.now());
        kwpSearchLog.setCreateBy(LoginUserHolder.getUserId());
        kwpSearchLog.setCreateTime(LocalDateTime.now());
        kwpSearchLog.setDelFlag(0);
        kwpSearchLogMapper.insert(kwpSearchLog);
    }


}
