
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.common.cache.constant.CacheNames;
import com.tmerclub.cloud.common.cache.util.RedisUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.product.bo.EsProductBO;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.search.bo.SpuExtensionBO;
import com.tmerclub.cloud.search.canal.model.CanalBinLogResult;
import com.tmerclub.cloud.search.constant.EsIndexEnum;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

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

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<SpuExtensionBO> result) {
    }

    /**
     * 更新商品，删除商品索引，再重新构建一个
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<SpuExtensionBO> result) {

        // 更新之后的数据
        SpuExtensionBO afterData = result.getAfterData();

        // 清除商品扩展信息缓存
        List<String> keys = new ArrayList<>(3);
        keys.add(CacheNames.SPU_EXTENSION_KEY + CacheNames.UNION + afterData.getSpuId());
        RedisUtil.deleteBatch(keys);

        UpdateRequest request = new UpdateRequest(EsIndexEnum.PRODUCT.value(), String.valueOf(afterData.getSpuId()));
        EsProductBO esProductBO = new EsProductBO();
        esProductBO.setSpuId(afterData.getSpuId());
        // 更新注水销量和评论数量
        esProductBO.setWaterSoldNum(afterData.getWaterSoldNum());
        esProductBO.setCommentNum(afterData.getCommentNum());
        request.doc(Json.toJsonString(esProductBO), XContentType.JSON);
        try {
            UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
            log.info(updateResponse.toString());
        } catch (IOException e) {
            log.error(e.toString());
            throw new LuckException("更新es信息异常", e);
        }
    }
}
