package com.zhentao.controller;

import com.zhentao.entity.MatchmakerCourse;
import com.zhentao.service.MatchmakerCourseService;
import com.zhentao.common.Result;
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/matchmaker-course")
public class MatchmakerCourseController {
    
    @Autowired
    private MatchmakerCourseService matchmakerCourseService;
    
    /**
     * 获取所有启用的红娘课程列表，可按分类类型筛选
     */
    @GetMapping("/list")
    public Result<List<MatchmakerCourse>> getCourseList(@RequestParam(value = "categoryType", required = false, defaultValue = "all") String categoryType) {
        try {
            List<MatchmakerCourse> courses = matchmakerCourseService.getActiveCourses(categoryType);
            return Result.success(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据分类获取红娘课程列表
     */
    @GetMapping("/list/category")
    public Result<List<MatchmakerCourse>> getCoursesByCategory(@RequestParam String categoryName) {
        try {
            List<MatchmakerCourse> courses = matchmakerCourseService.getCoursesByCategory(categoryName);
            return Result.success(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有课程分类
     */
    @GetMapping("/categories")
    public Result<List<String>> getCategories() {
        try {
            List<String> categories = matchmakerCourseService.getAllCategories();
            return Result.success(categories);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取分类列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取红娘课程详情
     */
    @GetMapping("/detail/{id}")
    public Result<MatchmakerCourse> getCourseDetail(@PathVariable Integer id) {
        try {
            MatchmakerCourse course = matchmakerCourseService.getCourseById(id);
            if (course == null) {
                return Result.error("课程不存在");
            }
            return Result.success(course);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取课程详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查红娘是否已兑换某课程
     */
    @GetMapping("/check-exchanged")
    public Result<Map<String, Object>> checkExchanged(@RequestParam Integer makerId, @RequestParam Integer courseId) {
        try {
            boolean exchanged = matchmakerCourseService.hasExchanged(makerId, courseId);
            Map<String, Object> data = new HashMap<>();
            data.put("exchanged", exchanged);
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查兑换状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 积分兑换课程
     */
    @PostMapping("/exchange")
    public Result<Map<String, Object>> exchangeCourse(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer makerId = requestBody.get("makerId") != null ? Integer.valueOf(requestBody.get("makerId").toString()) : null;
            Integer courseId = requestBody.get("courseId") != null ? Integer.valueOf(requestBody.get("courseId").toString()) : null;
            Integer points = requestBody.get("points") != null ? Integer.valueOf(requestBody.get("points").toString()) : null;
            
            if (makerId == null || courseId == null || points == null) {
                return Result.error("参数不完整");
            }
            
            // 检查课程是否存在
            MatchmakerCourse course = matchmakerCourseService.getCourseById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }
            
            // 检查是否已兑换
            if (matchmakerCourseService.hasExchanged(makerId, courseId)) {
                return Result.error("您已兑换过该课程");
            }
            
            // 调用服务层进行兑换
            boolean success = matchmakerCourseService.exchangeCourse(makerId, courseId, points);
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("courseId", courseId);
                data.put("courseName", course.getName());
                data.put("pointsUsed", points);
                return Result.success("兑换成功", data);
            }
            return Result.error("兑换失败，请检查积分余额");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("兑换失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取已兑换的课程列表
     */
    @GetMapping("/purchased")
    public Result<List<Map<String, Object>>> getPurchasedCourses(@RequestParam Integer makerId) {
        try {
            if (makerId == null) {
                return Result.error("红娘ID不能为空");
            }
            
            List<Map<String, Object>> purchasedList = matchmakerCourseService.getPurchasedCourses(makerId);
            return Result.success(purchasedList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取已兑换课程失败：" + e.getMessage());
        }
    }
}
