package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.PointsFreezeRecord;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtils;

/**
 * 积分冻结API控制器
 */
@RestController
@RequestMapping("/api/points")
public class PointsApiController {

    private static final Logger logger = LoggerFactory.getLogger(PointsApiController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取用户积分信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getPointsInfo(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            User user = userService.findByUsername(username);
            Integer totalPoints = user.getPoints();
            Integer frozenPoints = user.getFrozenPoints();
            Integer availablePoints = user.getAvailablePoints();

            Map<String, Object> pointsInfo = new HashMap<>();
            pointsInfo.put("totalPoints", totalPoints);
            pointsInfo.put("frozenPoints", frozenPoints);
            pointsInfo.put("availablePoints", availablePoints);

            response.put("success", true);
            response.put("data", pointsInfo);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取积分信息失败", e);
            response.put("success", false);
            response.put("message", "获取积分信息失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取用户积分冻结记录
     */
    @GetMapping("/freeze-records")
    public ResponseEntity<Map<String, Object>> getFreezeRecords(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<PointsFreezeRecord> records = userService.getPointsFreezeRecords(username);

            response.put("success", true);
            response.put("data", records);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取冻结记录失败", e);
            response.put("success", false);
            response.put("message", "获取冻结记录失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取积分使用历史（充值和使用记录）
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getPointsHistory(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 获取积分使用历史
            List<Map<String, Object>> history = userService.getPointsHistory(username, page, size);

            response.put("success", true);
            response.put("data", history);
            response.put("page", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取积分使用历史失败", e);
            response.put("success", false);
            response.put("message", "获取积分使用历史失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 手动处理过期冻结记录（管理员功能）
     */
    @PostMapping("/process-expired")
    public ResponseEntity<Map<String, Object>> processExpiredRecords(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 这里可以添加管理员权限检查
            // 暂时允许所有用户触发
            
            int processedCount = userService.processExpiredFrozenRecords();
            
            response.put("success", true);
            response.put("message", "处理过期记录完成");
            response.put("processedCount", processedCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理过期记录失败", e);
            response.put("success", false);
            response.put("message", "处理过期记录失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }
}
