package com.xy.xyaicpzs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.entity.OperationHistory;
import com.xy.xyaicpzs.domain.entity.User;
import com.xy.xyaicpzs.service.OperationHistoryService;
import com.xy.xyaicpzs.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 操作历史管理控制器
 */
@RestController
@RequestMapping("/operation-history")
@Slf4j
@Tag(name = "操作历史管理", description = "操作历史记录相关接口")
public class OperationHistoryController {

    @Autowired
    private OperationHistoryService operationHistoryService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取操作历史记录
     * 支持按操作模块和操作结果进行筛选
     */
    @GetMapping("/list")
    @Operation(summary = "获取操作历史记录", description = "获取操作历史记录，支持按操作模块、操作结果筛选和结果信息模糊搜索")
    public ApiResponse<List<OperationHistory>> getOperationHistory(
            @Parameter(description = "操作模块（0-会员码管理/1-Excel导入管理等）")
            @RequestParam(value = "operationModule", required = false) Integer operationModule,
            @Parameter(description = "操作结果（成功/失败）")
            @RequestParam(value = "operationResult", required = false) String operationResult,
            @Parameter(description = "结果信息关键词（支持模糊搜索）")
            @RequestParam(value = "keyword", required = false) String keyword,
            HttpServletRequest httpServletRequest) {
        
        try {
            // 权限校验：仅管理员可以查看
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (!userService.isAdmin(loginUser)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看操作历史");
            }
            
            log.info("获取操作历史，操作模块：{}，操作结果：{}，关键词：{}", operationModule, operationResult, keyword);
            
            // 构建查询条件
            QueryWrapper<OperationHistory> queryWrapper = new QueryWrapper<>();
            
            // 添加操作模块筛选条件
            if (operationModule != null && operationModule >= 0) {
                queryWrapper.eq("operationModule", operationModule);
            }
            
            // 添加操作结果筛选条件
            if (operationResult != null && !operationResult.trim().isEmpty()) {
                if (!operationResult.equals("成功") && !operationResult.equals("失败")) {
                    return ResultUtils.error(ErrorCode.PARAMS_ERROR, "操作结果只能是'成功'或'失败'");
                }
                queryWrapper.eq("operationResult", operationResult);
            }
            
            // 添加结果信息模糊搜索条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("resultMessage", keyword.trim());
            }
            
            // 按操作时间降序排序
            queryWrapper.orderByDesc("operationTime");
            
            // 查询操作历史
            List<OperationHistory> records = operationHistoryService.list(queryWrapper);
            
            log.info("操作历史查询成功，共{}条记录", records.size());
            
            return ResultUtils.success(records);
            
        } catch (Exception e) {
            log.error("获取操作历史失败", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取操作历史失败：" + e.getMessage());
        }
    }
} 