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

import com.fasterxml.jackson.databind.JsonNode;
import com.liquidnet.common.cache.redis.util.RedisUtil;
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.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.galaxy.dto.param.GalaxyArtSeriesClaimResultQueryReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyArtSeriesClaimResultQueryRespDto;
import com.liquidnet.service.goblin.constant.GoblinRedisConst;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.stereotype.Component;

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

@Slf4j
@Component
public class ConsumerGoblinBizArtworkClqRdsReceiver extends AbstractBizRedisReceiver {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MongoTemplate mongoTemplate;


//    @Value("${liquidnet.service.galaxy.url}")
//    private String serviceGalaxyUrl;
    @Value("${liquidnet.service.goblin.url}")
    private String serviceGoblinUrl;

    private static final String SQL_UPDATE_GOODS_SKU_NFT = "UPDATE goblin_goods_sku_nft SET upchain=?,series_id=?,series_hash=?,nft_hash=?,declare_at=?,updated_at=? WHERE sku_id=? ";

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

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

    @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;
    }

    private boolean bizArtworkClqProcessing(String skuId) {
        GoblinGoodsSkuInfoVo mgtGoodsSkuInfoVo = this.getGoodsSkuInfoVoFromMdb(skuId);
        if (null == mgtGoodsSkuInfoVo) {
            log.warn("#CONSUMER MSG NULL_SKU[{}]:[skuId={}]", this.getRedisStreamKey(), skuId);
            return true;
        }
        int skuType = mgtGoodsSkuInfoVo.getSkuType(), upchain = mgtGoodsSkuInfoVo.getUpchain();
        String unbox = mgtGoodsSkuInfoVo.getUnbox();
        // 非数字藏品 || 盲盒 || 非声明中 || 已有声明系列ID
        if (1 != skuType || !"0".equals(unbox) || 9 != upchain || StringUtils.isNotEmpty(mgtGoodsSkuInfoVo.getSeriesId())) {
            log.warn("#CONSUMER MSG VOID_SKU[{}]:[skuId={},skuType={},unbox={},upchain={},seriesId={}]",
                    this.getRedisStreamKey(), skuId, skuType, unbox, upchain, mgtGoodsSkuInfoVo.getSeriesId());
            return true;
        }

        GalaxyArtSeriesClaimResultQueryRespDto resultQueryRespDto = this.queryNftSeriesClaimResult(skuId, mgtGoodsSkuInfoVo.getRouteType());
        if (null == resultQueryRespDto) return false;// 声明查询失败，重新入队处理

        String seriesId = resultQueryRespDto.getSeriesId();
        String txHash = resultQueryRespDto.getTxHash();
        String nftHash = resultQueryRespDto.getNftHash();
        String chainTimestamp = resultQueryRespDto.getChainTimestamp();

        LocalDateTime now = LocalDateTime.now();
        mongoTemplate.getCollection(GoblinGoodsSkuInfoVo.class.getSimpleName()).updateOne(
                Query.query(Criteria.where("skuId").is(skuId).and("delFlg").is("0")).getQueryObject(),
                Update.update("upchain", 1).set("seriesId", seriesId).set("seriesHash", txHash).set("nftHash", nftHash).set("declareAt", chainTimestamp).getUpdateObject()
        );
        redisUtil.del(GoblinRedisConst.BASIC_GOODS_SKU.concat(skuId));

        // Mysql持久化
        HashMap<String, String> sqlUpdateMap = CollectionUtil.mapStringString();
        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        toMqSqls.add(SQL_UPDATE_GOODS_SKU_NFT);
        LinkedList<Object[]> updateGoodsSkuNftObjs = CollectionUtil.linkedListObjectArr();
        updateGoodsSkuNftObjs.add(new Object[]{1, seriesId, txHash, nftHash, chainTimestamp, now, skuId});

        sqlUpdateMap.put(MQConst.QUEUE_MESSAGE_KEY, SqlMapping.gets(toMqSqls, updateGoodsSkuNftObjs));
        stringRedisTemplate.opsForStream().add(StreamRecords.mapBacked(sqlUpdateMap).withStreamKey(MQConst.GoblinQueue.SQL_GOODS.getKey()));
        return true;
    }

    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */

    private GalaxyArtSeriesClaimResultQueryRespDto queryNftSeriesClaimResult(String skuId, String routerType) {
        GalaxyArtSeriesClaimResultQueryReqDto artSeriesClaimResultQueryReqDto = GalaxyArtSeriesClaimResultQueryReqDto.getNew();
        artSeriesClaimResultQueryReqDto.setSkuId(skuId);
        artSeriesClaimResultQueryReqDto.setRouterType(routerType);

//        String postUrl = serviceGalaxyUrl + "/galaxy/artwork/seriesClaimResultQuery";
        String postUrl = serviceGoblinUrl + "/goblin/nftArtwork/seriesClaimResultQuery";
        String postBoby = JsonUtils.toJson(artSeriesClaimResultQueryReqDto);
        try {
            String postRespStr = HttpUtil.postRaw(postUrl, postBoby, null);
            JsonNode postRespJNode = JsonUtils.fromJson(postRespStr, JsonNode.class), postRespCode, postRespDataJNode;
            if (null == postRespJNode || null == (postRespCode = postRespJNode.get("code")) || !postRespCode.asText().equals("0")) {
                log.warn("#CONSUMER MSG FAIL_UPC[{}]查询失败[paramsStr={},postRespStr={}]", this.getRedisStreamKey(), postBoby, postRespStr);
                return null;
            }
            if (1 != (postRespDataJNode = postRespJNode.get("data")).get("taskStatus").asInt()) {
                log.warn("#CONSUMER MSG FAIL_UPC[{}]声明失败[paramsStr={},postRespStr={}]", this.getRedisStreamKey(), postBoby, postRespStr);
                return null;
            }
            return JsonUtils.OM().convertValue(postRespDataJNode, GalaxyArtSeriesClaimResultQueryRespDto.class);
        } catch (Exception e) {
            log.error("Ex.CONSUMER MSG ERROR_UPC[{}]请求异常[url={},paramsStr={}],ex:{}", this.getRedisStreamKey(), postUrl, postBoby, e.getMessage());
            return null;
        }
    }

    /* ------------------------------------------------------------------------------------ */
    /* ------------------------------------------------------------------------------------ */

    public GoblinGoodsSkuInfoVo getGoodsSkuInfoVoFromMdb(String skuId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("skuId").is(skuId).and("delFlg").is("0")),
                GoblinGoodsSkuInfoVo.class, GoblinGoodsSkuInfoVo.class.getSimpleName());
    }

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