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.Gyzj;
import com.hxhq.business.domain.Sj;
import com.hxhq.business.domain.StudySj;
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.StudyGyzjMapper;
import com.hxhq.business.domain.StudyGyzj;
import com.hxhq.business.service.IStudyGyzjService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 试验-物资信息-给药制剂Service业务层处理
 *
 * @author hxhq
 * @date 2026-01-09
 */
@Service
public class StudyGyzjServiceImpl extends ServiceImpl<StudyGyzjMapper, StudyGyzj> implements IStudyGyzjService {

    /**
     * 批量新增
     *
     * @param list
     */
    @Override
    public void insertBatch(List<StudyGyzj> list) {
        baseMapper.insertBatch(list);
    }


    /**
     * 关联试验
     * @param studyId
     * @param sjList
     */
    @Override
    @Async
    public void saveBatch(Long studyId, List<Gyzj> sjList) {
        List<Long> resourceIdList = sjList.stream().map(MpBaseEntity::getId).collect(Collectors.toList());

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

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

}
