package com.jy.log.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.framework.model.constants.CommonConstant;
import com.jy.framework.model.event.AccessEvent;
import com.jy.framework.satoken.AccessInfo;
import com.jy.log.dao.LogAccessDao;
import com.jy.log.model.dto.LogAccessSelectDto;
import com.jy.log.model.entity.LogAccess;
import com.jy.log.model.vo.LogAccessVo;
import com.jy.log.service.LogAccessService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 访问日志 服务实现类
 * </p>
 *
 * @author
 * @since 2024-09-03
 */
@Service
public class LogAccessServiceImpl implements LogAccessService {

    @Resource
    private LogAccessDao logAccessDao;

    @Override
    public Page<LogAccessVo> getPage(LogAccessSelectDto dto) {
        return logAccessDao.getPage(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> idList) {
        logAccessDao.removeBatchByIds(idList);
    }

    @Override
    public void save(AccessEvent event) {
        AccessInfo accessInfo = event.getAccessInfo();
        String username = event.getUsername();
        boolean success = event.isSuccess();
        String message = event.getMessage();

        LogAccess sysAccessLog = new LogAccess();
        sysAccessLog.setUsername(username);
        sysAccessLog.setIp(accessInfo.getIp());
        sysAccessLog.setLocation(accessInfo.getLocation());
        sysAccessLog.setBrowser(accessInfo.getBrowser());
        sysAccessLog.setOs(accessInfo.getOs());
        sysAccessLog.setStatus(success ? CommonConstant.SUCCESS : CommonConstant.FAIL);
        sysAccessLog.setMsg(message);
        sysAccessLog.setAccessTime(accessInfo.getAccessTime());
        logAccessDao.save(sysAccessLog);
    }

}
