package com.jy.log.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jy.framework.model.event.ExceptionEvent;
import com.jy.framework.utils.AssertUtil;
import com.jy.framework.utils.ExceptionUtil;
import com.jy.framework.utils.ServletUtil;
import com.jy.log.dao.LogExceptionDao;
import com.jy.log.model.dto.LogExceptionSelectDto;
import com.jy.log.model.entity.LogException;
import com.jy.log.model.vo.LogExceptionVo;
import com.jy.log.service.LogExceptionService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
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 LogExceptionServiceImpl implements LogExceptionService {

    @Resource
    private HttpServletRequest request;

    @Resource
    private LogExceptionDao logExceptionDao;

    @Override
    public Page<LogExceptionVo> getPage(LogExceptionSelectDto dto) {
        return logExceptionDao.getPage(dto);
    }

    @Override
    public LogExceptionVo getDetail(Long id) {
        LogExceptionVo vo = logExceptionDao.getDetail(id);
        AssertUtil.notNull(vo, "未知数据");
        return vo;
    }

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

    @Override
    public void save(ExceptionEvent event) {
        // 获取请求信息
        String method = request.getMethod();
        String bestMatching = ServletUtil.getBestMatching(request);
        String variable = ServletUtil.getVariable(request);
        String param = ServletUtil.getParam(request);
        String body = ServletUtil.getBody(request);

        // 异常信息
        Exception exception = event.getException();

        // 保存日志
        LogException logException = new LogException();
        logException.setMethod(method);
        logException.setBestMatching(bestMatching);
        logException.setRequestAttribute(variable);
        logException.setRequestParam(param);
        logException.setRequestBody(body);
        logException.setErrorMsg(exception.getMessage());
        logException.setErrorDetail(ExceptionUtil.getDetailsStr(exception));
        logExceptionDao.save(logException);
    }

}
