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.TreatmentResource;
import com.example.exception.CustomException;
import com.example.mapper.TreatmentResourceMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Comparator;
import java.util.stream.Collectors;

@Service
public class TreatmentResourceService {

    @Resource
    private TreatmentResourceMapper treatmentResourceMapper;
    
    public Page<TreatmentResource> search(Page<TreatmentResource> page, String keyword, String role) {
        if ("admin".equals(role)) {
            return treatmentResourceMapper.searchResourcesForAdmin(page, keyword);
        } else {
            return treatmentResourceMapper.searchResourcesForPatient(page, keyword);
        }
    }
    
    public List<TreatmentResource> findByCategoryId(Integer categoryId) {
        return treatmentResourceMapper.selectByCategoryId(categoryId);
    }
    
    public TreatmentResource findById(Integer id) {
        return treatmentResourceMapper.selectById(id);
    }
    
    public void add(TreatmentResource resource) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 允许管理员和医生添加资源
        if (!"admin".equals(currentUser.getRole()) && !"doctor".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无权限添加资源");
        }
        
        // 设置默认值
        resource.setPublisherId(currentUser.getId());
        resource.setVisitCount(0);
        resource.setDownloadCount(0);
        
        // 如果是医生添加，则默认为待审核状态
        if ("doctor".equals(currentUser.getRole())) {
            resource.setAuditStatus("待审核");
        } else {
            // 管理员添加的资源默认已审核
            resource.setAuditStatus("已通过");
        }
        
        resource.setCreateTime(LocalDateTime.now());
        
        treatmentResourceMapper.insert(resource);
    }
    
    public void update(TreatmentResource resource) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 仅允许管理员修改资源
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无权限修改资源");
        }
        
        // 检查资源是否存在
        TreatmentResource dbResource = treatmentResourceMapper.selectById(resource.getId());
        if (dbResource == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "资源不存在");
        }
        
        treatmentResourceMapper.updateById(resource);
    }
    
    public void delete(Integer id) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 仅允许管理员删除资源
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无权限删除资源");
        }
        
        // 检查资源是否存在
        TreatmentResource dbResource = treatmentResourceMapper.selectById(id);
        if (dbResource == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "资源不存在");
        }
        
        treatmentResourceMapper.deleteById(id);
    }
    
    public void changeAuditStatus(Integer id, String status) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        // 仅允许管理员审核资源
        if (!"admin".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "无权限审核资源");
        }
        
        // 检查资源是否存在
        TreatmentResource dbResource = treatmentResourceMapper.selectById(id);
        if (dbResource == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR.code, "资源不存在");
        }
        
        // 更新审核状态
        TreatmentResource resource = new TreatmentResource();
        resource.setId(id);
        resource.setAuditStatus(status);
        
        treatmentResourceMapper.updateById(resource);
    }
    
    public void incrementVisitCount(Integer id) {
        treatmentResourceMapper.incrementVisitCount(id);
    }
    
    public void incrementDownloadCount(Integer id) {
        treatmentResourceMapper.incrementDownloadCount(id);
    }
    
    public PageInfo<TreatmentResource> selectPage(TreatmentResource resource, Integer pageNum, Integer pageSize) {
        // 获取当前用户角色
        Account currentUser = TokenUtils.getCurrentUser();
        String role = currentUser != null ? currentUser.getRole() : "patient";
        
        // 使用PageHelper进行分页，与Admin页面一致
        PageHelper.startPage(pageNum, pageSize);
        
        // 获取查询关键词
        String keyword = resource.getTitle() != null ? resource.getTitle() : "";
        
        // 直接使用Mapper的查询方法
        List<TreatmentResource> list;
        if ("admin".equals(role)) {
            list = treatmentResourceMapper.selectAll(keyword);
        } else {
            list = treatmentResourceMapper.selectAllAudited(keyword);
        }
        
        // 创建PageInfo对象
        return new PageInfo<>(list);
    }

    /**
     * 查询特定发布者的资源
     */
    public PageInfo<TreatmentResource> findByPublisher(TreatmentResource resource, Integer pageNum, Integer pageSize) {
        // 使用PageHelper进行分页，与Admin页面一致
        PageHelper.startPage(pageNum, pageSize);
        
        // 获取查询关键词
        String keyword = resource.getTitle() != null ? resource.getTitle() : "";
        
        // 调用Mapper查询方法，需要添加对应的Mapper方法
        List<TreatmentResource> list = treatmentResourceMapper.selectByPublisher(resource.getPublisherId(), keyword);
        
        // 创建PageInfo对象
        return new PageInfo<>(list);
    }

    /**
     * 获取资源使用情况统计数据
     * @return 资源使用情况统计数据
     */
    public Map<String, Object> getResourceStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            // 查询所有资源
            List<TreatmentResource> resources = treatmentResourceMapper.selectList(null);
            
            // 按分类统计资源数量
            Map<Integer, Long> countByCategory = resources.stream()
                    .collect(Collectors.groupingBy(TreatmentResource::getCategoryId, Collectors.counting()));
                    
            // 统计总访问次数和总下载次数
            int totalVisits = resources.stream()
                    .mapToInt(r -> r.getVisitCount() != null ? r.getVisitCount() : 0)
                    .sum();
                    
            int totalDownloads = resources.stream()
                    .mapToInt(r -> r.getDownloadCount() != null ? r.getDownloadCount() : 0)
                    .sum();
            
            // 访问次数最多的资源TOP5
            List<TreatmentResource> topVisitResources = resources.stream()
                    .sorted(Comparator.comparing(r -> r.getVisitCount() != null ? -r.getVisitCount() : 0))
                    .limit(5)
                    .collect(Collectors.toList());
                    
            // 下载次数最多的资源TOP5
            List<TreatmentResource> topDownloadResources = resources.stream()
                    .sorted(Comparator.comparing(r -> r.getDownloadCount() != null ? -r.getDownloadCount() : 0))
                    .limit(5)
                    .collect(Collectors.toList());
            
            // 按资源分类统计访问次数和下载次数
            Map<Integer, Integer> visitsByCategory = new HashMap<>();
            Map<Integer, Integer> downloadsByCategory = new HashMap<>();
            
            for (TreatmentResource resource : resources) {
                Integer categoryId = resource.getCategoryId();
                Integer visitCount = resource.getVisitCount() != null ? resource.getVisitCount() : 0;
                Integer downloadCount = resource.getDownloadCount() != null ? resource.getDownloadCount() : 0;
                
                visitsByCategory.put(categoryId, visitsByCategory.getOrDefault(categoryId, 0) + visitCount);
                downloadsByCategory.put(categoryId, downloadsByCategory.getOrDefault(categoryId, 0) + downloadCount);
            }
            
            // 构建返回结果
            statistics.put("totalResources", resources.size());
            statistics.put("totalVisits", totalVisits);
            statistics.put("totalDownloads", totalDownloads);
            statistics.put("countByCategory", countByCategory);
            statistics.put("visitsByCategory", visitsByCategory);
            statistics.put("downloadsByCategory", downloadsByCategory);
            statistics.put("topVisitResources", topVisitResources);
            statistics.put("topDownloadResources", topDownloadResources);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return statistics;
    }
} 