package com.dora.controller;

import com.dora.dto.AdminUserDto;
import com.dora.dto.ApiResponse;
import com.dora.dto.PageResultDto;
import com.dora.service.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 后台用户管理控制器
 */
@RestController
@RequestMapping("/admin/users")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "后台用户管理", description = "后台管理端用户管理相关接口")
public class AdminUserController {

    private final AdminUserService adminUserService;

    @GetMapping("/list")
    @Operation(summary = "获取用户列表", description = "分页获取用户列表，支持多种筛选条件。" +
            "membershipType参数：paid(当前付费会员)、exchange(当前兑换会员)、gift(赠送会员)、expired(过期会员)、paidExpired(付费过期会员)、exchangeExpired(兑换过期会员)、all(全部)")
    public ApiResponse<AdminUserDto.UserListResponse> getUserList(
            @Valid AdminUserDto.UserListRequest request) {
        
        log.info("收到用户列表查询请求: {}", request);
        return adminUserService.getUserList(request);
    }

    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public ApiResponse<AdminUserDto.UserDetailResponse> getUserDetail(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        
        log.info("收到用户详情查询请求，用户ID: {}", userId);
        return adminUserService.getUserDetail(userId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    public ApiResponse<String> updateUser(
            @Valid @RequestBody AdminUserDto.UserUpdateRequest request) {
        
        log.info("收到用户信息更新请求: {}", request);
        return adminUserService.updateUser(request);
    }

    @PutMapping("/status")
    @Operation(summary = "更新用户状态", description = "启用或禁用用户")
    public ApiResponse<String> updateUserStatus(
            @Valid @RequestBody AdminUserDto.UserStatusUpdateRequest request) {
        
        log.info("收到用户状态更新请求: {}", request);
        return adminUserService.updateUserStatus(request);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取用户统计信息", description = "获取用户相关的详细统计数据，包括：基础用户统计、VIP/SVIP分类统计（区分付费/兑换/过期）、特殊会员类型统计、认证和推广统计等。会员统计会考虑有效期状态。")
    public ApiResponse<AdminUserDto.UserStatistics> getUserStatistics() {
        
        log.info("收到用户统计信息查询请求");
        return adminUserService.getUserStatistics();
    }

    @PostMapping("/{userId}/reset-password")
    @Operation(summary = "重置用户密码", description = "管理员重置用户密码")
    public ApiResponse<String> resetUserPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "新密码") @RequestParam @NotBlank String newPassword) {
        
        log.info("收到用户密码重置请求，用户ID: {}", userId);
        return adminUserService.resetUserPassword(userId, newPassword);
    }

    @PostMapping("/batch/role")
    @Operation(summary = "批量更新用户角色", description = "批量更新多个用户的角色和会员到期时间")
    public ApiResponse<String> batchUpdateUserRole(
            @Parameter(description = "用户ID列表") @RequestBody @NotNull List<Long> userIds,
            @Parameter(description = "角色（0游客/1普通/2VIP/3SVIP）") @RequestParam @NotNull Integer role,
            @Parameter(description = "会员到期时间") @RequestParam(required = false) LocalDateTime membershipExpiresAt) {
        
        log.info("收到批量更新用户角色请求，用户数量: {}, 角色: {}", userIds.size(), role);
        return adminUserService.batchUpdateUserRole(userIds, role, membershipExpiresAt);
    }

    @PostMapping("/batch/promotion-level")
    @Operation(summary = "批量更新推广等级", description = "批量更新多个用户的推广等级")
    public ApiResponse<String> batchUpdatePromotionLevel(
            @Parameter(description = "用户ID列表") @RequestBody @NotNull List<Long> userIds,
            @Parameter(description = "推广等级") @RequestParam @NotNull Integer promotionLevel) {
        
        log.info("收到批量更新推广等级请求，用户数量: {}, 推广等级: {}", userIds.size(), promotionLevel);
        return adminUserService.batchUpdatePromotionLevel(userIds, promotionLevel);
    }

    @PostMapping("/export")
    @Operation(summary = "导出用户数据", description = "根据筛选条件导出用户数据")
    public ApiResponse<String> exportUserData(
            @Valid AdminUserDto.UserListRequest request) {
        
        log.info("收到用户数据导出请求: {}", request);
        return adminUserService.exportUserData(request);
    }

    @GetMapping("/{userId}/operation-logs")
    @Operation(summary = "获取用户操作日志", description = "获取指定用户的操作日志")
    public ApiResponse<PageResultDto<AdminUserDto.UserOperationLog>> getUserOperationLogs(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        
        log.info("收到用户操作日志查询请求，用户ID: {}, 页码: {}, 每页大小: {}", userId, page, size);
        return adminUserService.getUserOperationLogs(userId, page, size);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索用户", description = "根据关键词快速搜索用户")
    public ApiResponse<AdminUserDto.UserListResponse> searchUsers(
            @Parameter(description = "搜索关键词（用户名、手机号）") @RequestParam @NotBlank String keyword,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size) {
        
        log.info("收到用户搜索请求，关键词: {}", keyword);
        
        // 构建搜索请求
        AdminUserDto.UserListRequest request = new AdminUserDto.UserListRequest();
        request.setKeyword(keyword);
        request.setPage(page);
        request.setSize(size);
        
        return adminUserService.getUserList(request);
    }

    @GetMapping("/role/{role}")
    @Operation(summary = "按角色获取用户", description = "根据用户角色获取用户列表")
    public ApiResponse<AdminUserDto.UserListResponse> getUsersByRole(
            @Parameter(description = "用户角色（0游客/1普通/2VIP/3SVIP）") @PathVariable Integer role,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        
        log.info("收到按角色查询用户请求，角色: {}", role);
        
        // 构建查询请求
        AdminUserDto.UserListRequest request = new AdminUserDto.UserListRequest();
        request.setRole(role);
        request.setPage(page);
        request.setSize(size);
        
        return adminUserService.getUserList(request);
    }

    @GetMapping("/verified/{isVerified}")
    @Operation(summary = "按认证状态获取用户", description = "根据实名认证状态获取用户列表")
    public ApiResponse<AdminUserDto.UserListResponse> getUsersByVerificationStatus(
            @Parameter(description = "认证状态（0未认证/1已认证）") @PathVariable Integer isVerified,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        
        log.info("收到按认证状态查询用户请求，认证状态: {}", isVerified);
        
        // 构建查询请求
        AdminUserDto.UserListRequest request = new AdminUserDto.UserListRequest();
        request.setIsVerified(isVerified);
        request.setPage(page);
        request.setSize(size);
        
        return adminUserService.getUserList(request);
    }

    @GetMapping("/promotion-level/{promotionLevel}")
    @Operation(summary = "按推广等级获取用户", description = "根据推广等级获取用户列表")
    public ApiResponse<AdminUserDto.UserListResponse> getUsersByPromotionLevel(
            @Parameter(description = "推广等级") @PathVariable Integer promotionLevel,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size) {
        
        log.info("收到按推广等级查询用户请求，推广等级: {}", promotionLevel);
        
        // 构建查询请求
        AdminUserDto.UserListRequest request = new AdminUserDto.UserListRequest();
        request.setPromotionLevel(promotionLevel);
        request.setPage(page);
        request.setSize(size);
        
        return adminUserService.getUserList(request);
    }

    @GetMapping("/paid-users")
    @Operation(summary = "获取当前付费用户列表", description = "专门用于查询当前有效的付费会员，过滤掉兑换码用户、赠送用户和过期会员")
    public ApiResponse<AdminUserDto.UserListResponse> getPaidUsers(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小", example = "20") @RequestParam(defaultValue = "20") Integer size,
            @Parameter(description = "搜索关键词（用户名、手机号）") @RequestParam(required = false) String keyword,
            @Parameter(description = "注册时间开始") @RequestParam(required = false) String createTimeStart,
            @Parameter(description = "注册时间结束") @RequestParam(required = false) String createTimeEnd,
            @Parameter(description = "排序字段", example = "createTime") @RequestParam(defaultValue = "createTime") String sortField,
            @Parameter(description = "排序方向", example = "desc") @RequestParam(defaultValue = "desc") String sortOrder) {
        
        log.info("收到付费用户查询请求，页码: {}, 大小: {}", page, size);
        
        // 构建查询请求，固定membershipType为paid
        AdminUserDto.UserListRequest request = new AdminUserDto.UserListRequest();
        request.setPage(page);
        request.setSize(size);
        request.setKeyword(keyword);
        request.setSortField(sortField);
        request.setSortOrder(sortOrder);
        request.setMembershipType("paid"); // 固定为付费用户
        
        // 处理时间参数
        if (createTimeStart != null && !createTimeStart.isEmpty()) {
            try {
                request.setCreateTimeStart(java.time.LocalDateTime.parse(createTimeStart + "T00:00:00"));
            } catch (Exception e) {
                log.warn("创建时间开始参数格式错误: {}", createTimeStart);
            }
        }
        
        if (createTimeEnd != null && !createTimeEnd.isEmpty()) {
            try {
                request.setCreateTimeEnd(java.time.LocalDateTime.parse(createTimeEnd + "T23:59:59"));
            } catch (Exception e) {
                log.warn("创建时间结束参数格式错误: {}", createTimeEnd);
            }
        }
        
        return adminUserService.getUserList(request);
    }
}
