
package com.tmerclub.cloud.search.listener;

import com.tmerclub.cloud.api.order.bo.EsOrderInvoiceBO;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.api.order.feign.OrderInvoiceFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.mongodb.bo.order.MongoOrderBO;
import com.tmerclub.cloud.common.order.bo.EsOrderBO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.search.bo.OrderBO;
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.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

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

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

    @Autowired
    private MongoTemplate mongoTemplate;;
    @DubboReference
    private OrderFeignClient orderFeignClient;
    @DubboReference
    private OrderInvoiceFeignClient orderInvoiceFeignClient;

    /**
     * 插入订单，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<OrderBO> result) {
        Long orderId = result.getPrimaryKey();
        EsOrderBO esOrder = getEsOrderData(orderId);
        if (Objects.isNull(esOrder)) {
            log.error("订单信息异常的订单id为：{}", orderId);
            return;
        }
        EsSearchUtil.esSave(esOrder.getOrderId(), EsIndexEnum.ORDER, esOrder);
    }

    /**
     * 更新订单数据（同时更新订单对应发票的es数据）
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<OrderBO> result) {
        OrderBO afterData = result.getAfterData();
        EsOrderBO esOrder = getEsOrderData(afterData.getOrderId());
        if (Objects.isNull(esOrder)) {
            log.error("订单信息异常的订单id为：{}", afterData.getOrderId());
            return;
        }
        EsSearchUtil.esUpdate(esOrder.getOrderId(), EsIndexEnum.ORDER, esOrder);
        // 更新发票的es数据
        List<EsOrderInvoiceBO> esOrderInvoiceBOList = this.getEsOrderInvoiceData(afterData.getOrderId());
        for (EsOrderInvoiceBO esOrderInvoiceBO : esOrderInvoiceBOList) {
            if (esOrder.getWaitPurchase() == 1) {
                esOrderInvoiceBO.setOrderStatus(OrderStatus.WAIT_PURCHASE.value());
            }
            EsSearchUtil.esUpdate(esOrderInvoiceBO.getOrderInvoiceId(), EsIndexEnum.ORDER_INVOICE, esOrderInvoiceBO);
        }
    }

    private EsOrderBO getEsOrderData(Long orderId) {
        EsOrderBO esOrderBO = orderFeignClient.getEsOrderInfo(orderId);
        if (Objects.isNull(esOrderBO)) {
            return null;
        }
        // 保存订单数据到mongodb
        MongoOrderBO mongoOrderBO = BeanUtil.map(esOrderBO, MongoOrderBO.class);
        mongoTemplate.save(mongoOrderBO);
        // 添加es中保存的订单数据
        return esOrderBO;
    }

    /**
     * 获取订单发票的es数据
     *
     * @param orderId
     * @return
     */
    private List<EsOrderInvoiceBO> getEsOrderInvoiceData(Long orderId) {
        ServerResponseEntity<List<EsOrderInvoiceBO>> response = orderInvoiceFeignClient.listEsOrderInvoiceByOrderId(orderId);
        if (!response.isSuccess()) {
            throw new LuckException(response.getMsg());
        }
        return response.getData();
    }
}
