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.Cell;
import com.hxhq.business.domain.StudySj;
import com.hxhq.common.core.domain.MpBaseEntity;
import com.hxhq.common.core.utils.DateUtils;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudyCellMapper;
import com.hxhq.business.domain.StudyCell;
import com.hxhq.business.service.IStudyCellService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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

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

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

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

}
