package com.qnfhq.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qnfhq.common.service.impl.BaseServiceImpl;
import com.qnfhq.common.utils.IpUtils;
import com.qnfhq.modules.user.dao.AppuserLoginLogDao;
import com.qnfhq.modules.user.entity.AppUserEntity;
import com.qnfhq.modules.user.entity.AppuserLoginLogEntity;
import com.qnfhq.modules.user.service.AppuserLoginLogService;
import cn.hutool.core.util.StrUtil;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;

/**
 * 系统访问记录
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-11
 */
@Service
public class AppuserLoginLogServiceImpl extends BaseServiceImpl<AppuserLoginLogDao, AppuserLoginLogEntity> implements AppuserLoginLogService {

    private static final Logger logger = LoggerFactory.getLogger(AppuserLoginLogServiceImpl.class);

    public QueryWrapper<AppuserLoginLogEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<AppuserLoginLogEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public void insertAppActionLog(AppUserEntity user, String msg, String status, HttpServletRequest request) {
        AppuserLoginLogEntity log = new AppuserLoginLogEntity();
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        log.setUserId(user.getId());
        log.setUsername(user.getLoginName());
        String ip = IpUtils.getIpAddr(request);
        log.setIpaddr(ip);
        try {
            log.setLoginLocation(IpUtils.getCityInfo(ip));
        } catch (Exception e) {
            logger.error("error in IpUtils.getCityInfo:"+e.getMessage());
        }
        log.setBrowser(browser);
        log.setOs(os);
        log.setMsg(msg);
        log.setStatus(status);
        log.setLoginTime(new Date());
        baseDao.insert(log);
    }

}