package com.erp.approval.controller;

import com.erp.approval.dto.OperationLogQueryRequest;
import com.erp.approval.entity.OperationLog;
import com.erp.approval.service.OperationLogService;
import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 操作日志控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/operation-logs")
@RequiredArgsConstructor
public class OperationLogController {

    private final OperationLogService operationLogService;

    /**
     * 操作日志列表（分页/筛选）
     * GET /api/operation-logs
     */
    @GetMapping
    public ApiResponse<PageResponse<OperationLog>> listLogs(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "id") String sortField,
            @RequestParam(required = false, defaultValue = "desc") String sortOrder) {

        OperationLogQueryRequest request = OperationLogQueryRequest.builder()
                .page(page)
                .pageSize(pageSize)
                .action(action)
                .module(module)
                .userId(userId)
                .userName(userName)
                .startDate(startDate)
                .endDate(endDate)
                .keyword(keyword)
                .sortField(sortField)
                .sortOrder(sortOrder)
                .build();

        PageResponse<OperationLog> result = operationLogService.listLogs(tenantId, request);
        return ApiResponse.success(result);
    }

    /**
     * 操作日志详情
     * GET /api/operation-logs/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<OperationLog> getLog(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @PathVariable Long id) {

        OperationLog log = operationLogService.getLogById(tenantId, id);
        if (log == null) {
            return ApiResponse.error(404, "日志记录不存在");
        }
        return ApiResponse.success(log);
    }

    /**
     * 获取操作统计
     * GET /api/operation-logs/statistics
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getStatistics(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        Map<String, Object> result = operationLogService.getStatistics(tenantId, startDate, endDate);
        return ApiResponse.success(result);
    }

    /**
     * 导出操作日志
     * GET /api/operation-logs/export
     */
    @GetMapping("/export")
    public void export(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false, defaultValue = "csv") String format,
            jakarta.servlet.http.HttpServletResponse response) throws Exception {

        OperationLogQueryRequest request = OperationLogQueryRequest.builder()
                .action(action)
                .module(module)
                .userId(userId)
                .userName(userName)
                .startDate(startDate)
                .endDate(endDate)
                .keyword(keyword)
                .build();

        if ("xlsx".equalsIgnoreCase(format) || "excel".equalsIgnoreCase(format)) {
            operationLogService.exportExcel(tenantId, request, response);
        } else if ("json".equalsIgnoreCase(format)) {
            // JSON格式直接输出
            List<OperationLog> data = operationLogService.queryForExport(tenantId, request);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write("{\"code\":200,\"message\":\"success\",\"data\":" +
                    new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(data) +
                    ",\"total\":" + data.size() + "}");
        } else {
            // 默认CSV格式
            operationLogService.exportCsv(tenantId, request, response);
        }
    }

    /**
     * 异步导出（大数据量）
     * POST /api/operation-logs/export-async
     */
    @PostMapping("/export-async")
    public ApiResponse<String> exportAsync(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String keyword) throws Exception {

        OperationLogQueryRequest request = OperationLogQueryRequest.builder()
                .action(action)
                .module(module)
                .userId(userId)
                .userName(userName)
                .startDate(startDate)
                .endDate(endDate)
                .keyword(keyword)
                .build();

        String taskId = operationLogService.exportExcelAsync(tenantId, request).join();
        return ApiResponse.success(taskId);
    }
}
