
package com.tmerclub.cloud.search.listener;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.product.constant.CategoryLevel;
import com.tmerclub.cloud.api.product.feign.CategoryFeignClient;
import com.tmerclub.cloud.api.product.feign.ProductFeignClient;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.product.bo.EsCategoryBO;
import com.tmerclub.cloud.common.product.bo.EsProductBO;
import com.tmerclub.cloud.common.product.vo.CategoryLangVO;
import com.tmerclub.cloud.common.product.vo.CategoryVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.CategoryBO;
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.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author tmerclub
 * @date 2020/11/13
 */
@Component
public class CategoryCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<CategoryBO> {

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

    @DubboReference
    private CategoryFeignClient categoryFeignClient;
    @DubboReference
    private ProductFeignClient productFeignClient;

    /**
     * 更新分类，删除商品索引，再重新构建一个
     *
     * @param result
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<CategoryBO> result) {
        CategoryBO afterData = result.getAfterData();
        boolean updateCategoryName = Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.THIRD.value());
        boolean updateShopCategoryName = !Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.SECOND.value());
        boolean isUpdate = updateCategoryName || updateShopCategoryName;
        // 非平台三级分类或商家二级分类，则不需要更改分类名
        if (!isUpdate) {
            return;
        }

        EsProductBO esProductBO = new EsProductBO();
        ServerResponseEntity<CategoryVO> categoryResponse = categoryFeignClient.getByCategoryId(afterData.getCategoryId());
        if (!categoryResponse.isSuccess()) {
            logger.error("分类id为：{}的分类数据异常", afterData.getCategoryId());
            return;
        }
        CategoryVO categoryVO = categoryResponse.getData();
        if (CollUtil.isEmpty(categoryVO.getCategoryLangList())) {
            logger.error("分类id为：{}的分类国际化数据异常", afterData.getCategoryId());
            return;
        }
        Map<Integer, String> categoryMap = categoryVO.getCategoryLangList().stream().collect(Collectors.toMap(CategoryLangVO::getLang, CategoryLangVO::getName));
        // 平台分类
        if (Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.THIRD.value())) {
            esProductBO.setCategory(new EsCategoryBO());
            esProductBO.getCategory().setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
            esProductBO.getCategory().setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        }
        // 商家分类
        else if (!Objects.equals(Constant.PLATFORM_SHOP_ID, afterData.getShopId()) && afterData.getLevel().equals(CategoryLevel.SECOND.value())) {
            esProductBO.setShopCategory(new EsCategoryBO());
            esProductBO.getShopCategory().setCategoryNameZh(categoryMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang()));
            esProductBO.getShopCategory().setCategoryNameEn(categoryMap.get(LanguageEnum.LANGUAGE_EN.getLang()));
        }
        List<Long> spuIds = getSpuIdsByCategoryId(afterData);
        EsSearchUtil.esUpdateSpuBySpuIds(spuIds, esProductBO);
    }

    /**
     * 根据分类信息，获取分类下的商品Id列表
     *
     * @param category
     * @return
     */
    private List<Long> getSpuIdsByCategoryId(CategoryBO category) {
        ServerResponseEntity<List<Long>> spuIdResponse;
        // 平台分类
        if (Objects.equals(category.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            spuIdResponse = productFeignClient.getSpuIdsByCategoryIds(Collections.singletonList(category.getCategoryId()));
        } else {
            spuIdResponse = productFeignClient.getSpuIdsByShopCategoryIds(Collections.singletonList(category.getCategoryId()));
        }
        return spuIdResponse.getData();
    }
}
