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

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.constants.UpgradeSellerLists;
import com.zm.order.tool.server.dao.OrderDao;
import com.zm.order.tool.server.dao.OrderItemCommentDao;
import com.zm.order.tool.server.manager.NewHintManager;
import com.zm.order.tool.server.manager.SearchCommentManager;
import com.zm.order.tool.server.model.KafkaConsumerMessage;
import com.zm.order.tool.server.model.Order;
import com.zm.order.tool.server.model.OrderItemComment;
import com.zm.order.tool.server.newdatasource.NewDataSourceOrderItemCommentDao;
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.beans.factory.annotation.Value;
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;

/**
 * binlog监听
 *
 * @author nianchang
 * @date 2021/12/21 2:34 下午
 */
@Component
@SuppressWarnings("all")
public class ConvertItemCommentSyncListener {

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

    @Autowired
    private NewHintManager hintManager;

    @Autowired
    private NewDataSourceOrderItemCommentDao newItemCommentDao;

    @Autowired
    private OrderItemCommentDao itemCommentDao;
    
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private SearchCommentManager searchCommentManager;

    @Value("${new.sharding.db.size}")
    private int dbSize;

    @Value("${new.sharding.tb.size}")
    private int tbSize;

//    @KafkaListener(topics = "${kafka.bin.log.sync.new.item.comment.topic}")
    public void consumer(List<ConsumerRecord<String, String>> recordList, Acknowledgment ack) {
        try {
            logger.info("[bin_log_sync_item_comment_consumer]before！");
            if (CollectionUtils.isEmpty(recordList)) {
                return;
            }
            for (ConsumerRecord<String, String> record : recordList) {
                OrderItemComment model = parse(record);
                if (model != null) {
                    logger.info("[bin_log_sync_item_comment_consumer_as]model:{}", model);
                    if (Objects.equals(0, model.getMasterDataSource())) {
                        return;
                    }
                    if (!UpgradeSellerLists.LIST.contains(model.getSellerId())) {
                        logger.info("Filter un upgrade seller item comment. orderNo:{}", model.getOrderNo());
                        return;
                    }
                    logger.info("[bin_log_sync_item_comment_consumer_qwef]model:{}", model.getOrderNo());
                    final Long id = model.getId();
                    final Long sellerId = model.getSellerId();
                    OrderItemComment comment = itemCommentDao.selectById(sellerId, id);
                    OrderItemComment replace = comment == null ? model : newItemCommentDao.selectById(sellerId, id);

                    if (replace != null) {
                        Order order = orderDao.selectByOrderNo(replace.getOrderNo(), replace.getUserId());
                        if (order != null) {
                            replace.setBizType(order.getBizType());
                            replace.setOrderType(order.getOrderType());
                            replace.setOrderSubType(order.getOrderSubType());
                            replace.setPerformanceType(order.getPerformanceType());
                        }
                        itemCommentDao.replaceList(Lists.newArrayList(replace));
                        searchCommentManager.indexDocument(replace, CommonConstants.ES_ORDER_COMMENT_INDEX);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ConvertItemCommentSyncListener[item_comment_fail_consumer]failed！msg:{}, cause by:{}", recordList, e);
        } finally {
            ack.acknowledge();
        }
    }

    private OrderItemComment 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(), OrderItemComment.class);
    }
}
