package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.entity.MatchmakerCourse;
import com.zhentao.mapper.MatchmakerCourseMapper;
import com.zhentao.service.MatchmakerCourseService;
import com.zhentao.service.PointsManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 红娘课程服务实现类
 */
@Service
public class MatchmakerCourseServiceImpl extends ServiceImpl<MatchmakerCourseMapper, MatchmakerCourse> implements MatchmakerCourseService {
    
    @Autowired(required = false)
    private PointsManageService pointsManageService;
    
    @Autowired
    private MatchmakerCourseMapper matchmakerCourseMapper;
    
    @Override
    public List<MatchmakerCourse> getActiveCourses(String categoryType) {
        LambdaQueryWrapper<MatchmakerCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MatchmakerCourse::getStatus, 1);

        // basic -> 基础课程（difficulty = 1）
        // advanced -> 进阶课程（difficulty = 2）
        // premium -> 精品课程（is_recommended = 1）
        if ("basic".equalsIgnoreCase(categoryType)) {
            wrapper.eq(MatchmakerCourse::getDifficulty, 1);
        } else if ("advanced".equalsIgnoreCase(categoryType)) {
            wrapper.eq(MatchmakerCourse::getDifficulty, 2);
        } else if ("premium".equalsIgnoreCase(categoryType)) {
            wrapper.eq(MatchmakerCourse::getIsRecommended, 1);
        }

        wrapper.orderByDesc(MatchmakerCourse::getIsRecommended)
               .orderByDesc(MatchmakerCourse::getRating)
               .orderByDesc(MatchmakerCourse::getCreatedTime);
        return list(wrapper);
    }
    
    @Override
    public List<MatchmakerCourse> getCoursesByCategory(String categoryName) {
        LambdaQueryWrapper<MatchmakerCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MatchmakerCourse::getStatus, 1)
               .eq(MatchmakerCourse::getCategoryName, categoryName)
               .orderByDesc(MatchmakerCourse::getCreatedTime);
        return list(wrapper);
    }
    
    @Override
    public MatchmakerCourse getCourseById(Integer id) {
        return getById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeCourse(Integer makerId, Integer courseId, Integer points) {
        if (makerId == null || courseId == null || points == null || points <= 0) {
            return false;
        }
        
        // 检查课程是否存在
        MatchmakerCourse course = getById(courseId);
        if (course == null) {
            return false;
        }
        
        // 检查是否已兑换过该课程
        if (hasExchanged(makerId, courseId)) {
            System.out.println("红娘已兑换过该课程，makerId=" + makerId + ", courseId=" + courseId);
            return false;
        }
        
        // 扣除积分
        if (pointsManageService != null) {
            boolean deducted = pointsManageService.deductPoints(makerId, points, "兑换红娘课程: " + course.getName());
            if (!deducted) {
                System.out.println("积分扣除失败，makerId=" + makerId + ", points=" + points);
                return false;
            }
        } else {
            System.out.println("警告：PointsManageService未注入，跳过积分扣除");
        }
        
        // 记录兑换信息到数据库
        try {
            matchmakerCourseMapper.insertCourseExchange(makerId, courseId, points, new Date());
            
            // 更新课程参与人数
            course.setParticipants(course.getParticipants() != null ? course.getParticipants() + 1 : 1);
            updateById(course);
            
            System.out.println("红娘课程兑换成功，makerId=" + makerId + ", courseId=" + courseId + ", points=" + points);
            return true;
        } catch (Exception e) {
            System.err.println("记录兑换信息失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("记录兑换信息失败", e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getPurchasedCourses(Integer makerId) {
        if (makerId == null) {
            return new ArrayList<>();
        }
        
        try {
            List<Map<String, Object>> result = matchmakerCourseMapper.selectPurchasedCourses(makerId);
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            System.err.println("查询已兑换课程失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean hasExchanged(Integer makerId, Integer courseId) {
        if (makerId == null || courseId == null) {
            return false;
        }
        return matchmakerCourseMapper.checkExchanged(makerId, courseId) > 0;
    }
    
    @Override
    public List<String> getAllCategories() {
        LambdaQueryWrapper<MatchmakerCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MatchmakerCourse::getStatus, 1)
               .select(MatchmakerCourse::getCategoryName)
               .groupBy(MatchmakerCourse::getCategoryName);
        List<MatchmakerCourse> courses = list(wrapper);
        return courses.stream()
                .map(MatchmakerCourse::getCategoryName)
                .filter(name -> name != null && !name.isEmpty())
                .distinct()
                .collect(Collectors.toList());
    }
}
