
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.order.bo.EsPurchaseOrderBO;
import com.tmerclub.cloud.api.order.feign.PurchaseOrderFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.PurchaseOrderBO;
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 PurchaseOrderCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<PurchaseOrderBO> {

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

    @DubboReference
    private PurchaseOrderFeignClient purchaseOrderFeignClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<PurchaseOrderBO> result) {
        Long orderId = result.getPrimaryKey();
        EsPurchaseOrderBO purchaseOrderBO = getEsOrderData(orderId);
        if (Objects.isNull(purchaseOrderBO)) {
            log.error("采购订单信息异常的订单id为：{}", orderId);
            return;
        }
        EsSearchUtil.esSave(purchaseOrderBO.getPurchaseOrderId(), EsIndexEnum.PURCHASE_ORDER, purchaseOrderBO);
    }

    /**
     * 更新订单数据
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<PurchaseOrderBO> result) {
        PurchaseOrderBO afterData = result.getAfterData();
        EsPurchaseOrderBO purchaseOrderBO = getEsOrderData(afterData.getPurchaseOrderId());
        if (Objects.isNull(purchaseOrderBO)) {
            log.error("采购订单信息异常的订单id为：{}", afterData.getPurchaseOrderId());
            return;
        }
        EsSearchUtil.esUpdate(purchaseOrderBO.getPurchaseOrderId(), EsIndexEnum.PURCHASE_ORDER, purchaseOrderBO);
    }

    private EsPurchaseOrderBO getEsOrderData(Long orderId) {
        ServerResponseEntity<EsPurchaseOrderBO> orderResponseEntity = purchaseOrderFeignClient.saveMongoAndGetEsInfo(orderId);
        if (!orderResponseEntity.isSuccess()) {
            throw new LuckException(orderResponseEntity.getMsg());
        }
        // 添加es中保存的采购订单数据
        return orderResponseEntity.getData();
    }
}
