package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.entity.Course;
import com.zhentao.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 课程控制器
 */
@RestController
@RequestMapping("/api/course")
public class CourseController {
    
    @Autowired
    private CourseService courseService;
    
    /**
     * 获取课程详情
     * 
     * @param id 课程ID
     * @return 课程详情
     */
    @GetMapping("/detail/{id}")
    public Result<Course> getCourseDetail(@PathVariable Integer id) {
        try {
            Course course = courseService.getCourseById(id);
            if (course == null) {
                return Result.error("课程不存在");
            }
            return Result.success(course);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程列表（分页）
     * 
     * @param page 页码
     * @param pageSize 每页数量
     * @return 课程列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getCourseList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status) {
        try {
            Page<Course> pageObj = new Page<>(page, pageSize);
            LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
            // 如果指定了 status 参数，则按状态过滤（用于小程序端）
            // 如果没有指定 status，则返回所有状态的课程（用于管理端）
            if (status != null) {
                wrapper.eq(Course::getStatus, status);
            }
            wrapper.orderByDesc(Course::getIsRecommended)
                   .orderByDesc(Course::getRating)
                   .orderByDesc(Course::getCreatedTime);
            
            Page<Course> result = courseService.page(pageObj, wrapper);
            
            // 调试日志：检查查询结果
            System.out.println("===== 课程列表查询结果 =====");
            System.out.println("总记录数: " + result.getTotal());
            System.out.println("返回记录数: " + result.getRecords().size());
            if (!result.getRecords().isEmpty()) {
                Course firstCourse = result.getRecords().get(0);
                System.out.println("第一条课程数据:");
                System.out.println("  ID: " + firstCourse.getId());
                System.out.println("  Name: " + firstCourse.getName());
                System.out.println("  Status: " + firstCourse.getStatus());
            }
            System.out.println("=============================");
            
            Map<String, Object> data = new HashMap<>();
            data.put("list", result.getRecords());
            data.put("total", result.getTotal());
            data.put("page", result.getCurrent());
            data.put("pageSize", result.getSize());
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取推荐课程列表
     * 
     * @return 推荐课程列表
     */
    @GetMapping("/recommended")
    public Result<List<Course>> getRecommendedCourses() {
        try {
            List<Course> courseList = courseService.getRecommendedCourses();
            return Result.success(courseList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取推荐课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 购买课程
     * 
     * @param courseId 课程ID
     * @return 结果
     */
    @PostMapping("/purchase/{courseId}")
    public Result<String> purchaseCourse(@PathVariable Integer courseId) {
        try {
            // TODO: 实现购买逻辑
            Course course = courseService.getCourseById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }
            return Result.success("购买成功", "购买成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("购买失败：" + e.getMessage());
        }
    }
    
    /**
     * 【管理端】创建课程
     * 
     * @param course 课程信息
     * @return 结果
     */
    @PostMapping("/admin/create")
    public Result<Course> createCourse(@RequestBody Course course) {
        try {
            // 设置默认值
            if (course.getStatus() == null) {
                course.setStatus(1);
            }
            if (course.getIsRecommended() == null) {
                course.setIsRecommended(0);
            }
            if (course.getRating() == null) {
                course.setRating(0.0f);
            }
            if (course.getParticipants() == null) {
                course.setParticipants(0);
            }
            
            boolean success = courseService.save(course);
            if (success) {
                return Result.success(course);
            }
            return Result.error("创建课程失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 【管理端】更新课程
     * 
     * @param id 课程ID
     * @param course 课程信息
     * @return 结果
     */
    @PutMapping("/admin/update/{id}")
    public Result<Course> updateCourse(@PathVariable Integer id, @RequestBody Course course) {
        try {
            Course existCourse = courseService.getById(id);
            if (existCourse == null) {
                return Result.error("课程不存在");
            }
            
            course.setId(id);
            boolean success = courseService.updateById(course);
            if (success) {
                return Result.success(courseService.getById(id));
            }
            return Result.error("更新课程失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新课程失败：" + e.getMessage());
        }
    }
    
    /**
     * 【管理端】删除课程
     * 
     * @param id 课程ID
     * @return 结果
     */
    @DeleteMapping("/admin/delete/{id}")
    public Result<String> deleteCourse(@PathVariable Integer id) {
        try {
            Course existCourse = courseService.getById(id);
            if (existCourse == null) {
                return Result.error("课程不存在");
            }
            
            boolean success = courseService.removeById(id);
            if (success) {
                return Result.success("删除成功");
            }
            return Result.error("删除课程失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除课程失败：" + e.getMessage());
        }
    }
}

