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

import com.fasterxml.jackson.databind.JsonNode;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
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 org.springframework.util.LinkedMultiValueMap;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;

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

    @Override
    protected boolean consumerMessageHandler(String msg) {
        boolean aBoolean = false;
        try {
            if (StringUtils.isEmpty(msg)) {
                log.warn("CONSUMER MSG NULL_MSG ==> [{}]:{}", this.getRedisStreamKey(), msg);
                aBoolean = true;
            } else {
                String[] msgArr = msg.split(",");
                String skuId = msgArr[0], time = msgArr.length == 2 ? msgArr[1] : null;

                LocalDateTime now = LocalDateTime.now(), checkTime = now.minusSeconds(10);
                LocalDateTime createAt = StringUtils.isEmpty(time) ? checkTime : LocalDateTime.parse(time);
                long durationToMillis = Duration.between(createAt, checkTime).toMillis();
                if (durationToMillis >= 0) {
                    aBoolean = this.bizArtworkClqProcessing(skuId);
                } else {
                    try {
                        Thread.sleep(Math.abs(durationToMillis));
                    } catch (InterruptedException ignored) {
                    }
                    aBoolean = this.bizArtworkClqProcessing(skuId);
                }
            }
        } catch (Exception e) {
            log.error("CONSUMER MSG EX_HANDLE ==> [{}]:{}", this.getRedisStreamKey(), msg, e);
        } 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_ARTWORK_CLQ.getKey();
    }

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

    private boolean bizArtworkClqProcessing(String skuId) {
        String postUrl = serviceGoblinUrl + "/goblin/que/artwork/clq";
        LinkedMultiValueMap<String, String> postDataMap = CollectionUtil.linkedMultiValueMapStringString();
        try {
            postDataMap.add("skuId", skuId);
            String postRespStr = HttpUtil.post(postUrl, postDataMap);
            // 失败重新入队逻辑改至`被调用API`实现
//            JsonNode postRespJNode = JsonUtils.fromJson(postRespStr, JsonNode.class), postRespCode;
//            if (null == postRespJNode || null == (postRespCode = postRespJNode.get("code")) || !postRespCode.asText().equals("0")) {
//                log.warn("#NFT声明查询:处理失败[paramsStr={},postRespStr={}]", postDataMap, postRespStr);
//                return false;
//            }
            return true;
        } catch (Exception e) {
            log.error("Ex.NFT声明查询:处理异常[url={},paramsStr={}],ex:{}", postUrl, postDataMap, e.getMessage());
            return false;
        }
    }

    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */
}
