package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.entity.ShopGoods;
import com.gxwebsoft.shop.mapper.ShopGiftMapper;
import com.gxwebsoft.shop.service.ShopGiftService;
import com.gxwebsoft.shop.entity.ShopGift;
import com.gxwebsoft.shop.param.ShopGiftParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.ShopGoodsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 礼品卡Service实现
 *
 * @author 科技小王子
 * @since 2025-08-11 18:07:31
 */
@Service
public class ShopGiftServiceImpl extends ServiceImpl<ShopGiftMapper, ShopGift> implements ShopGiftService {
    @Resource
    private ShopGoodsService shopGoodsService;

    @Override
    public PageResult<ShopGift> pageRel(ShopGiftParam param) {
        PageParam<ShopGift, ShopGiftParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ShopGift> list = baseMapper.selectPageRel(page, param);
        if (!list.isEmpty()) {
            Set<Integer> goodsIds = list.stream().map(ShopGift::getGoodsId).collect(Collectors.toSet());
            List<ShopGoods> goodsList = shopGoodsService.listByIds(goodsIds);
            for (ShopGift shopGift : list) {
              ShopGoods shopGoods = goodsList.stream().filter(sG -> sG.getGoodsId().equals(shopGift.getGoodsId())).findFirst().orElse(null);
              if (shopGoods != null) {
                shopGift.setGoods(shopGoods);
              }
            }
        }
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ShopGift> listRel(ShopGiftParam param) {
        List<ShopGift> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ShopGift, ShopGiftParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ShopGift getByIdRel(Integer id) {
        ShopGiftParam param = new ShopGiftParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public ShopGift getByCode(String code) {
        ShopGiftParam param = new ShopGiftParam();
        param.setCode(code);
        return param.getOne(baseMapper.selectListRel(param));
    }

}
