
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.product.feign.BrandFeignClient;
import com.tmerclub.cloud.api.product.feign.ProductFeignClient;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.product.bo.EsBrandBO;
import com.tmerclub.cloud.common.product.bo.EsProductBO;
import com.tmerclub.cloud.common.product.vo.BrandLangVO;
import com.tmerclub.cloud.common.product.vo.BrandVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.BrandBO;
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.stereotype.Component;

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

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

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

    @DubboReference
    private ProductFeignClient productFeignClient;
    @DubboReference
    private BrandFeignClient brandFeignClient;

    /**
     * 更新品牌
     * @param result
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<BrandBO> result) {
        BrandBO afterData = result.getAfterData();
        ServerResponseEntity<BrandVO> brandResponse = brandFeignClient.getInfo(afterData.getBrandId());
        BrandVO brand = brandResponse.getData();
        EsProductBO esProductBO = new EsProductBO();
        esProductBO.setBrand(new EsBrandBO());
        for (BrandLangVO brandLangVO : brand.getBrandLangList()) {
            if (Objects.equals(brandLangVO.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                esProductBO.getBrand().setBrandNameZh(brandLangVO.getName());
                continue;
            }
            esProductBO.getBrand().setBrandNameEn(brandLangVO.getName());
        }
        esProductBO.getBrand().setBrandId(brand.getBrandId());
        esProductBO.getBrand().setBrandImg(afterData.getImgUrl());
        ServerResponseEntity<List<Long>> responseData = productFeignClient.getSpuIdsByBrandId(afterData.getBrandId());
        EsSearchUtil.esUpdateSpuBySpuIds(responseData.getData(), esProductBO);
    }
}
