
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.product.feign.ProductFeignClient;
import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.util.CacheManagerUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.bo.EsProductBO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.SpuTagBO;
import com.tmerclub.cloud.search.canal.model.CanalBinLogResult;
import com.tmerclub.cloud.search.util.EsSearchUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;


/**
 * @author YXF
 * @date 2021/01/21
 */
@Component
public class SpuTagCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<SpuTagBO> {

    private static final Logger log = LoggerFactory.getLogger(SpuTagCanalListener.class);

    @DubboReference
    private ProductFeignClient productFeignClient;
    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @Override
    protected void processInsertInternal(CanalBinLogResult<SpuTagBO> result) {
        updateSpuTagData(result);
    }

    @Override
    protected void processUpdateInternal(CanalBinLogResult<SpuTagBO> result) {
        SpuTagBO beforeData = result.getBeforeData();
        if (Objects.isNull(beforeData.getSeq())) {
            return;
        }
        updateSpuTagData(result);
    }

    @Override
    protected void processDeleteInternal(CanalBinLogResult<SpuTagBO> result) {
        updateSpuTagData(result);
    }

    private void updateSpuTagData(CanalBinLogResult<SpuTagBO> result) {
        SpuTagBO afterData = result.getAfterData();
        cacheManagerUtil.evictCache(CacheNames.SPU_TAG_BY_SHOP, afterData.getShopId().toString());

        ServerResponseEntity<List<Long>> spuTagResponse = productFeignClient.getSpuTagBySpuId(afterData.getSpuId());
        if (!spuTagResponse.isSuccess()) {
            throw new LuckException(spuTagResponse.getMsg());
        }
        EsProductBO esProductBO = new EsProductBO();
        esProductBO.setTagIds(spuTagResponse.getData());
        List<Long> spuIds = Collections.singletonList(afterData.getSpuId());
        EsSearchUtil.esUpdateSpuBySpuIds(spuIds, esProductBO);
    }
}
