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.KwpGoodsViewLogMapper;
import com.sckw.product.model.KwpGoodsViewLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author xucaiqin
 * @date 2025-11-14 09:19:22
 */
@Service
@RequiredArgsConstructor
public class KwpGoodsViewLogService {

    private final KwpGoodsViewLogMapper kwpGoodsViewLogMapper;

    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(Long id, String name, String goodsType,String keywords, Integer source, HttpServletRequest request) {
        KwpGoodsViewLog kwpGoodsViewLog = new KwpGoodsViewLog();
        kwpGoodsViewLog.setId(new IdWorker(1).nextId());
        kwpGoodsViewLog.setEntId(LoginUserHolder.getEntId());
        kwpGoodsViewLog.setUserId(LoginUserHolder.getUserId());
        kwpGoodsViewLog.setSearchWords(keywords);
        kwpGoodsViewLog.setGoodsId(id);
        kwpGoodsViewLog.setGoodsName(name);
        kwpGoodsViewLog.setGoodsType(goodsType);
        kwpGoodsViewLog.setSource(source);
        kwpGoodsViewLog.setUserAgent(parseUserAgent(request));
        kwpGoodsViewLog.setIpAddress(JakartaServletUtil.getClientIP(request));
        kwpGoodsViewLog.setSearchTime(LocalDateTime.now());
        kwpGoodsViewLog.setCreateBy(LoginUserHolder.getUserId());
        kwpGoodsViewLog.setCreateTime(LocalDateTime.now());
        kwpGoodsViewLog.setDelFlag(0);
        kwpGoodsViewLogMapper.insert(kwpGoodsViewLog);
    }


}
