package com.njzscloud.supervisory.sys.log.controller;

import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.security.support.UserDetail;
import com.njzscloud.common.security.util.SecurityUtil;
import com.njzscloud.supervisory.sys.log.annotation.Log;
import com.njzscloud.supervisory.sys.log.domain.SysLog;
import com.njzscloud.supervisory.sys.log.domain.dto.SysLogQueryCriteria;
import com.njzscloud.supervisory.sys.log.service.SysLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ljw
 * @date 2025-10-24
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/log")
public class SysLogController {

    private final SysLogService sysLogService;

    @Log("导出数据")
    @GetMapping(value = "/export")
    public void exportLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException {
        criteria.setLogType("INFO");
        sysLogService.download(sysLogService.queryAll(criteria), response);
    }

    @Log("导出错误数据")
    @GetMapping(value = "/error/export")
    public void exportErrorLog(HttpServletResponse response, SysLogQueryCriteria criteria) throws IOException {
        criteria.setLogType("ERROR");
        sysLogService.download(sysLogService.queryAll(criteria), response);
    }

    @GetMapping
    public R<PageResult<SysLog>> queryLog(SysLogQueryCriteria criteria, PageParam pageParam) {
        criteria.setLogType("INFO");
        return R.success(sysLogService.queryAll(criteria, pageParam));
    }

    @GetMapping(value = "/user")
    public R<PageResult<SysLog>> queryUserLog(SysLogQueryCriteria criteria, PageParam pageParam) {
        criteria.setLogType("INFO");
        UserDetail userDetail = SecurityUtil.loginUser();
        criteria.setUsername(userDetail.getNickname());
        return R.success(sysLogService.queryAllByUser(criteria, pageParam));
    }

    @GetMapping(value = "/error")
    public R<PageResult<SysLog>> queryErrorLog(SysLogQueryCriteria criteria, PageParam pageParam) {
        criteria.setLogType("ERROR");
        return R.success(sysLogService.queryAll(criteria, pageParam));
    }

    @GetMapping(value = "/error/{id}")
    public R<Object> queryErrorLogDetail(@PathVariable Long id) {
        return R.success(sysLogService.findByErrDetail(id));
    }

    @DeleteMapping(value = "/del/error")
    @Log("删除所有ERROR日志")
    public R<?> delAllErrorLog() {
        sysLogService.delAllByError();
        return R.success();
    }

    @DeleteMapping(value = "/del/info")
    @Log("删除所有INFO日志")
    public R<?> delAllInfoLog() {
        sysLogService.delAllByInfo();
        return R.success();
    }

}
