package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.common.config.TokenUtils;
import com.example.entity.Account;
import com.example.entity.ResourceRating;
import com.example.service.ResourceRatingService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

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

/**
 * 资源评分控制器
 */
@RestController
@RequestMapping("/resourceRating")
public class ResourceRatingController {

    @Resource
    private ResourceRatingService resourceRatingService;
    
    /**
     * 获取资源评分列表（分页）
     */
    @GetMapping("/resource/{resourceId}")
    public Result findResourceRatingsPage(
            @PathVariable Integer resourceId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        // 查询评分列表
        List<ResourceRating> ratings = resourceRatingService.findByResourceId(resourceId);
        
        // 构建分页结果
        Map<String, Object> pageResult = new HashMap<>();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, ratings.size());
        
        // 截取当前页数据
        List<ResourceRating> pageRatings = ratings.subList(
            start < ratings.size() ? start : 0, 
            end < ratings.size() ? end : 0
        );
        
        pageResult.put("list", pageRatings);
        pageResult.put("total", ratings.size());
        pageResult.put("pageNum", pageNum);
        pageResult.put("pageSize", pageSize);
        
        return Result.success(pageResult);
    }
    
    /**
     * 获取资源平均评分
     */
    @GetMapping("/average/{resourceId}")
    public Result getAverageRating(@PathVariable Integer resourceId) {
        Double averageRating = resourceRatingService.getAverageRating(resourceId);
        return Result.success(averageRating);
    }
    
    /**
     * 获取资源评分数量
     */
    @GetMapping("/count/{resourceId}")
    public Result getRatingCount(@PathVariable Integer resourceId) {
        Integer count = resourceRatingService.getRatingCount(resourceId);
        return Result.success(count);
    }
    
    /**
     * 添加或更新评分
     */
    @PostMapping
    public Result add(@RequestBody ResourceRating resourceRating) {
        resourceRatingService.rateResource(resourceRating);
        return Result.success();
    }
    
    /**
     * 获取当前用户的所有评分
     */
    @GetMapping("/user")
    public Result getUserRatings() {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("401", "用户未登录");
        }
        
        // 验证用户是否为患者
        if (!"patient".equals(currentUser.getRole())) {
            return Result.error("403", "只有患者可以查看自己的评分");
        }
        
        // 获取用户评分列表
        List<ResourceRating> ratings = resourceRatingService.findByPatientId(currentUser.getId());
        return Result.success(ratings);
    }
    
    /**
     * 获取所有评分数据（用于推荐算法）
     */
    @GetMapping("/all")
    public Result getAllRatings() {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("401", "用户未登录");
        }
        
        // 验证用户是否为患者
        if (!"patient".equals(currentUser.getRole())) {
            return Result.error("403", "只有患者可以访问评分数据");
        }
        
        // 获取所有评分列表
        List<ResourceRating> ratings = resourceRatingService.findAll();
        return Result.success(ratings);
    }
    
    /**
     * 获取资源的平均评分和评分数量
     */
    @GetMapping("/resource/{resourceId}/stats")
    public Result getResourceRatingStats(@PathVariable Integer resourceId) {
        Double averageRating = resourceRatingService.getAverageRating(resourceId);
        Integer count = resourceRatingService.getRatingCount(resourceId);
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("averageRating", averageRating);
        stats.put("ratingCount", count);
        
        return Result.success(stats);
    }
    
    /**
     * 删除评价
     */
    @DeleteMapping("/{id}")
    public Result deleteRating(@PathVariable Integer id) {
        resourceRatingService.deleteRating(id);
        return Result.success();
    }
    
    /**
     * 根据资源ID查询评分记录
     */
    @GetMapping("/{resourceId}")
    public Result findByResourceId(@PathVariable Integer resourceId) {
        List<ResourceRating> ratings = resourceRatingService.findByResourceId(resourceId);
        double averageRating = resourceRatingService.getAverageRating(resourceId);
        Integer count = resourceRatingService.getRatingCount(resourceId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("ratings", ratings);
        result.put("averageRating", averageRating);
        result.put("count", count != null ? count : 0);
        
        return Result.success(result);
    }
} 