package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.config.TokenUtils;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.ResourceRating;
import com.example.entity.TreatmentResource;
import com.example.exception.CustomException;
import com.example.mapper.ResourceRatingMapper;
import com.example.mapper.TreatmentResourceMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ResourceRatingService {

    @Resource
    private ResourceRatingMapper resourceRatingMapper;
    
    @Resource
    private TreatmentResourceMapper treatmentResourceMapper;
    
    /**
     * 添加评分
     */
    public void add(ResourceRating resourceRating) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 只有患者可以添加评分
        if (!"patient".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有患者可以评分");
        }
        
        // 设置患者ID
        resourceRating.setPatientId(currentUser.getId());
        
        // 检查评分是否有效
        if (resourceRating.getRating() == null || resourceRating.getRating() < 1 || resourceRating.getRating() > 5) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "评分必须在1-5之间");
        }
        
        // 检查是否已经评分过
        int count = resourceRatingMapper.countByResourceIdAndPatientId(resourceRating.getResourceId(), currentUser.getId());
        if (count > 0) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "您已经评价过该资源");
        }
        
        // 设置创建时间
        resourceRating.setCreateTime(LocalDateTime.now());
        
        // 保存评分
        resourceRatingMapper.insert(resourceRating);
    }
    
    /**
     * 根据资源ID查询评分记录
     */
    public List<ResourceRating> findByResourceId(Integer resourceId) {
        return resourceRatingMapper.selectByResourceId(resourceId);
    }
    
    /**
     * 获取资源的平均评分
     */
    public double getAverageRating(Integer resourceId) {
        return resourceRatingMapper.getAverageRating(resourceId);
    }
    
    public Integer getRatingCount(Integer resourceId) {
        return resourceRatingMapper.getRatingCount(resourceId);
    }
    
    public void rateResource(ResourceRating rating) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 只有患者才能评价资源
        if (!"patient".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "只有患者才能评价资源");
        }
        
        // 检查资源是否存在
        TreatmentResource resource = treatmentResourceMapper.selectById(rating.getResourceId());
        if (resource == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "资源不存在");
        }
        
        // 检查资源是否已通过审核
        if (!"已通过".equals(resource.getAuditStatus())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "资源未通过审核，无法评价");
        }
        
        // 检查患者是否已经评价过该资源
        ResourceRating existingRating = resourceRatingMapper.findByResourceAndPatient(
                rating.getResourceId(), currentUser.getId());
        
        if (existingRating != null) {
            // 更新评价
            existingRating.setRating(rating.getRating());
            existingRating.setComment(rating.getComment());
            resourceRatingMapper.updateById(existingRating);
        } else {
            // 新增评价
            rating.setPatientId(currentUser.getId());
            rating.setCreateTime(LocalDateTime.now());
            resourceRatingMapper.insert(rating);
        }
    }
    
    public void deleteRating(Integer id) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 查询评价
        ResourceRating rating = resourceRatingMapper.selectById(id);
        if (rating == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "评价不存在");
        }
        
        // 只有评价的患者本人或管理员才能删除评价
        if (!currentUser.getId().equals(rating.getPatientId()) && !"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无权限删除该评价");
        }
        
        resourceRatingMapper.deleteById(id);
    }
    
    /**
     * 根据患者ID查询评分记录
     */
    public List<ResourceRating> findByPatientId(Integer patientId) {
        LambdaQueryWrapper<ResourceRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ResourceRating::getPatientId, patientId);
        queryWrapper.orderByDesc(ResourceRating::getCreateTime);
        return resourceRatingMapper.selectList(queryWrapper);
    }
    
    /**
     * 查询所有评分记录
     */
    public List<ResourceRating> findAll() {
        LambdaQueryWrapper<ResourceRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ResourceRating::getCreateTime);
        return resourceRatingMapper.selectList(queryWrapper);
    }
} 