package com.dora.controller;

import com.dora.dto.ApiResponse;
import com.dora.dto.WithdrawDto;
import com.dora.service.AdminWithdrawService;
import com.dora.util.JwtUtil;
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.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;

/**
 * 管理员提现审核控制器
 */
@RestController
@RequestMapping("/admin/withdraw")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "管理员提现审核", description = "管理员提现审核相关接口")
public class AdminWithdrawController {

    private final AdminWithdrawService adminWithdrawService;
    private final JwtUtil jwtUtil;

    @PostMapping("/review")
    @Operation(summary = "审核提现申请", description = "管理员审核用户的提现申请")
    public ApiResponse<String> reviewWithdraw(
            @Valid @RequestBody WithdrawDto.AdminReviewRequest request,
            HttpServletRequest httpRequest) {
        
        // 获取管理员ID（从JWT token中获取）
        Long adminId = getCurrentAdminId(httpRequest);
        
        return adminWithdrawService.reviewWithdraw(adminId, request);
    }

    @PostMapping("/{withdrawId}/audit")
    @Operation(summary = "审核提现申请(REST风格)", description = "兼容前端调用: POST /admin/withdraw/{withdrawId}/audit?status=1&reason=xxx&transactionNo=xxx&feeAmount=xxx&actualAmount=xxx")
    public ApiResponse<String> auditWithdraw(
            @Parameter(description = "提现申请ID") @PathVariable Long withdrawId,
            @Parameter(description = "审核状态（1通过/2拒绝）") @RequestParam Integer status,
            @Parameter(description = "拒绝原因（可选）") @RequestParam(required = false) String reason,
            @Parameter(description = "第三方交易流水号（通过时可填）") @RequestParam(required = false) String transactionNo,
            @Parameter(description = "手续费金额（通过时可填）") @RequestParam(required = false) java.math.BigDecimal feeAmount,
            @Parameter(description = "实际到账金额（通过时必填）") @RequestParam(required = false) java.math.BigDecimal actualAmount,
            HttpServletRequest httpRequest) {
        Long adminId = getCurrentAdminId(httpRequest);
        WithdrawDto.AdminReviewRequest req = new WithdrawDto.AdminReviewRequest();
        req.setWithdrawId(withdrawId);
        req.setStatus(status);
        req.setReason(reason);
        req.setTransactionNo(transactionNo);
        req.setFeeAmount(feeAmount);
        req.setActualAmount(actualAmount);
        return adminWithdrawService.reviewWithdraw(adminId, req);
    }

    @PostMapping(value = "/{withdrawId}/audit", consumes = "application/json")
    @Operation(summary = "审核提现申请(JSON)", description = "兼容前端调用: POST /admin/withdraw/{withdrawId}/audit，Body: {status, reason}")
    public ApiResponse<String> auditWithdrawJson(
            @Parameter(description = "提现申请ID") @PathVariable Long withdrawId,
            @RequestBody AuditBody body,
            HttpServletRequest httpRequest) {
        Long adminId = getCurrentAdminId(httpRequest);
        if (body == null || body.getStatusIntOrNull() == null) {
            return ApiResponse.error(400, "缺少必要参数: status");
        }
        WithdrawDto.AdminReviewRequest req = new WithdrawDto.AdminReviewRequest();
        req.setWithdrawId(withdrawId);
        req.setStatus(body.getStatusIntOrNull());
        req.setReason(body.getReason());
        req.setTransactionNo(body.getTransactionNo());
        req.setFeeAmount(body.getFeeAmount());
        req.setActualAmount(body.getActualAmount());
        return adminWithdrawService.reviewWithdraw(adminId, req);
    }

    /**
     * 审核 JSON 请求体
     */
    public static class AuditBody {
        private Object status;
        private String reason;
        private String transactionNo;
        private java.math.BigDecimal feeAmount;
        private java.math.BigDecimal actualAmount;

        public Object getStatus() { return status; }
        public void setStatus(Object status) { this.status = status; }
        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
        public String getTransactionNo() { return transactionNo; }
        public void setTransactionNo(String transactionNo) { this.transactionNo = transactionNo; }
        public java.math.BigDecimal getFeeAmount() { return feeAmount; }
        public void setFeeAmount(java.math.BigDecimal feeAmount) { this.feeAmount = feeAmount; }
        public java.math.BigDecimal getActualAmount() { return actualAmount; }
        public void setActualAmount(java.math.BigDecimal actualAmount) { this.actualAmount = actualAmount; }

        public Integer getStatusIntOrNull() {
            if (status == null) return null;
            if (status instanceof Integer) return (Integer) status;
            if (status instanceof Number) return ((Number) status).intValue();
            if (status instanceof Boolean) return ((Boolean) status) ? 1 : 2;
            if (status instanceof String) {
                String s = ((String) status).trim().toLowerCase();
                if ("true".equals(s) || "approve".equals(s) || "approved".equals(s) || "pass".equals(s)) return 1;
                if ("false".equals(s) || "reject".equals(s) || "rejected".equals(s) || "deny".equals(s)) return 2;
                try { return Integer.parseInt(s); } catch (Exception ignore) {}
            }
            return null;
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取提现申请列表", description = "管理员查看所有用户的提现申请列表")
    public ApiResponse<WithdrawDto.AdminWithdrawListResponse> getWithdrawList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "审核状态筛选") @RequestParam(required = false) Integer status,
            @Parameter(description = "用户ID筛选") @RequestParam(required = false) Long userId,
            @Parameter(description = "提现账户类型筛选") @RequestParam(required = false) String accountType) {
        
        WithdrawDto.AdminWithdrawListRequest request = new WithdrawDto.AdminWithdrawListRequest();
        request.setPage(page);
        request.setSize(size);
        request.setStatus(status);
        request.setUserId(userId);
        request.setAccountType(accountType);
        
        return adminWithdrawService.getWithdrawList(request);
    }

    @GetMapping("/detail/{withdrawId}")
    @Operation(summary = "获取提现申请详情", description = "管理员查看特定提现申请的详细信息")
    public ApiResponse<WithdrawDto.AdminWithdrawItem> getWithdrawDetail(
            @Parameter(description = "提现申请ID") @PathVariable Long withdrawId) {
        
        return adminWithdrawService.getWithdrawDetail(withdrawId);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取提现审核统计信息", description = "获取各种状态的提现申请统计数据")
    public ApiResponse<WithdrawDto.WithdrawStatusStats> getWithdrawStats() {
        return adminWithdrawService.getWithdrawStats();
    }

    @PostMapping("/batch-review")
    @Operation(summary = "批量审核提现申请", description = "管理员批量审核多个提现申请")
    public ApiResponse<String> batchReviewWithdraw(
            @RequestBody BatchReviewRequest request,
            HttpServletRequest httpRequest) {
        
        // 获取管理员ID（从JWT token中获取）
        Long adminId = getCurrentAdminId(httpRequest);
        
        return adminWithdrawService.batchReviewWithdraw(
            adminId, 
            request.getWithdrawIds(), 
            request.getStatus(), 
            request.getReason()
        );
    }

    /**
     * 批量审核请求DTO
     */
    public static class BatchReviewRequest {
        private List<Long> withdrawIds;
        private Integer status;
        private String reason;

        public List<Long> getWithdrawIds() {
            return withdrawIds;
        }

        public void setWithdrawIds(List<Long> withdrawIds) {
            this.withdrawIds = withdrawIds;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }
    }

    /**
     * 从请求中获取当前管理员ID
     */
    private Long getCurrentAdminId(HttpServletRequest request) {
        try {
            // 从Header中获取token
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw new RuntimeException("未提供有效的认证token");
            }
            
            String token = authHeader.substring(7);
            
            // 验证token有效性
            if (!jwtUtil.validateToken(token)) {
                throw new RuntimeException("token无效或已过期");
            }
            
            // 检查是否为管理员token
            if (!jwtUtil.isAdminToken(token)) {
                throw new RuntimeException("非管理员token，无权访问");
            }
            
            // 获取管理员ID
            return jwtUtil.getAdminIdFromToken(token);
            
        } catch (Exception e) {
            log.warn("获取管理员ID失败", e);
            throw new RuntimeException("获取管理员身份失败：" + e.getMessage());
        }
    }
} 