
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.order.bo.EsOrderRefundBO;
import com.tmerclub.cloud.api.order.feign.OrderRefundFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.search.bo.OrderRefundBO;
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 YXF
 * @date 2022/8/23
 */
@Component
public class OrderRefundCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<OrderRefundBO> {

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

    @DubboReference
    private OrderRefundFeignClient orderRefundFeignClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<OrderRefundBO> result) {
        Long refundId = result.getPrimaryKey();
        EsOrderRefundBO orderRefund = getEsOrderRefundData(refundId);
        if (Objects.isNull(orderRefund)) {
            log.error("订单信息异常的订单id为：{}", refundId);
            return;
        }
        EsSearchUtil.esSave(orderRefund.getRefundId(), EsIndexEnum.ORDER_REFUND, orderRefund);
    }

    /**
     * 更新订单数据
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<OrderRefundBO> result) {
        OrderRefundBO afterData = result.getAfterData();
        EsOrderRefundBO orderRefund = getEsOrderRefundData(afterData.getRefundId());
        if (Objects.isNull(orderRefund)) {
            log.error("订单信息异常的订单id为：{}", afterData.getRefundId());
            return;
        }
        EsSearchUtil.esUpdate(orderRefund.getRefundId(), EsIndexEnum.ORDER_REFUND, orderRefund);
    }

    private EsOrderRefundBO getEsOrderRefundData(Long refundId) {
        ServerResponseEntity<EsOrderRefundBO> orderResponseEntity = orderRefundFeignClient.saveMongoAndGetEsOrderRefundInfo(refundId);
        if (!orderResponseEntity.isSuccess()) {
            throw new LuckException(orderResponseEntity.getMsg());
        }
        // 添加es中保存的订单数据
        return orderResponseEntity.getData();
    }
}
