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 org.springframework.util.LinkedMultiValueMap;

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

@Slf4j
@Component
public class ConsumerGoblinBizArtworkTransQueryReceiver 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 bizId = msgArr[0], time = msgArr.length == 2 ? msgArr[1] : null;

                LocalDateTime now = LocalDateTime.now(), checkTime = now.minusSeconds(15);
                LocalDateTime createAt = StringUtils.isEmpty(time) ? checkTime : LocalDateTime.parse(time);
                long durationToMillis = Duration.between(createAt, checkTime).toMillis();
                if (durationToMillis >= 0) {
                    aBoolean = this.bizArtworkTransQueryProcessing(bizId);
                } else {
                    try {
                        Thread.sleep(Math.abs(durationToMillis));
                    } catch (InterruptedException ignored) {
                    }
                    aBoolean = this.bizArtworkTransQueryProcessing(bizId);
                }
            }
        } 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_TRANS_QUERY.getKey();
    }

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

    private boolean bizArtworkTransQueryProcessing(String artworkId) {
        String postUrl = serviceGoblinUrl + "/goblin/que/artwork/transQuery";
        LinkedMultiValueMap<String, String> postDataMap = CollectionUtil.linkedMultiValueMapStringString();
        try {
            postDataMap.add("artworkId", artworkId);
            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("#藏品转赠结果查询:处理失败[paramsStr={},postRespStr={}]", postDataMap, postRespStr);
//                return false;
//            }
            return true;
        } catch (Exception e) {
            log.error("Ex.藏品转赠结果查询:处理异常[url={},paramsStr={}],ex:{}", postUrl, postDataMap, e.getMessage());
            return false;
        }
    }

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