package cn.newfeifan.mall.module.product.api.sku;

import cn.newfeifan.mall.framework.common.util.object.BeanUtils;
import cn.newfeifan.mall.module.product.api.sku.dto.ProductSkuRespDTO;
import cn.newfeifan.mall.module.product.api.sku.dto.ProductSkuUpdateStockReqDTO;
import cn.newfeifan.mall.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.newfeifan.mall.module.product.service.sku.ProductSkuService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品 SKU API 实现类
 *
 * @author LeeYan9
 * @since 2022-09-06
 */
@Service
@Validated
public class ProductSkuApiImpl implements ProductSkuApi {

    @Resource
    private ProductSkuService productSkuService;

    @Override
    public ProductSkuRespDTO getSku(Long id) {
        ProductSkuDO sku = productSkuService.getSku(id);
        return BeanUtils.toBean(sku, ProductSkuRespDTO.class);
    }

    @Override
    public List<ProductSkuRespDTO> getSkuList(Collection<Long> ids) {
        List<ProductSkuDO> skus = productSkuService.getSkuList(ids);

        Map<Long,Long> skuidShopidMap = new HashMap<Long,Long>();
        for(ProductSkuDO productSkuDO:skus){
            skuidShopidMap.put(productSkuDO.getId(),productSkuDO.getShopId());
        }
        //把店铺id设置进skuList对象中，为购物车按店铺拆分显示，做准备
        List<ProductSkuRespDTO> skuList = BeanUtils.toBean(skus, ProductSkuRespDTO.class);
        for(ProductSkuRespDTO productSkuRespDTO:skuList){
            productSkuRespDTO.setShopId(skuidShopidMap.get(productSkuRespDTO.getId()));
        }

        return skuList;
    }

    @Override
    public List<ProductSkuRespDTO> getSkuListBySpuId(Collection<Long> spuIds) {
        List<ProductSkuDO> skus = productSkuService.getSkuListBySpuId(spuIds);
        return BeanUtils.toBean(skus, ProductSkuRespDTO.class);
    }

    @Override
    public void updateSkuStock(ProductSkuUpdateStockReqDTO updateStockReqDTO) {
        productSkuService.updateSkuStock(updateStockReqDTO);
    }

}
