package com.hxhq.business.service.impl;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hxhq.business.domain.Bacteria;
import com.hxhq.business.domain.StudyCell;
import com.hxhq.common.core.domain.MpBaseEntity;
import com.hxhq.common.core.utils.DateUtils;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudyBacteriaMapper;
import com.hxhq.business.domain.StudyBacteria;
import com.hxhq.business.service.IStudyBacteriaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验-细菌关联Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-12
 */
@Service
public class StudyBacteriaServiceImpl extends ServiceImpl<StudyBacteriaMapper, StudyBacteria> implements IStudyBacteriaService
{
    /**
     * 查询试验-细菌关联列表
     *
     * @param studyBacteria 试验-细菌关联
     * @return 试验-细菌关联
     */
    @Override
    public List<StudyBacteria> queryList(StudyBacteria studyBacteria)
    {
        QueryWrapper<StudyBacteria> queryWrapper = Wrappers.query();
        return this.list(queryWrapper);
    }

    @Override
    public void saveBatch(Long studyId, List<Bacteria> bacteriaList) {
        List<Long> resourceIdList = bacteriaList.stream().map(MpBaseEntity::getId).distinct().collect(Collectors.toList());

        // 查询数据库中已有记录
        LambdaQueryWrapper<StudyBacteria> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudyBacteria::getStudyId, studyId)
                .in(StudyBacteria::getResourceId, resourceIdList);
        List<StudyBacteria> list = this.list(queryWrapper);
        List<Long> dbResourceIdList = list.stream().map(StudyBacteria::getResourceId).collect(Collectors.toList());

        // 对比试剂id，插入数据库中没有的记录
        List<Long> insertResourceId = resourceIdList.stream()
                .filter(element -> !dbResourceIdList.contains(element))
                .collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(insertResourceId)) {
            List<StudyBacteria> studyCellList = new ArrayList<>();
            for (Long resourceId : insertResourceId) {
                StudyBacteria studyBacteria = new StudyBacteria();
                studyBacteria.setResourceId(resourceId);
                studyBacteria.setStudyId(studyId);
                studyCellList.add(studyBacteria);
            }
            this.saveBatch(studyCellList);
        }
    }

}
