/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.springblade.modules.mall.entity.SeckillGoods;
import org.springblade.modules.mall.vo.SeckillGoodsVO;
import org.springblade.modules.mall.mapper.SeckillGoodsMapper;
import org.springblade.modules.mall.service.ISeckillGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 秒杀商品表 服务实现类
 *
 * @author BladeX
 * @since 2023-05-04
 */
@Service
public class SeckillGoodsServiceImpl extends ServiceImpl<SeckillGoodsMapper, SeckillGoods> implements ISeckillGoodsService {

	@Override
	public IPage<SeckillGoodsVO> selectSeckillGoodsPage(IPage<SeckillGoodsVO> page, SeckillGoodsVO seckillGoods) {
		return page.setRecords(baseMapper.selectGoods(page, seckillGoods.getSeckillRoundId()));
	}

	@Override
	public List<SeckillGoodsVO> getGoods(IPage<SeckillGoodsVO> page, Long seckkillRoundId) {
		return baseMapper.selectGoods(page, seckkillRoundId);
	}

	@Override
	public void addSeckillGoods(List<SeckillGoods> seckillGoods) {
		List<Long> collect = seckillGoods.stream().map(SeckillGoods::getSeckillRoundId).collect(Collectors.toList());
		if (CollUtil.isNotEmpty(collect)) {
			List<SeckillGoods> list = this.lambdaQuery().in(SeckillGoods::getSeckillRoundId, collect).list();
			Map<Long, Long> map = list.stream().collect(Collectors.toMap(SeckillGoods::getGoodsId, SeckillGoods::getGoodsId));
			Iterator<SeckillGoods> iterator = seckillGoods.iterator();
			// 将已添加过的商品移除
			if (iterator.hasNext()) {
				SeckillGoods next = iterator.next();
				if (map.get(next.getGoodsId()) != null) {
					iterator.remove();
				}
			}
			this.saveBatch(seckillGoods);
		}
	}

}
