package com.tmerclub.cloud.product.listener;

import com.tmerclub.cloud.api.multishop.feign.ShopSubstituteSalesFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.product.constant.IsSynUpdate;
import com.tmerclub.cloud.common.product.constant.SalesType;
import com.tmerclub.cloud.common.product.vo.SpuVO;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.vo.ShopSubstituteSalesVO;
import com.tmerclub.cloud.product.service.SpuService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author xxw
 * @date 2022/11/3 9:12
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.SUPPLIER_PRODUCT_UPDATE, consumerGroup = RocketMqConstant.SUPPLIER_PRODUCT_UPDATE)
public class SupplierSpuUpdateNotifyConsumer implements RocketMQListener<Long> {

    @Autowired
    private SpuService spuService;

    @DubboReference
    private ShopSubstituteSalesFeignClient shopSubstituteSalesFeignClient;

    /**
     * 供应商品基本信息更新后给供应商返发货的且是手动设价的代销商品添加提示
     *
     * @param supplierSpuId
     */
    @Override
    public void onMessage(Long supplierSpuId) {
        List<SpuVO> commissionSpuList = spuService.getCommissionSpuList(supplierSpuId);
        List<Long> shopIdList = commissionSpuList.stream().map(SpuVO::getShopId).collect(Collectors.toList());
        if (shopIdList.size() == 0) {
            return;
        }
        List<ShopSubstituteSalesVO> shopSubstituteSalesVOList = shopSubstituteSalesFeignClient.shopSubstituteSalesList(shopIdList).getData();
        //满足条件的商家id
        List<Long> shopIdS = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (ShopSubstituteSalesVO salesVO : shopSubstituteSalesVOList) {
            if (Objects.equals(salesVO.getSalesType(), SalesType.MANUAL_OPERATION_PRICE.value())) {
                shopIdS.add(salesVO.getShopId());
            }
        }
        //满足条件的代销商品id
        List<Long> spuIdList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (SpuVO spuVO : commissionSpuList) {
            if (shopIdS.contains(spuVO.getShopId())) {
                spuIdList.add(spuVO.getSpuId());
            }
        }
        spuService.batchChangeSynUpdate(spuIdList, IsSynUpdate.NO_CHANGE.value());
    }
}
