package com.mosquito.project.controller;

import com.mosquito.project.dto.BatchOperationRequest;
import com.mosquito.project.domain.Activity;
import com.mosquito.project.dto.CreateActivityRequest;
import com.mosquito.project.dto.UpdateActivityRequest;
import com.mosquito.project.dto.ActivityStatsResponse;
import com.mosquito.project.dto.ActivityGraphResponse;
import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.service.ActivityService;
import com.mosquito.project.domain.LeaderboardEntry;
import com.mosquito.project.permission.RequirePermission;
import com.mosquito.project.permission.PermissionCheckService;
import com.mosquito.project.persistence.repository.UserInviteRepository;
import com.mosquito.project.persistence.repository.UserRewardRepository;
import com.mosquito.project.persistence.entity.UserRewardEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/v1/activities")
@Tag(name = "Activity Management", description = "活动管理API")
public class ActivityController {

    // 权限码常量 (使用PRD四段式格式: module.resource.operation.dataScope)
    private static final String PERM_ACTIVITY_VIEW = "activity.index.view.ALL";
    private static final String PERM_ACTIVITY_CREATE = "activity.index.create.ALL";
    private static final String PERM_ACTIVITY_UPDATE = "activity.index.update.ALL";
    private static final String PERM_ACTIVITY_DELETE = "activity.index.delete.ALL";
    private static final String PERM_ACTIVITY_PUBLISH = "activity.index.publish.ALL";
    private static final String PERM_ACTIVITY_PAUSE = "activity.index.pause.ALL";
    private static final String PERM_ACTIVITY_RESUME = "activity.index.resume.ALL";
    private static final String PERM_ACTIVITY_END = "activity.index.end.ALL";
    private static final String PERM_ACTIVITY_EXPORT = "activity.index.export.ALL";
    private static final String PERM_ACTIVITY_STATS = "activity.stats.view.ALL";
    private static final String PERM_ACTIVITY_APPROVE = "activity.approval.approve.ALL";
    private static final String PERM_ACTIVITY_SUBMIT = "activity.approval.submit.ALL";
    private static final String PERM_ACTIVITY_CLONE = "activity.index.clone.ALL";
    private static final String PERM_ACTIVITY_TEMPLATE_VIEW = "activity.template.view.ALL";
    private static final String PERM_ACTIVITY_CONFIG_EDIT = "activity.config.edit.ALL";
    private static final String PERM_ACTIVITY_PARTICIPANT_VIEW = "activity.participant.view.ALL";

    private final ActivityService activityService;
    private final UserInviteRepository userInviteRepository;
    private final UserRewardRepository userRewardRepository;
    private final PermissionCheckService permissionCheckService;

    public ActivityController(ActivityService activityService, UserInviteRepository userInviteRepository,
                            UserRewardRepository userRewardRepository, PermissionCheckService permissionCheckService) {
        this.activityService = activityService;
        this.userInviteRepository = userInviteRepository;
        this.userRewardRepository = userRewardRepository;
        this.permissionCheckService = permissionCheckService;
    }

    @PostMapping
    @RequirePermission(PERM_ACTIVITY_CREATE)
    @Operation(summary = "创建活动", description = "创建一个新的推广活动")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "201", description = "活动创建成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "请求参数错误")
    })
    public ResponseEntity<ApiResponse<Activity>> createActivity(
            @Valid @RequestBody CreateActivityRequest request,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);
        Activity createdActivity = activityService.createActivity(request, currentUserId, currentUserDeptId);
        ApiResponse<Activity> response = ApiResponse.success(createdActivity);
        response.setCode(HttpStatus.CREATED.value());
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }

    @GetMapping
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "获取活动列表", description = "获取活动列表（支持分页、搜索、状态筛选）")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getActivities(
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页大小") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            @Parameter(description = "活动状态") @RequestParam(name = "status", required = false) String status,
            @Parameter(description = "关键词搜索") @RequestParam(name = "keyword", required = false) String keyword,
            @Parameter(description = "开始时间") @RequestParam(name = "startDate", required = false) OffsetDateTime startDate,
            @Parameter(description = "结束时间") @RequestParam(name = "endDate", required = false) OffsetDateTime endDate,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        var pagedResult = activityService.getActivitiesPaged(page, size, status, keyword, startDate, endDate, currentUserId);
        return ResponseEntity.ok(ApiResponse.success(pagedResult));
    }

    @PutMapping("/{id}")
    @RequirePermission(PERM_ACTIVITY_UPDATE)
    @Operation(summary = "更新活动", description = "更新指定活动的详细信息")
    public ResponseEntity<ApiResponse<Activity>> updateActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Valid @RequestBody UpdateActivityRequest request) {
        Activity updatedActivity = activityService.updateActivity(id, request);
        return ResponseEntity.ok(ApiResponse.success(updatedActivity));
    }

    @GetMapping("/{id}")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "获取活动", description = "根据ID获取活动详情")
    public ResponseEntity<ApiResponse<Activity>> getActivityById(
            @Parameter(description = "活动ID") @PathVariable Long id,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);

        // 数据权限检查
        Activity activity = activityService.getActivityById(id);
        if (activity != null) {
            boolean hasAccess = permissionCheckService.canAccessData(
                currentUserId,
                activity.getDepartmentId(),
                activity.getCreatorId(),
                currentUserDeptId
            );
            if (!hasAccess) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(403, "无权限访问该活动数据"));
            }
        }
        return ResponseEntity.ok(ApiResponse.success(activity));
    }

    @GetMapping("/{id}/stats")
    @RequirePermission(PERM_ACTIVITY_STATS)
    @Operation(summary = "获取活动统计", description = "获取活动的参与统计信息")
    public ResponseEntity<ApiResponse<ActivityStatsResponse>> getActivityStats(@Parameter(description = "活动ID") @PathVariable Long id) {
        ActivityStatsResponse stats = activityService.getActivityStats(id);
        return ResponseEntity.ok(ApiResponse.success(stats));
    }

    @GetMapping("/{id}/graph")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "获取活动关系图", description = "获取用户邀请关系图谱")
    public ResponseEntity<ApiResponse<ActivityGraphResponse>> getActivityGraph(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "根用户ID，可选") @RequestParam(name = "rootUserId", required = false) Long rootUserId,
            @Parameter(description = "最大深度，默认3") @RequestParam(name = "maxDepth", required = false, defaultValue = "3") Integer maxDepth,
            @Parameter(description = "限制数量，默认1000") @RequestParam(name = "limit", required = false, defaultValue = "1000") Integer limit) {
        ActivityGraphResponse graph = activityService.getActivityGraph(id, rootUserId, maxDepth, limit);
        return ResponseEntity.ok(ApiResponse.success(graph));
    }

    @GetMapping("/{id}/leaderboard")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "获取排行榜", description = "获取活动邀请排行榜")
    public ResponseEntity<ApiResponse<List<LeaderboardEntry>>> getLeaderboard(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页大小") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            @Parameter(description = "只返回前N名") @RequestParam(name = "topN", required = false) Integer topN) {
        List<LeaderboardEntry> list = activityService.getLeaderboard(id);
        if (topN != null && topN > 0 && topN < list.size()) {
            list = list.subList(0, topN);
        }
        int p = (page == null || page < 0) ? 0 : page;
        int s = (size == null || size < 1) ? 20 : size;
        int from = p * s;
        int total = list.size();
        if (from >= total) {
            return ResponseEntity.ok(ApiResponse.paginated(java.util.Collections.emptyList(), p, s, total));
        }
        int to = Math.min(from + s, total);
        return ResponseEntity.ok(ApiResponse.paginated(list.subList(from, to), p, s, total));
    }

    @GetMapping("/{id}/leaderboard/export")
    @RequirePermission(PERM_ACTIVITY_EXPORT)
    @Operation(summary = "导出排行榜", description = "将排行榜导出为CSV格式")
    public ResponseEntity<byte[]> exportLeaderboard(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "只导出前N名") @RequestParam(name = "topN", required = false) Integer topN) {
        String csv = (topN == null) ? activityService.generateLeaderboardCsv(id) : activityService.generateLeaderboardCsv(id, topN);
        byte[] body = csv.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"leaderboard_" + id + ".csv\"");
        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }

    // P1修复：添加与PRD矩阵对齐的活动导出接口
    @GetMapping("/export")
    @RequirePermission(PERM_ACTIVITY_EXPORT)
    @Operation(summary = "导出活动列表", description = "将活动列表导出为CSV格式")
    public ResponseEntity<byte[]> exportActivities() {
        StringBuilder csv = new StringBuilder();
        csv.append("ID,名称,状态,开始时间,结束时间,参与人数,分享数,转化数\n");

        for (Activity activity : activityService.getAllActivities()) {
            csv.append(activity.getId()).append(",")
               .append(escapeCsv(activity.getName())).append(",")
               .append(activity.getStatus() != null ? activity.getStatus() : "").append(",")
               .append(activity.getStartTime() != null ? activity.getStartTime().toString() : "").append(",")
               .append(activity.getEndTime() != null ? activity.getEndTime().toString() : "").append(",");
            try {
                ActivityStatsResponse stats = activityService.getActivityStats(activity.getId());
                csv.append(stats.getTotalParticipants()).append(",")
                   .append(stats.getTotalShares()).append(",")
                   .append(stats.getNewUsers()).append("\n");
            } catch (Exception e) {
                csv.append("0,0,0\n");
            }
        }

        byte[] body = csv.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("text/csv; charset=UTF-8"));
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"activity_export_" +
                java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".csv\"");

        return new ResponseEntity<>(body, headers, HttpStatus.OK);
    }

    @PostMapping("/{id}/publish")
    @RequirePermission(PERM_ACTIVITY_PUBLISH)
    @Operation(summary = "发布活动", description = "将活动状态改为运行中(需要先审批通过)")
    public ResponseEntity<ApiResponse<Activity>> publishActivity(@Parameter(description = "活动ID") @PathVariable Long id) {
        Activity activity = activityService.publishActivity(id);
        return ResponseEntity.ok(ApiResponse.success(activity, "活动发布成功"));
    }

    @PostMapping("/{id}/submit")
    @RequirePermission(PERM_ACTIVITY_SUBMIT)
    @Operation(summary = "提交审批", description = "将活动提交审批")
    public ResponseEntity<ApiResponse<Activity>> submitForApproval(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "申请人ID") @RequestParam(required = false) Long applicantId,
            HttpServletRequest httpRequest) {
        // 使用当前登录用户作为申请人，若未指定则自动填充
        Long currentUserId = getCurrentUserId(httpRequest);
        if (applicantId == null && currentUserId != null) {
            applicantId = currentUserId;
        }
        if (applicantId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "无法获取申请人信息，请先登录"));
        }
        Activity activity = activityService.submitForApproval(id, applicantId);
        return ResponseEntity.ok(ApiResponse.success(activity, "活动已提交审批"));
    }

    @PostMapping("/{id}/approve")
    @RequirePermission(PERM_ACTIVITY_APPROVE)
    @Operation(summary = "审批通过(已废弃)", description = "请使用审批中心进行审批")
    @Deprecated
    public ResponseEntity<ApiResponse<Activity>> approveActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "是否立即发布") @RequestParam(defaultValue = "false") boolean autoPublish) {
        // 收敛为单通道：活动审批统一走审批中心，禁止直接调用
        return ResponseEntity.status(410).body(ApiResponse.error(410,
            "此接口已废弃，活动审批请通过审批中心(Approval Center)进行"));
    }

    @PostMapping("/{id}/reject")
    @RequirePermission(PERM_ACTIVITY_APPROVE)
    @Operation(summary = "审批拒绝(已废弃)", description = "请使用审批中心进行审批")
    @Deprecated
    public ResponseEntity<ApiResponse<Activity>> rejectActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "拒绝原因") @RequestParam(required = false) String reason) {
        // 收敛为单通道：活动审批统一走审批中心，禁止直接调用
        return ResponseEntity.status(410).body(ApiResponse.error(410,
            "此接口已废弃，活动审批请通过审批中心(Approval Center)进行"));
    }

    @PostMapping("/{id}/pause")
    @RequirePermission(PERM_ACTIVITY_PAUSE)
    @Operation(summary = "暂停活动", description = "将活动状态改为暂停")
    public ResponseEntity<ApiResponse<Activity>> pauseActivity(@Parameter(description = "活动ID") @PathVariable Long id) {
        Activity activity = activityService.pauseActivity(id);
        return ResponseEntity.ok(ApiResponse.success(activity, "活动暂停成功"));
    }

    @PostMapping("/{id}/resume")
    @RequirePermission(PERM_ACTIVITY_RESUME)
    @Operation(summary = "恢复活动", description = "将活动状态恢复为已发布")
    public ResponseEntity<ApiResponse<Activity>> resumeActivity(@Parameter(description = "活动ID") @PathVariable Long id) {
        Activity activity = activityService.resumeActivity(id);
        return ResponseEntity.ok(ApiResponse.success(activity, "活动恢复成功"));
    }

    @PostMapping("/{id}/end")
    @RequirePermission(PERM_ACTIVITY_END)
    @Operation(summary = "结束活动", description = "将活动状态改为已结束")
    public ResponseEntity<ApiResponse<Activity>> endActivity(@Parameter(description = "活动ID") @PathVariable Long id) {
        Activity activity = activityService.endActivity(id);
        return ResponseEntity.ok(ApiResponse.success(activity, "活动结束成功"));
    }

    @DeleteMapping("/{id}")
    @RequirePermission(PERM_ACTIVITY_DELETE)
    @Operation(summary = "删除活动", description = "删除活动（需要审批，草稿/进行中/已结束状态均需审批）")
    public ResponseEntity<ApiResponse<Void>> deleteActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        activityService.deleteActivity(id, currentUserId);
        return ResponseEntity.ok(ApiResponse.success(null, "活动删除成功"));
    }

    @PostMapping("/{id}/archive")
    @RequirePermission(PERM_ACTIVITY_DELETE)
    @Operation(summary = "归档活动", description = "归档已结束的活动（ENDED->ARCHIVED）")
    public ResponseEntity<ApiResponse<Void>> archiveActivity(@Parameter(description = "活动ID") @PathVariable Long id) {
        activityService.archiveActivity(id);
        return ResponseEntity.ok(ApiResponse.success(null, "活动归档成功"));
    }

    /**
     * 复制活动
     * 将现有活动复制为新草稿，继承关键配置但重置运行态字段
     */
    @PostMapping("/{id}/clone")
    @RequirePermission(PERM_ACTIVITY_CLONE)
    @Operation(summary = "复制活动", description = "复制活动为新草稿，继承关键配置")
    public ResponseEntity<ApiResponse<Activity>> cloneActivity(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "新活动名称") @RequestParam(required = false) String newName,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);
        Activity clonedActivity = activityService.cloneActivity(id, newName, currentUserId, currentUserDeptId);
        return ResponseEntity.ok(ApiResponse.success(clonedActivity, "活动复制成功"));
    }

    /**
     * 批量发布活动
     */
    @PostMapping("/batch/publish")
    @RequirePermission(PERM_ACTIVITY_PUBLISH)
    @Operation(summary = "批量发布活动", description = "批量发布多个活动")
    public ResponseEntity<ApiResponse<Map<String, Object>>> batchPublish(
            @Valid @RequestBody BatchOperationRequest request,
            HttpServletRequest httpRequest) {
        Map<String, Object> result = activityService.batchPublish(request.getActivityIds());
        return ResponseEntity.ok(ApiResponse.success(result, "批量发布完成"));
    }

    /**
     * 批量暂停活动
     */
    @PostMapping("/batch/pause")
    @RequirePermission(PERM_ACTIVITY_PAUSE)
    @Operation(summary = "批量暂停活动", description = "批量暂停多个活动")
    public ResponseEntity<ApiResponse<Map<String, Object>>> batchPause(
            @Valid @RequestBody BatchOperationRequest request,
            HttpServletRequest httpRequest) {
        Map<String, Object> result = activityService.batchPause(request.getActivityIds());
        return ResponseEntity.ok(ApiResponse.success(result, "批量暂停完成"));
    }

    /**
     * 批量结束活动
     */
    @PostMapping("/batch/end")
    @RequirePermission(PERM_ACTIVITY_END)
    @Operation(summary = "批量结束活动", description = "批量结束多个活动")
    public ResponseEntity<ApiResponse<Map<String, Object>>> batchEnd(
            @Valid @RequestBody BatchOperationRequest request,
            HttpServletRequest httpRequest) {
        Map<String, Object> result = activityService.batchEnd(request.getActivityIds());
        return ResponseEntity.ok(ApiResponse.success(result, "批量结束完成"));
    }

    /**
     * 上传活动素材图片
     */
    @PostMapping(value = "/{id}/upload-image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RequirePermission(PERM_ACTIVITY_UPDATE)
    @Operation(summary = "上传活动素材图片", description = "上传活动自定义素材图片，支持PNG、JPG、GIF格式，最大10MB")
    public ResponseEntity<ApiResponse<Map<String, String>>> uploadImage(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "图片文件") @RequestPart("file") MultipartFile file) {
        activityService.uploadCustomizationImage(id, file);
        // 返回文件访问路径（实际应返回CDN/存储路径）
        Map<String, String> result = new HashMap<>();
        result.put("url", "/api/v1/activities/" + id + "/images/" + file.getOriginalFilename());
        result.put("filename", file.getOriginalFilename());
        return ResponseEntity.ok(ApiResponse.success(result, "图片上传成功"));
    }

    // ========== 管理后台接口 ==========

    /**
     * 管理后台：获取活动列表
     */
    @GetMapping("/admin")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "管理后台获取活动列表", description = "获取活动列表（管理视图，支持分页、搜索、状态筛选）")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAdminActivities(
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页大小") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            @Parameter(description = "活动状态") @RequestParam(name = "status", required = false) String status,
            @Parameter(description = "关键词搜索") @RequestParam(name = "keyword", required = false) String keyword,
            @Parameter(description = "开始时间") @RequestParam(name = "startDate", required = false) OffsetDateTime startDate,
            @Parameter(description = "结束时间") @RequestParam(name = "endDate", required = false) OffsetDateTime endDate,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        var pagedResult = activityService.getActivitiesPaged(page, size, status, keyword, startDate, endDate, currentUserId);
        return ResponseEntity.ok(ApiResponse.success(pagedResult));
    }

    /**
     * 管理后台：获取活动详情
     */
    @GetMapping("/admin/{id}")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "管理后台获取活动详情", description = "根据ID获取活动详情（管理视图）")
    public ResponseEntity<ApiResponse<Activity>> getAdminActivityById(
            @Parameter(description = "活动ID") @PathVariable Long id,
            HttpServletRequest httpRequest) {
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);

        // 数据权限检查
        Activity activity = activityService.getActivityById(id);
        if (activity != null) {
            boolean hasAccess = permissionCheckService.canAccessData(
                currentUserId,
                activity.getDepartmentId(),
                activity.getCreatorId(),
                currentUserDeptId
            );
            if (!hasAccess) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(403, "无权限访问该活动数据"));
            }
        }
        return ResponseEntity.ok(ApiResponse.success(activity));
    }

    /**
     * 管理后台：获取活动参与者列表
     */
    @GetMapping("/admin/{id}/participants")
    @RequirePermission(PERM_ACTIVITY_PARTICIPANT_VIEW)
    @Operation(summary = "获取活动参与者列表", description = "获取活动的所有参与者（管理视图）")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getActivityParticipants(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页数量") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            @Parameter(description = "搜索关键词（邮箱或用户ID）") @RequestParam(name = "query", required = false) String query,
            HttpServletRequest httpRequest) {

        // 数据权限检查
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);
        Activity activity = activityService.getActivityById(id);
        if (activity != null) {
            boolean hasAccess = permissionCheckService.canAccessData(
                currentUserId,
                activity.getDepartmentId(),
                activity.getCreatorId(),
                currentUserDeptId
            );
            if (!hasAccess) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(403, "无权限访问该活动数据"));
            }
        }

        Page<com.mosquito.project.persistence.entity.UserInviteEntity> participantPage;
        if (query != null && !query.isBlank()) {
            participantPage = userInviteRepository.findByActivityIdAndQuery(id, query, PageRequest.of(page, size));
        } else {
            participantPage = userInviteRepository.findByActivityId(id, PageRequest.of(page, size));
        }

        List<Map<String, Object>> participants = participantPage.getContent().stream()
            .map(invite -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", invite.getId());
                map.put("inviterUserId", invite.getInviterUserId());
                map.put("inviteeUserId", invite.getInviteeUserId());
                map.put("email", invite.getEmail());
                map.put("status", invite.getStatus());
                map.put("invitedAt", invite.getInvitedAt() != null ? invite.getInvitedAt().toString() : null);
                return map;
            })
            .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("content", participants);
        result.put("totalElements", participantPage.getTotalElements());
        result.put("totalPages", participantPage.getTotalPages());
        result.put("currentPage", participantPage.getNumber());

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 管理后台：获取活动奖励明细列表
     */
    @GetMapping("/admin/{id}/rewards")
    @RequirePermission(PERM_ACTIVITY_VIEW)
    @Operation(summary = "获取活动奖励明细", description = "获取活动的所有奖励发放记录（管理视图）")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getActivityRewards(
            @Parameter(description = "活动ID") @PathVariable Long id,
            @Parameter(description = "页码，从0开始") @RequestParam(name = "page", required = false, defaultValue = "0") Integer page,
            @Parameter(description = "每页数量") @RequestParam(name = "size", required = false, defaultValue = "20") Integer size,
            HttpServletRequest httpRequest) {

        // 数据权限检查
        Long currentUserId = getCurrentUserId(httpRequest);
        Long currentUserDeptId = getCurrentUserDepartmentId(httpRequest);
        Activity activity = activityService.getActivityById(id);
        if (activity != null) {
            boolean hasAccess = permissionCheckService.canAccessData(
                currentUserId,
                activity.getDepartmentId(),
                activity.getCreatorId(),
                currentUserDeptId
            );
            if (!hasAccess) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.error(403, "无权限访问该活动数据"));
            }
        }

        Page<UserRewardEntity> rewardPage = userRewardRepository.findByActivityId(id, PageRequest.of(page, size));

        List<Map<String, Object>> rewards = rewardPage.getContent().stream()
            .map(reward -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", reward.getId());
                map.put("userId", reward.getUserId());
                map.put("activityId", reward.getActivityId());
                map.put("points", reward.getPoints());
                map.put("couponCode", reward.getCouponCode());
                map.put("couponBatchId", reward.getCouponBatchId());
                map.put("type", reward.getType());
                map.put("status", reward.getStatus());
                map.put("createdAt", reward.getCreatedAt() != null ? reward.getCreatedAt().toString() : null);
                return map;
            })
            .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("content", rewards);
        result.put("totalElements", rewardPage.getTotalElements());
        result.put("totalPages", rewardPage.getTotalPages());
        result.put("currentPage", rewardPage.getNumber());

        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof String) {
            try {
                return Long.parseLong((String) userIdObj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取当前用户部门ID
     */
    private Long getCurrentUserDepartmentId(HttpServletRequest request) {
        Object deptIdObj = request.getAttribute("departmentId");
        if (deptIdObj instanceof Long) {
            return (Long) deptIdObj;
        } else if (deptIdObj instanceof Integer) {
            return ((Integer) deptIdObj).longValue();
        } else if (deptIdObj instanceof String) {
            try {
                return Long.parseLong((String) deptIdObj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * CSV字段转义
     */
    private String escapeCsv(String value) {
        if (value == null) return "";
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        return value;
    }

    /**
     * 获取活动模板列表
     * 对应权限: activity.template.view.ALL
     */
    @GetMapping("/templates")
    @RequirePermission(PERM_ACTIVITY_TEMPLATE_VIEW)
    @Operation(summary = "获取活动模板列表", description = "获取可用的活动模板")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getTemplates(HttpServletRequest request) {
        // 返回预定义的活动模板列表
        List<Map<String, Object>> templates = List.of(
            Map.of("id", "template_1", "name", "邀请有礼模板", "description", "标准邀请有礼活动模板"),
            Map.of("id", "template_2", "name", "分享抽大奖模板", "description", "分享即可参与抽奖活动模板"),
            Map.of("id", "template_3", "name", "新人专享模板", "description", "新用户专享奖励活动模板")
        );
        return ResponseEntity.ok(ApiResponse.success(templates));
    }

    /**
     * 获取指定模板详情
     * 对应权限: activity.template.view.ALL
     */
    @GetMapping("/templates/{templateId}")
    @RequirePermission(PERM_ACTIVITY_TEMPLATE_VIEW)
    @Operation(summary = "获取活动模板详情", description = "获取指定活动模板的详细信息")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTemplateById(
            @PathVariable String templateId,
            HttpServletRequest request) {
        Map<String, Object> template = Map.of(
            "id", templateId,
            "name", "活动模板",
            "description", "模板描述",
            "defaultConfig", Map.of(
                "rewardType", "POINTS",
                "rewardAmount", 100,
                "shareText", "邀请好友一起参与活动"
            )
        );
        return ResponseEntity.ok(ApiResponse.success(template));
    }

    /**
     * 获取活动配置详情
     * 对应权限: activity.config.edit.ALL
     */
    @GetMapping("/{activityId}/config")
    @RequirePermission(PERM_ACTIVITY_CONFIG_EDIT)
    @Operation(summary = "获取活动配置详情", description = "获取指定活动的详细配置")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getActivityConfig(
            @PathVariable Long activityId,
            HttpServletRequest request) {
        Activity activity = activityService.getActivityById(activityId);
        if (activity == null) {
            return ResponseEntity.status(404).body(ApiResponse.error(404, "活动不存在"));
        }

        Map<String, Object> config = new HashMap<>();
        config.put("activityId", activity.getId());
        config.put("name", activity.getName());
        config.put("targetUsersConfig", activity.getTargetUsersConfig());
        config.put("pageContentConfig", activity.getPageContentConfig());
        config.put("rewardTiersConfig", activity.getRewardTiersConfig());
        config.put("rewardCalculationMode", activity.getRewardCalculationMode());
        config.put("multiLevelRewardConfig", activity.getMultiLevelRewardConfig());
        config.put("rewardMode", activity.getRewardMode());
        config.put("rewardTiers", activity.getRewardTiers());
        config.put("startTime", activity.getStartTime());
        config.put("endTime", activity.getEndTime());
        config.put("status", activity.getStatus());

        return ResponseEntity.ok(ApiResponse.success(config));
    }

    /**
     * 更新活动配置
     * 对应权限: activity.config.edit.ALL
     */
    @PutMapping("/{activityId}/config")
    @RequirePermission(PERM_ACTIVITY_CONFIG_EDIT)
    @Operation(summary = "更新活动配置", description = "更新指定活动的配置")
    public ResponseEntity<ApiResponse<Activity>> updateActivityConfig(
            @PathVariable Long activityId,
            @RequestBody Map<String, Object> config,
            HttpServletRequest request) {
        // 验证：至少要有一个配置项
        if (config == null || config.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "配置不能为空"));
        }

        // 调用服务层更新活动配置
        Activity updatedActivity = activityService.updateActivityConfig(activityId, config);
        return ResponseEntity.ok(ApiResponse.success(updatedActivity, "配置更新成功"));
    }
}
