
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.order.bo.EsOrderInvoiceBO;
import com.tmerclub.cloud.api.order.feign.OrderInvoiceFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.OrderInvoiceBO;
import com.tmerclub.cloud.search.canal.model.CanalBinLogResult;
import com.tmerclub.cloud.search.constant.EsIndexEnum;
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.Objects;

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

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

    @DubboReference
    private OrderInvoiceFeignClient orderInvoiceFeignClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<OrderInvoiceBO> result) {
        Long orderInvoiceId = result.getPrimaryKey();
        EsOrderInvoiceBO esOrder = getEsOrderInvoiceData(orderInvoiceId);
        if (Objects.isNull(esOrder)) {
            log.error("订单发票信息异常的订单id为：{}", orderInvoiceId);
            return;
        }
        EsSearchUtil.esSave(esOrder.getOrderInvoiceId(), EsIndexEnum.ORDER_INVOICE, esOrder);
    }

    /**
     * 更新订单数据
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<OrderInvoiceBO> result) {
        OrderInvoiceBO afterData = result.getAfterData();
        EsOrderInvoiceBO esOrder = getEsOrderInvoiceData(afterData.getOrderInvoiceId());
        if (Objects.isNull(esOrder)) {
            log.error("订单发票信息异常的订单id为：{}", afterData.getOrderInvoiceId());
            return;
        }
        EsSearchUtil.esUpdate(esOrder.getOrderInvoiceId(), EsIndexEnum.ORDER_INVOICE, esOrder);
    }

    private EsOrderInvoiceBO getEsOrderInvoiceData(Long orderInvoiceId) {
        ServerResponseEntity<EsOrderInvoiceBO> orderResponseEntity = orderInvoiceFeignClient.getEsOrderInvoice(orderInvoiceId);
        if (!orderResponseEntity.isSuccess()) {
            throw new LuckException(orderResponseEntity.getMsg());
        }
        // 添加es中保存的订单数据
        return orderResponseEntity.getData();
    }
}
