package com.liquidnet.service.consumer.base.receiver;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.service.base.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class ConsumerGoblinBizNftMongoReceiver extends AbstractBizRedisReceiver {
    @Value("${liquidnet.service.goblin.url}")
    private String serviceGoblinUrl;

    @Override
    protected boolean consumerMessageHandler(String msg) {
        boolean aBoolean = true;
        try {
            if (StringUtils.isEmpty(msg)) {
                log.warn("CONSUMER MSG NULL_DTO ==> [{}]:{}", this.getRedisStreamKey(), msg);
                aBoolean = true;
            } else {
                aBoolean = this.bizArtworkMdbProcessing(msg);
            }
        } catch (Exception e) {
            log.error("CONSUMER MSG EX_HANDLE ==> [{}]:{}", this.getRedisStreamKey(), msg, e);
            aBoolean = false;
        } finally {
            if (!aBoolean) {
                HashMap<String, String> map = CollectionUtil.mapStringString();
                map.put(MQConst.QUEUE_MESSAGE_KEY, msg);
                stringRedisTemplate.opsForStream().add(StreamRecords.mapBacked(map).withStreamKey(this.getRedisStreamKey()));
            }
        }
        return aBoolean;
    }

    @Override
    protected String getRedisStreamKey() {
        return MQConst.GoblinQueue.BIZ_NFT_MONGO.getKey();
    }

    @Override
    protected String getRedisStreamGroup() {
        return MQConst.GoblinQueue.BIZ_NFT_MONGO.getGroup();
    }

    private boolean bizArtworkMdbProcessing(String msg) {
        String postUrl = serviceGoblinUrl.concat("/goblin/que/mdb/adapt");
        try {
            String postRespStr = HttpUtil.postRaw(postUrl, msg, null);
            // 失败重新入队逻辑改至`被调用API`实现
//            JsonNode postRespJNode = JsonUtils.fromJson(postRespStr, JsonNode.class), postRespCode;
//            if (null == postRespJNode || null == (postRespCode = postRespJNode.get("code")) || !postRespCode.asText().equals("0")) {
//                log.warn("#MDB数据处理:处理失败[paramsStr={},postRespStr={}]", msg, postRespStr);
//                return false;
//            }
            return true;
        } catch (Exception e) {
            log.error("Ex.MDB数据处理:处理异常[url={},paramsStr={}],ex:{}", postUrl, msg, e.getMessage());
            return false;
        }
    }
}
