package cn.freemud.service.product;

import cn.freemud.entities.dto.GetMenuResponseDto;
import cn.freemud.entities.dto.GetProductInfoDto;
import cn.freemud.entities.dto.ProductInfosDto;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.thirdparty.ProductClient;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.sdk.api.assortment.shoppingcart.constant.CommonsConstant;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Clover.z
 * @Date 2021/10/29
 * @Desc 商品服务通用能力下沉
 */
@Component
@RequiredArgsConstructor
public class ProductManager {

    private final ProductClient productClient;


    List<GetMenuResponseDto.DataBean.RootNodeBean.ChildrenBeanFirst.ChildrenBeanSecond.ProductBean> getProductsInfo(String partnerId, String storeCode, String menuType, List<String> goodsIdList) {
        if (CollectionUtils.isEmpty(goodsIdList)) {
            return new ArrayList<>();
        }

        //移除空的goodsId及spq的商品券
        goodsIdList = goodsIdList.parallelStream().filter(StringUtils::isNotEmpty).filter(goodsId -> !goodsId.startsWith(CommonsConstant.COUPON_PREFIX)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(goodsIdList)) {
            return new ArrayList<>();
        }

        GetProductInfoDto query = new GetProductInfoDto();
        query.setPartnerId(partnerId);
        query.setShopId(storeCode);
        query.setProductInfoType(2);
        query.setProductIds(goodsIdList);
        query.setChannel(menuType);
        ProductInfosDto resposne = productClient.listProductInfos(query);
        if (!Objects.equals(ResponseResultEnum.SUCCESS.getCode(), resposne.getCode()) || null == resposne.getData()) {
            throw new ServiceException(ResponseResult.STORE_ITEM_QUERY_ERROR);
        }
        return CollectionUtils.isEmpty(resposne.getData().getProducts()) ? new ArrayList<>() : resposne.getData().getProducts();
    }

}
