package com.zm.order.tool.server.listener.reverse;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.google.common.base.Throwables;
import com.zm.order.tool.server.constants.UpgradeSellerLists;
import com.zm.order.tool.server.dao.OrderRefundDetailsDao;
import com.zm.order.tool.server.model.KafkaConsumerMessage;
import com.zm.order.tool.server.model.Order;
import com.zm.order.tool.server.model.OrderRefundDetails;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderDao;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderRefundDetailsDao;
import com.zm.order.tool.server.stream.convert.RefundStreamConverter;
import com.zm.order.tool.server.stream.factory.MapperFactory;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * <p>
 *
 * </p>
 *
 * @author nianchang
 * @date 2023/03/21 1:57 下午
 */
@Component
@SuppressWarnings("all")
public class ResConvertRefundDetailSyncListener {

    private static final Logger logger = LoggerFactory.getLogger(ResConvertRefundDetailSyncListener.class);

    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;

    @Autowired
    private NewDataSourceOrderRefundDetailsDao newRefundDetailDao;

    @Autowired
    private RefundStreamConverter converter;

    @Autowired
    private NewDataSourceOrderDao orderDao;

//    @KafkaListener(topics = "${kafka.bin.log.sync.refund.details.topic}")
    public void consumer(List<ConsumerRecord<String, String>> recordList, Acknowledgment ack) {
        try {
            logger.info("[bin_log_sync_refund_details_consumer]before！");
            if (CollectionUtils.isEmpty(recordList)) {
                return;
            }
            for (ConsumerRecord<String, String> record : recordList) {
                OrderRefundDetails model = parse(record);
                if (model != null) {
                    logger.info("[bin_log_sync_res_refund_detail_consumer_0]model:{}", model);
                    if (Objects.equals(1, model.getMasterDataSource())) {
                        return;
                    }
                    if (!UpgradeSellerLists.LIST.contains(model.getSellerId())) {
                        logger.info("Filter res un upgrade seller refund detail. orderNo:{}", model.getOrderNo());
                        return;
                    }
                    logger.info("[bin_log_sync_res_refund_detail_consumer_12312]refundNo:{}", model.getRefundNo());
                    final Long id = model.getId();
                    OrderRefundDetails refund = newRefundDetailDao.selectById(id);
                    OrderRefundDetails replace = refund == null ? model : refundDetailsDao.selectById(id);

                    if (replace != null) {
                        Order order = orderDao.selectByOrderNo(replace.getOrderNo(), replace.getUserId());
                        if (order != null) {
                            replace.setBizType(order.getBizType());
                            replace.setPerformanceType(order.getPerformanceType());
                            replace.setPayType(MapperFactory.payTypeMap(order.getBizType(), replace.getPayType()));
                        }
                        newRefundDetailDao.replace(replace);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConvertRefundDetailSyncListener[res_refund_detail_consumer_fail]failed！msg:{}, cause by:{}",
                    recordList, Throwables.getStackTraceAsString(e));
        } finally {
            ack.acknowledge();
        }
    }

    private OrderRefundDetails parse(ConsumerRecord<String, String> record) {
        String dataSource = record.value();
        if (StringUtils.isEmpty(dataSource)) {
            return null;
        }
        KafkaConsumerMessage message = JSON.parseObject(dataSource, KafkaConsumerMessage.class);
        return JSON.parseObject(message.getData(), OrderRefundDetails.class);
    }
}
