package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.AdminPlazaAuditDto.*;
import com.dora.service.AdminPlazaAuditService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 管理端 - 广场作品审核控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/plaza/audit")
@Tag(name = "管理端-广场审核", description = "广场作品审核管理接口")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminPlazaAuditController {

    private final AdminPlazaAuditService auditService;

    @GetMapping("/pending")
    @Operation(summary = "查询待审核作品列表", description = "分页查询待审核的广场作品")
    public Result<PendingWorksListResponse> getPendingWorks(
            @Valid @ModelAttribute PendingWorksQueryRequest request) {
        try {
            PendingWorksListResponse response = auditService.getPendingWorks(request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询待审核作品失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/pending/{workNo}")
    @Operation(summary = "查询待审核作品详情", description = "查询指定作品的详细信息")
    public Result<PendingWorkDetailResponse> getPendingWorkDetail(
            @Parameter(description = "作品编号", required = true) @PathVariable(name = "workNo", required = true) String workNo) {
        try {
            PendingWorkDetailResponse response = auditService.getPendingWorkDetail(workNo);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询待审核作品详情失败 - workNo: {}", workNo, e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/audit")
    @Operation(summary = "审核作品", description = "审核单个作品，通过或拒绝")
    public Result<AuditResultResponse> auditWork(
            @Valid @RequestBody AuditWorkRequest request,
            Authentication authentication) {
        try {
            // 从认证信息中获取管理员信息
            Long adminId = Long.valueOf(authentication.getName());
            String adminName = authentication.getName(); // 实际应该从数据库获取管理员名称
            
            AuditResultResponse response = auditService.auditWork(request, adminId, adminName);
            return Result.success(response);
        } catch (Exception e) {
            log.error("审核作品失败 - workNo: {}", request.getWorkNo(), e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/batch-audit")
    @Operation(summary = "批量审核作品", description = "批量审核多个作品")
    public Result<Integer> batchAuditWorks(
            @Parameter(description = "作品编号列表", required = true) @RequestParam List<String> workNos,
            @Parameter(description = "审核状态：approved/rejected", required = true) @RequestParam String auditStatus,
            @Parameter(description = "审核备注") @RequestParam(required = false) String auditRemark,
            Authentication authentication) {
        try {
            Long adminId = Long.valueOf(authentication.getName());
            String adminName = authentication.getName();
            
            int successCount = auditService.batchAuditWorks(workNos, auditStatus, auditRemark, adminId, adminName);
            return Result.success(successCount, String.format("成功审核 %d 个作品", successCount));
        } catch (Exception e) {
            log.error("批量审核作品失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/stats")
    @Operation(summary = "获取审核统计数据", description = "获取待审核数量、今日审核数量等统计信息")
    public Result<AuditStatsResponse> getAuditStats() {
        try {
            AuditStatsResponse response = auditService.getAuditStats();
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取审核统计数据失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/history")
    @Operation(summary = "查询审核历史记录", description = "分页查询审核历史记录")
    public Result<List<AuditHistoryRecord>> getAuditHistory(
            @Valid @ModelAttribute AuditHistoryQueryRequest request) {
        try {
            List<AuditHistoryRecord> records = auditService.getAuditHistory(request);
            return Result.success(records);
        } catch (Exception e) {
            log.error("查询审核历史记录失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/revoke")
    @Operation(summary = "撤销审核", description = "将已审核的作品重新设为待审核状态")
    public Result<AuditResultResponse> revokeAudit(
            @Valid @RequestBody RevokeAuditRequest request) {
        try {
            Long adminId = com.dora.util.SecurityUtil.getCurrentUserId();
            String adminName = com.dora.util.SecurityUtil.getUsername();
            AuditResultResponse result = auditService.revokeAudit(request.getWorkNo(), request.getReason(), adminId, adminName);
            log.info("撤销审核成功, workNo: {}, adminId: {}", request.getWorkNo(), adminId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("撤销审核失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/quick-approve")
    @Operation(summary = "快捷审核", description = "批量通过最早的N个待审核作品")
    public Result<Integer> quickApprove(
            @Parameter(description = "数量") @RequestParam(defaultValue = "10") int count,
            @Parameter(description = "任务类型（可选）") @RequestParam(required = false) String taskType) {
        try {
            Long adminId = com.dora.util.SecurityUtil.getCurrentUserId();
            String adminName = com.dora.util.SecurityUtil.getUsername();
            int successCount = auditService.quickApprove(count, taskType, adminId, adminName);
            log.info("快捷审核完成, 成功: {}, adminId: {}", successCount, adminId);
            return Result.success(successCount);
        } catch (Exception e) {
            log.error("快捷审核失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/detail/{workNo}")
    @Operation(summary = "获取作品详细审核信息", description = "含历史记录、作者统计等")
    public Result<WorkAuditDetailResponse> getWorkAuditDetail(
            @Parameter(description = "作品编号") @PathVariable(name = "workNo", required = true) String workNo) {
        try {
            WorkAuditDetailResponse detail = auditService.getWorkAuditDetail(workNo);
            return Result.success(detail);
        } catch (Exception e) {
            log.error("查询作品详细审核信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/admin-stats")
    @Operation(summary = "获取审核员工作量统计", description = "统计审核员的工作量和效率")
    public Result<AdminWorkloadStatsResponse> getAdminWorkloadStats(
            @Parameter(description = "审核员ID（默认当前管理员）") @RequestParam(required = false) Long adminId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
        try {
            if (adminId == null) {
                adminId = com.dora.util.SecurityUtil.getCurrentUserId();
            }
            AdminWorkloadStatsResponse stats = auditService.getAdminWorkloadStats(adminId, startTime, endTime);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("查询审核员工作量统计失败", e);
            return Result.error(e.getMessage());
        }
    }
}

