package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.GenericStatus;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.entity.CoursePackage;
import com.lesingle.edu.entity.Theme;
import com.lesingle.edu.mapper.CoursePackageMapper;
import com.lesingle.edu.mapper.ThemeMapper;
import com.lesingle.edu.service.ThemeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 主题字典服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ThemeServiceImpl extends ServiceImpl<ThemeMapper, Theme> implements ThemeService {

    private final ThemeMapper themeMapper;
    private final CoursePackageMapper courseMapper;

    /**
     * 查询所有主题
     */
    @Override
    public List<Theme> findAll() {
        log.info("查询所有主题");
        List<Theme> result = lambdaQuery()
                .orderByAsc(Theme::getSortOrder)
                .list();
        log.info("查询所有主题成功，count={}", result.size());
        return result;
    }

    /**
     * 查询主题详情
     */
    @Override
    public Theme findById(Long id) {
        log.info("查询主题详情，id={}", id);
        Theme theme = themeMapper.selectById(id);
        if (theme == null) {
            log.warn("主题不存在，id={}", id);
            throw new BusinessException("主题不存在");
        }
        return theme;
    }

    /**
     * 创建主题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Theme create(String name, String description, String color, Integer sortOrder) {
        log.info("创建主题，name={}, sortOrder={}", name, sortOrder);
        // 获取最大排序号
        Integer maxSortOrder = themeMapper.selectList(null)
                .stream()
                .map(Theme::getSortOrder)
                .max(Integer::compareTo)
                .orElse(0);

        Theme theme = new Theme();
        theme.setName(name);
        theme.setDescription(description);
        theme.setColor(color);
        theme.setSortOrder(sortOrder != null ? sortOrder : maxSortOrder + 1);
        theme.setStatus(GenericStatus.ACTIVE.getCode());
        themeMapper.insert(theme);

        log.info("主题创建成功，id={}", theme.getId());
        return theme;
    }

    /**
     * 更新主题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Theme update(Long id, String name, String description, String color, Integer sortOrder, String status) {
        log.info("更新主题，id={}, name={}, status={}", id, name, status);
        Theme theme = themeMapper.selectById(id);
        if (theme == null) {
            log.warn("主题不存在，id={}", id);
            throw new BusinessException("主题不存在");
        }

        if (name != null) {
            theme.setName(name);
        }
        if (description != null) {
            theme.setDescription(description);
        }
        if (color != null) {
            theme.setColor(color);
        }
        if (sortOrder != null) {
            theme.setSortOrder(sortOrder);
        }
        if (status != null) {
            theme.setStatus(status);
        }

        themeMapper.updateById(theme);
        log.info("主题更新成功，id={}", id);
        return theme;
    }

    /**
     * 删除主题
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        log.info("删除主题，id={}", id);
        // 检查是否有关联课程
        Long courseCount = courseMapper.selectCount(
                new LambdaQueryWrapper<CoursePackage>().eq(CoursePackage::getThemeId, id)
        );

        if (courseCount > 0) {
            log.warn("删除主题失败，该主题下有 {} 个课程包，id={}", courseCount, id);
            throw new BusinessException("该主题下有 " + courseCount + " 个课程包，无法删除");
        }

        themeMapper.deleteById(id);
        log.info("主题删除成功，id={}", id);
    }

    /**
     * 重新排序
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reorder(List<Long> ids) {
        log.info("重新排序主题，count={}", ids.size());
        for (int i = 0; i < ids.size(); i++) {
            Theme theme = themeMapper.selectById(ids.get(i));
            if (theme != null) {
                theme.setSortOrder(i + 1);
                themeMapper.updateById(theme);
            }
        }
        log.info("主题重新排序成功");
    }
}
