package com.qqchen.deploy.backend.schedule.service.impl;

import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.qqchen.deploy.backend.schedule.dto.ScheduleJobCategoryDTO;
import com.qqchen.deploy.backend.schedule.entity.ScheduleJobCategory;
import com.qqchen.deploy.backend.schedule.query.ScheduleJobCategoryQuery;
import com.qqchen.deploy.backend.schedule.repository.IScheduleJobCategoryRepository;
import com.qqchen.deploy.backend.schedule.repository.IScheduleJobRepository;
import com.qqchen.deploy.backend.schedule.service.IScheduleJobCategoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务分类Service实现
 * 
 * @author qichen
 */
@Slf4j
@Service
public class ScheduleJobCategoryServiceImpl extends BaseServiceImpl<ScheduleJobCategory, ScheduleJobCategoryDTO, ScheduleJobCategoryQuery, Long>
        implements IScheduleJobCategoryService {

    @Resource
    private IScheduleJobCategoryRepository categoryRepository;

    @Resource
    private IScheduleJobRepository jobRepository;

    @Override
    @Transactional
    public ScheduleJobCategoryDTO create(ScheduleJobCategoryDTO dto) {
        // 检查编码唯一性
        if (categoryRepository.existsByCodeAndDeletedFalse(dto.getCode())) {
            throw new BusinessException(ResponseCode.DATA_ALREADY_EXISTS, new Object[]{"分类编码", dto.getCode()});
        }
        return super.create(dto);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 检查是否有关联的任务
        Long jobCount = jobRepository.countByCategoryIdAndDeletedFalse(id);
        if (jobCount > 0) {
            throw new BusinessException(ResponseCode.DATA_IN_USE, new Object[]{"该分类下存在任务"});
        }
        super.delete(id);
    }

    @Override
    public Page<ScheduleJobCategoryDTO> page(ScheduleJobCategoryQuery query) {
        Page<ScheduleJobCategoryDTO> page = super.page(query);

        // 统计每个分类的任务数量
        List<ScheduleJobCategoryDTO> content = page.getContent().stream()
                .peek(category -> {
                    Long count = jobRepository.countByCategoryIdAndDeletedFalse(category.getId());
                    category.setJobCount(count);
                })
                .collect(Collectors.toList());

        return new PageImpl<>(content, page.getPageable(), page.getTotalElements());
    }
}

