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.Gsp;
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.StudyGspMapper;
import com.hxhq.business.domain.StudyGsp;
import com.hxhq.business.service.IStudyGspService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验使用供试品关联Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-10
 */
@Service
public class StudyGspServiceImpl extends ServiceImpl<StudyGspMapper, StudyGsp> implements IStudyGspService
{
    /**
     * 查询试验使用供试品关联列表
     *
     * @param studyGsp 试验使用供试品关联
     * @return 试验使用供试品关联
     */
    @Override
    public List<StudyGsp> queryList(StudyGsp studyGsp)
    {
        QueryWrapper<StudyGsp> queryWrapper = Wrappers.query();
        return this.list(queryWrapper);
    }

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

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

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

}
