package org.dromara.common.batch.writer;

import lombok.RequiredArgsConstructor;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
public class GameAthleteWriter implements ItemWriter<GameAthlete> {

    private final GameAthleteMapper gameAthleteMapper;

    @Override
    public void write(List<? extends GameAthlete> items) throws Exception {
        // 1. 提取所有非空的athleteCode
        Set<String> codes = items.stream()
            .map(GameAthlete::getAthleteCode)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        if (!codes.isEmpty()) {
            // 2. 查询已存在的记录
            Map<String, Long> codeToIdMap = gameAthleteMapper.selectList(
                Wrappers.lambdaQuery(GameAthlete.class)
                    .in(GameAthlete::getAthleteCode, codes)
                    .select(GameAthlete::getAthleteId, GameAthlete::getAthleteCode)
            ).stream().collect(Collectors.toMap(
                GameAthlete::getAthleteCode,
                GameAthlete::getAthleteId
            ));

            // 3. 设置已存在记录的ID
            items.forEach(item -> {
                if (item.getAthleteCode() != null) {
                    Long id = codeToIdMap.get(item.getAthleteCode());
                    if (id != null) {
                        item.setAthleteId(id);
                    }
                }
            });
        }

        // 4. 批量保存或更新
        gameAthleteMapper.insertOrUpdateBatch(items);
    }
}
