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

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.OrderDao;
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.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 ConvertRefundDetailSyncListener {

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

    @Autowired
    private OrderRefundDetailsDao refundDetailsDao;

    @Autowired
    private NewDataSourceOrderRefundDetailsDao newRefundDetailDao;

    @Autowired
    private RefundStreamConverter converter;

    @Autowired
    private OrderDao orderDao;

//    @KafkaListener(topics = "${kafka.bin.log.sync.new.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_refundDetail_consumer_xcq]model:{}", model);
                    if (Objects.equals(0, model.getMasterDataSource())) {
                        return;
                    }
                    if (!UpgradeSellerLists.LIST.contains(model.getSellerId())) {
                        logger.info("Filter un upgrade seller refund detail. orderNo:{}", model.getOrderNo());
                        return;
                    }
                    logger.info("[bin_log_sync_refundDetail_consumer_ccs]model:{}", model.getRefundNo());
                    final Long id = model.getId();
                    OrderRefundDetails refund = refundDetailsDao.selectById(id);
                    OrderRefundDetails replace = refund == null ? model : newRefundDetailDao.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.reversePayTypeMap(order.getBizType(), replace.getPayType()));
                        }
                        refundDetailsDao.replace(replace);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConvertRefundDetailSyncListener[refund_detail_fail_consumer]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);
    }
}
