package com.seer.teach.admin.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.admin.convert.VersionConvert;
import com.seer.teach.admin.response.VersionMappingResp;
import com.seer.teach.admin.response.VersionResp;
import com.seer.teach.admin.service.AdminVersionsService;
import com.seer.teach.teacher.module.entity.MaterialEntity;
import com.seer.teach.teacher.module.entity.VersionsEntity;
import com.seer.teach.teacher.service.MaterialService;
import com.seer.teach.teacher.service.VersionsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 管理端版本服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-10-29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminVersionsServiceImpl implements AdminVersionsService {

    private final VersionsService versionsService;

    private final MaterialService materialService;

    @Override
    public List<VersionMappingResp> listVersionMappings() {
        List<VersionsEntity> versions = versionsService.list(new LambdaQueryWrapper<>(VersionsEntity.class).orderByAsc(VersionsEntity::getId));
        return VersionConvert.INSTANCE.convertToVersionMappingRespList(versions);
    }

    @Override
    public List<VersionResp> listBySubjectId(Integer subjectId) {
        List<VersionsEntity> versions = versionsService.getListBySubjectId(subjectId);
        return VersionConvert.INSTANCE.convertToVersionRespList(versions);
    }

    @Override
    public List<VersionResp> listBySubjectIdAndGradeId(Integer subjectId, Integer gradeId) {
        List<VersionsEntity> versions = versionsService.getListBySubjectId(subjectId);
        if(CollectionUtils.isEmpty(versions)){
            return Collections.emptyList();
        }
        Set<Integer> versionIds = versions.stream().map(VersionsEntity::getId).collect(Collectors.toSet());

        List<MaterialEntity> materialEntities = materialService.list(new LambdaQueryWrapper<>(MaterialEntity.class)
                .eq(MaterialEntity::getGradeId, gradeId)
                .in(MaterialEntity::getVersionId, versionIds));
        if(CollectionUtils.isEmpty(materialEntities)){
            return Collections.emptyList();
        }
        Set<Integer> materialVersionIds = materialEntities.stream().map(MaterialEntity::getVersionId).collect(Collectors.toSet());
        return VersionConvert.INSTANCE.convertToVersionRespList(versions.stream().filter(versionsEntity -> materialVersionIds.contains(versionsEntity.getId())).collect(Collectors.toList()));
    }
}