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.Sj;
import com.hxhq.common.core.domain.MpBaseEntity;
import com.hxhq.common.core.utils.DateUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.hxhq.business.mapper.StudySjMapper;
import com.hxhq.business.domain.StudySj;
import com.hxhq.business.service.IStudySjService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验生成、使用试剂关联Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-10
 */
@Service
public class StudySjServiceImpl extends ServiceImpl<StudySjMapper, StudySj> implements IStudySjService
{
    /**
     * 查询试验生成、使用试剂关联列表
     *
     * @param studySj 试验生成、使用试剂关联
     * @return 试验生成、使用试剂关联
     */
    @Override
    public List<StudySj> queryList(StudySj studySj)
    {
        QueryWrapper<StudySj> queryWrapper = Wrappers.query();
        return this.list(queryWrapper);
    }

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

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

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

}
