package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.ResourceCategory;
import com.example.entity.TreatmentResource;
import com.example.service.ResourceCategoryService;
import com.example.service.TreatmentResourceService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 心理治疗资源控制器
 */
@RestController
@RequestMapping("/treatmentResource")
public class TreatmentResourceController {

    @Resource
    private TreatmentResourceService treatmentResourceService;
    
    @Resource
    private ResourceCategoryService resourceCategoryService;
    
    /**
     * 分页搜索资源
     */
    @GetMapping("/search")
    public Result search(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String keyword) {
        
        // 获取当前用户角色
        Account currentUser = TokenUtils.getCurrentUser();
        String role = currentUser != null ? currentUser.getRole() : "patient";
        
        Page<TreatmentResource> page = new Page<>(pageNum, pageSize);
        page = treatmentResourceService.search(page, keyword, role);
        
        return Result.success(page);
    }
    
    /**
     * 分页查询
     */
    @GetMapping("/selectPage")
    public Result selectPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            TreatmentResource resource) {
        
        PageInfo<TreatmentResource> pageInfo = treatmentResourceService.selectPage(resource, pageNum, pageSize);
        return Result.success(pageInfo);
    }
    
    /**
     * 根据分类获取资源
     */
    @GetMapping("/category/{categoryId}")
    public Result findByCategoryId(@PathVariable Integer categoryId) {
        List<TreatmentResource> list = treatmentResourceService.findByCategoryId(categoryId);
        return Result.success(list);
    }
    
    /**
     * 根据ID获取资源
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        TreatmentResource resource = treatmentResourceService.findById(id);
        treatmentResourceService.incrementVisitCount(id);
        return Result.success(resource);
    }
    
    /**
     * 新增资源
     */
    @PostMapping
    public Result add(@RequestBody TreatmentResource resource) {
        treatmentResourceService.add(resource);
        return Result.success();
    }
    
    /**
     * 更新资源
     */
    @PutMapping
    public Result update(@RequestBody TreatmentResource resource) {
        treatmentResourceService.update(resource);
        return Result.success();
    }
    
    /**
     * 删除资源
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        treatmentResourceService.delete(id);
        return Result.success();
    }
    
    /**
     * 审核资源
     */
    @PutMapping("/audit/{id}")
    public Result audit(@PathVariable Integer id, @RequestParam String status) {
        treatmentResourceService.changeAuditStatus(id, status);
        return Result.success();
    }
    
    /**
     * 下载资源
     */
    @GetMapping("/download/{id}")
    public Result download(@PathVariable Integer id) {
        TreatmentResource resource = treatmentResourceService.findById(id);
        if (resource != null) {
            treatmentResourceService.incrementDownloadCount(id);
        }
        return Result.success(resource);
    }

    /**
     * 增加资源访问次数（新路径）
     */
    @PutMapping("/incrementVisit/{id}")
    public Result incrementVisit(@PathVariable Integer id) {
        treatmentResourceService.incrementVisitCount(id);
        return Result.success();
    }

    /**
     * 增加资源下载次数（新路径）
     */
    @PutMapping("/incrementDownload/{id}")
    public Result incrementDownload(@PathVariable Integer id) {
        treatmentResourceService.incrementDownloadCount(id);
        return Result.success();
    }

    /**
     * 查询医生自己发布的资源
     */
    @GetMapping("/myResources")
    public Result myResources(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            TreatmentResource resource) {
        
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("401", "未登录");
        }
        
        // 只有医生可以查询自己发布的资源
        if (!"doctor".equals(currentUser.getRole())) {
            return Result.error("403", "无权限查询");
        }
        
        // 强制设置发布者ID为当前登录用户
        resource.setPublisherId(currentUser.getId());
        
        // 使用PageHelper进行分页
        PageInfo<TreatmentResource> pageInfo = treatmentResourceService.findByPublisher(resource, pageNum, pageSize);
        
        return Result.success(pageInfo);
    }

    /**
     * 获取资源使用情况统计数据
     */
    @GetMapping("/statistics")
    public Result getStatistics() {
        return Result.success(treatmentResourceService.getResourceStatistics());
    }

    /**
     * 获取所有已审核通过的心理资源
     */
    @GetMapping("/all")
    public Result getAllApprovedResources(@RequestParam(required = false) String auditStatus) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("401", "用户未登录");
        }
        
        // 查询关键词为空，表示获取所有资源
        String keyword = "";
        
        // 根据审核状态查询资源
        List<TreatmentResource> resources;
        
        if (auditStatus != null && !auditStatus.isEmpty()) {
            // 使用TreatmentResourceService的selectPage方法
            TreatmentResource queryParam = new TreatmentResource();
            queryParam.setAuditStatus(auditStatus);
            // 这里不使用分页，所以传一个很大的pageSize
            PageInfo<TreatmentResource> pageInfo = treatmentResourceService.selectPage(queryParam, 1, 1000);
            resources = pageInfo.getList();
        } else {
            // 默认只返回已通过审核的资源
            TreatmentResource queryParam = new TreatmentResource();
            queryParam.setAuditStatus("已通过");
            // 这里不使用分页，所以传一个很大的pageSize
            PageInfo<TreatmentResource> pageInfo = treatmentResourceService.selectPage(queryParam, 1, 1000);
            resources = pageInfo.getList();
        }
        
        return Result.success(resources);
    }
} 