package com.gic.haoban.manage.service.service.content.adaptor;

import com.gic.api.base.commons.ServiceResponse;
import com.gic.store.goods.dto.goods.GoodsInfoSimpleDTO;
import com.gic.store.goods.dto.goods.GoodsSpuInfoDTO;
import com.gic.store.goods.service.GoodsCenterApiService;
import com.gic.store.goods.service.GoodsInfoOutApiService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author MUSI
 * @Date 2023/8/15 9:28 AM
 * @Description
 * @Version
 **/
@Component
public class GoodsInfoAdaptor {

    @Autowired
    private GoodsCenterApiService goodsCenterApiService;
    @Autowired
    private GoodsInfoOutApiService goodsInfoOutApiService;

    public Map<String, GoodsSpuInfoDTO> queryGoodsMinPrice(String enterpriseId, List<String> goodsIds) {
        ServiceResponse<List<GoodsSpuInfoDTO>> response = goodsCenterApiService.queryGoodsMinPrice(enterpriseId, goodsIds);
        if (!response.isSuccess() || CollectionUtils.isEmpty(response.getResult())) {
            return Collections.emptyMap();
        }
        return response.getResult()
                .stream()
                .collect(Collectors.toMap(GoodsSpuInfoDTO::getGoodsId, Function.identity(), (v1, v2) -> v1));
    }

    public Map<String, GoodsInfoSimpleDTO> queryGoodsAndMinPrice(String enterpriseId, List<String> goodsIds) {
        ServiceResponse<List<GoodsInfoSimpleDTO>> response = goodsInfoOutApiService.queryGoodsSimpleInfo(goodsIds);
        if (!response.isSuccess() || CollectionUtils.isEmpty(response.getResult())) {
            return Collections.emptyMap();
        }
        Map<String, GoodsSpuInfoDTO> goodsMinPriceMap = queryGoodsMinPrice(enterpriseId, goodsIds);
        return response.getResult()
                .stream()
                .peek(item->{
                    GoodsSpuInfoDTO goodsSpuInfoDTO = goodsMinPriceMap.get(item.getGoodsId());
                    if (goodsSpuInfoDTO != null && goodsSpuInfoDTO.getMinPrice() != null) {
                        item.setSalePrice(goodsSpuInfoDTO.getMinPrice());
                    }
                }).collect(Collectors.toMap(GoodsInfoSimpleDTO::getGoodsId, Function.identity(), (v1, v2) -> v1));
    }

}
