package com.liquidnet.service.galaxy.router.zxin.biz;

import com.liquidnet.common.third.zxlnft.biz.ZxlnftBiz;
import com.liquidnet.common.third.zxlnft.config.ZxlnftConfig;
import com.liquidnet.common.third.zxlnft.constant.ZxlnftEnum;
import com.liquidnet.common.third.zxlnft.dto.*;
import com.liquidnet.common.third.zxlnft.util.ZxlnftSdkUtil;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.galaxy.biz.GalaxyBeanTransferBiz;
import com.liquidnet.service.galaxy.biz.GalaxyEnumBiz;
import com.liquidnet.service.galaxy.biz.GalaxyTradeBiz;
import com.liquidnet.service.galaxy.constant.GalaxyEnum;
import com.liquidnet.service.galaxy.constant.GalaxyErrorEnum;
import com.liquidnet.service.galaxy.dto.bo.GalaxyNftOrderBindBo;
import com.liquidnet.service.galaxy.dto.bo.GalaxyNftOrderBo;
import com.liquidnet.service.galaxy.dto.bo.GalaxySeriesNftInfoBo;
import com.liquidnet.service.galaxy.dto.bo.GalaxyUserInfoBo;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftBuyRespDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishAndBuyReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishAndBuyRespDto;
import com.liquidnet.service.galaxy.dto.vo.mongo.GalaxyNftOrderFailLogVo;
import com.liquidnet.service.galaxy.exception.GalaxyNftBuyException;
import com.liquidnet.service.galaxy.exception.GalaxyNftPublishException;
import com.liquidnet.service.galaxy.utils.GalaxyDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: ZxinTradeBiz
 * @Package com.liquidnet.service.galaxy.router.zxin.biz
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2022/3/15 13:08
 */
@Slf4j
@Component
public class ZxinTradeCommonBiz {
    @Autowired
    private ZxlnftSdkUtil zxlnftSdkUtil;

    @Autowired
    private ZxlnftBiz zxlnftBiz;

    @Autowired
    private ZxlnftConfig zxlnftConfig;

    @Autowired
    private GalaxyDataUtils dataUtils;

    @Autowired
    private GalaxyBeanTransferBiz galaxyBeanTransferBiz;

    @Autowired
    private GalaxyTradeBiz galaxyTradeBiz;

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    public ResponseDto<GalaxyNftPublishAndBuyRespDto> nftPublishAndBuy(GalaxyNftPublishAndBuyReqDto reqDto) {
        log.info("开始执行nftPublishAndBuy 请求参数:{}",reqDto.toString());
        //获取用户信息
        GalaxyUserInfoBo userInfoBo = dataUtils.getGalaxyUserInfo(reqDto.getRouterType(),reqDto.getUserId());
        if(StringUtil.isNull(userInfoBo)){
            log.error("开始执行nftPublishAndBuy error msg:{}",GalaxyErrorEnum.NFT_BUY_FAIL_USER_NOT_EXIST.getMessage());
            return ResponseDto.failure(GalaxyErrorEnum.NFT_BUY_FAIL_USER_NOT_EXIST.getCode(), GalaxyErrorEnum.NFT_BUY_FAIL_USER_NOT_EXIST.getMessage());
        }

        //获取sku信息
        GalaxySeriesNftInfoBo seriesNftInfoBo = dataUtils.getSeriesNftInfoBo(reqDto.getRouterType(),reqDto.getSkuId());
        if(StringUtil.isNull(seriesNftInfoBo)||StringUtil.isEmpty(seriesNftInfoBo.getSeriesId())){
            log.error("开始执行nftPublishAndBuy error msg:{}",GalaxyErrorEnum.SERIES_NFT_INFO_NOT_EXIST.getMessage());
            return ResponseDto.failure(GalaxyErrorEnum.SERIES_NFT_INFO_NOT_EXIST.getCode(), GalaxyErrorEnum.SERIES_NFT_INFO_NOT_EXIST.getMessage());
        }

        //获取订单信息
        GalaxyNftOrderBo nftOrderBo = dataUtils.getNftOrderBo(reqDto.getRouterType(),reqDto.getNftOrderPayId());
        //初始化订单数据
        if(nftOrderBo==null){
            nftOrderBo = galaxyBeanTransferBiz.buildNftOrderBo(reqDto.getNftOrderPayId(),userInfoBo,seriesNftInfoBo);
            dataUtils.setNftOrderBo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBo);
        }else if(StringUtil.isNotNull(nftOrderBo)){
            if(nftOrderBo.getNftPublishStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.TASK_SUCCESS.getCode())
                    &&nftOrderBo.getNftBuyStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.TASK_SUCCESS.getCode())){
                GalaxyNftPublishAndBuyRespDto nftPublishAndBuyRespDto = GalaxyNftPublishAndBuyRespDto.getNew();
                nftPublishAndBuyRespDto.setUserId(reqDto.getUserId());
                nftPublishAndBuyRespDto.setNftId(nftOrderBo.getNftId());
                log.error("开始执行nftPublishAndBuy error msg:{}", GalaxyErrorEnum.PUBLISH_FAIL_ALREADY_EXIST.toString());
                return ResponseDto.success(nftPublishAndBuyRespDto);
            }
            if(nftOrderBo.getNftPublishStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.TASK_SUCCESS.getCode())
                    &&(nftOrderBo.getNftBuyStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.INIT.getCode())
                    ||nftOrderBo.getNftBuyStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.PROCESSING.getCode()))){
                //再次发起购买
                GalaxyNftPublishAndBuyRespDto nftPublishAndBuyRespDto = this.executeBuyBusiness(reqDto,userInfoBo,seriesNftInfoBo,nftOrderBo);
                if(StringUtil.isNotNull(nftPublishAndBuyRespDto)&&StringUtil.isNotEmpty(nftPublishAndBuyRespDto.getNftId())){
                    return ResponseDto.success(nftPublishAndBuyRespDto);
                }else{
                    log.error("开始执行nftPublishAndBuy-->executeBuyBusiness error msg:{}",GalaxyErrorEnum.NFT_BUY_FAIL.getMessage());
                    return ResponseDto.failure(GalaxyErrorEnum.NFT_BUY_FAIL.getCode(),GalaxyErrorEnum.NFT_BUY_FAIL.getMessage());
                }
            }
        }

        String author = seriesNftInfoBo.getAuthor();
        String nftName = seriesNftInfoBo.getNftName();
        String nftUrl = seriesNftInfoBo.getNftUrl();
        String displayUrl = seriesNftInfoBo.getDisplayUrl();

        String nftDesc = seriesNftInfoBo.getNftDesc();
        String nftFlag = seriesNftInfoBo.getNftFlag();
        //发行个数
        Long publishCount = 1L;
        //开始索引
        Integer seriesBeginIndex = null;
        //发行金额
        Long sellCount = seriesNftInfoBo.getSellCount().longValue(); //积分
        /**
         * 根据sku获取系列Id
         */
        String seriesId = seriesNftInfoBo.getSeriesId();
        //返回参数nftId
        String nftId = null;
        String publishTaskId = null;
        Long nftPublishChainTimestamp = null;
        Integer nftPublishStatus = null;
        String nftPublishTradeHash = null;

        //定义失败信息
        String failDesc = null;
        try{
            /**
             * 获取订单和nft绑定信息
             */
            GalaxyNftOrderBindBo nftOrderBindBo = dataUtils.getGalaxyNftOrderBindBo(reqDto.getRouterType(),reqDto.getNftOrderPayId());
            if(StringUtil.isNull(nftOrderBindBo)){
                //获取发行索引
                long nftIdNo = dataUtils.incrNftIdNo(reqDto.getRouterType(),reqDto.getSkuId());
                //如果发行数大于最大发行数量
                if(nftIdNo > seriesNftInfoBo.getNftTotalCount()){
                    //发行失败
                    throw new GalaxyNftPublishException(GalaxyErrorEnum.NFT_PUBLISH_ERROR.getCode(),"该sku："+reqDto.getSkuId()+" 总共"+seriesNftInfoBo.getNftTotalCount()+"个NFT已经发行完毕，没有剩余库存！");
                }

                //判断是否切换订单
                while(galaxyTradeBiz.isNeedSwitch(reqDto.getSkuId(),String.valueOf(nftIdNo))){
                    long finalNftIdNo = nftIdNo;
                    //开启新线程去执行购买
                    executorService.submit(() -> {
                        galaxyTradeBiz.switchBuyRouterBySkuId(reqDto.getSkuId(),String.valueOf(finalNftIdNo),seriesNftInfoBo);
                    });
                    nftIdNo = dataUtils.incrNftIdNo(reqDto.getRouterType(),reqDto.getSkuId());
                }

                nftOrderBindBo = GalaxyNftOrderBindBo.getNew();
                nftOrderBindBo.setNftOrderPayId(reqDto.getNftOrderPayId());
                nftOrderBindBo.setSeriesId(seriesNftInfoBo.getSeriesId());
                nftOrderBindBo.setSeriesCode(seriesNftInfoBo.getSeriesCode());
                nftOrderBindBo.setNftIdIndex(Integer.valueOf(String.valueOf(nftIdNo)));
                nftOrderBindBo.setRouterType(reqDto.getRouterType());
                String nowTimeStr = DateUtil.Formatter.yyyyMMddHHmmss.format(LocalDateTime.now());
                nftOrderBindBo.setCreatedAt(nowTimeStr);
                dataUtils.setGalaxyNftOrderBindBo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBindBo);
            }
            seriesBeginIndex = nftOrderBindBo.getNftIdIndex();

//        //查询系列信息(暂时不通过系列查询获取发行序列号)
//        Nft032SeriesReqDto nft032ReqDto = Nft032SeriesReqDto.getNew();
//        nft032ReqDto.setSeriesId(seriesId);
//        ZxlnftResponseDto<Nft032SeriesRespDto> resp = zxlnftSdkUtil.nft032Series(nft032ReqDto);
//
//        if(resp.isSuccess()){
//            //该系列已经发行多少个nft
//            Long crtCount = resp.getData().getSeriesInfo().getCrtCount();
//            log.info("系列：{} 已发行 ：{}", seriesId, crtCount);
//            //设置开始索引
//            seriesBeginIndex = Integer.parseInt(String.valueOf(crtCount.longValue() + 1));
//        }

            /**
             * 如果已经发行购买成功
             */
            if(nftOrderBo.getNftPublishStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.PROCESSING.getCode())){
                if(StringUtil.isNotEmpty(nftOrderBo.getNftPublishTaskId())){
                    publishTaskId = nftOrderBo.getNftPublishTaskId();
                }
            }else if(nftOrderBo.getNftPublishStatus().equalsIgnoreCase(GalaxyEnum.TaskStatusEnum.INIT.getCode())){
                //3.1.2调用NFT发行接口
                /**
                 * 发行无限制系列
                 */
                Nft034PublishReqDto nft034ReqDto = Nft034PublishReqDto.getNew();
                nft034ReqDto.setAuthor(author);
                nft034ReqDto.setName(nftName);
                nft034ReqDto.setUrl(nftUrl);
                nft034ReqDto.setDisplayUrl(displayUrl);
                nft034ReqDto.setDesc(nftDesc);
                nft034ReqDto.setFlag(nftFlag);
                nft034ReqDto.setPublishCount(publishCount);
                //无限制零系列
                nft034ReqDto.setSeriesId(seriesId);
                nft034ReqDto.setSeriesBeginIndex(seriesBeginIndex);
                nft034ReqDto.setSellStatus(Integer.parseInt(ZxlnftEnum.SellStatusEnum.CAN_SELL.getCode()));
                nft034ReqDto.setSellCount(sellCount);
                nft034ReqDto.setOperateId(IDGenerator.get32UUID());
                nft034ReqDto.setMetaData(seriesNftInfoBo.getNftHash());

                ZxlnftResponseDto<Nft034PublishRespDto> nft034RespDto = zxlnftSdkUtil.nft034Publish(nft034ReqDto);
                if (nft034RespDto.isSuccess()){
                    publishTaskId = nft034RespDto.getData().getTaskId();
                    nftOrderBo.setNftPublishTaskId(publishTaskId);
                }
            }

            if (StringUtil.isNotEmpty(publishTaskId)){
                try{
                    //3.1.4查询 NFT发行结果
                    Nft035PublishResultReqDto nft035ReqDto = Nft035PublishResultReqDto.getNew();
                    nft035ReqDto.setTaskId(publishTaskId);

                    int count = 0;
                    String nftIdBegin = null;
                    long timeStart = System.currentTimeMillis();
                    while (StringUtil.isEmpty(nftIdBegin)) {
                        Thread.sleep(500l);
                        count++;
                        ZxlnftResponseDto<Nft035PublishResultRespDto> nft035RespDtoTemp = zxlnftSdkUtil.nft035PublishResult(nft035ReqDto);
                        log.info("=======执行第{}次查询,taskId:{}", count, nft035ReqDto.getTaskId());
                        if (nft035RespDtoTemp.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.TASK_SUCCESS.getCode())) {
                            nftIdBegin = nft035RespDtoTemp.getData().getNftIdBegin();
                            nftPublishChainTimestamp = nft035RespDtoTemp.getData().getChainTimestamp();
                            nftPublishStatus = nft035RespDtoTemp.getData().getTaskStatus();
                            nftPublishTradeHash = nft035RespDtoTemp.getData().getTxHash();
                        } else if (nft035RespDtoTemp.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.TASK_FAIL.getCode())) {
                            log.info("任务执行失败！taskId:{}", nft035ReqDto.getTaskId());
                            nftPublishStatus = nft035RespDtoTemp.getData().getTaskStatus();
                            //发行失败
                            throw new GalaxyNftPublishException(GalaxyErrorEnum.PUBLISH_FAIL.getCode(), "nft035PublishResult_resp:"+GalaxyErrorEnum.PUBLISH_FAIL.getMessage());
                        }else if(nft035RespDtoTemp.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.PROCESSING.getCode())){
                            log.info("任务执行中！taskId:{}", nft035ReqDto.getTaskId());
                            nftPublishStatus = nft035RespDtoTemp.getData().getTaskStatus();
                        }

                        if (count == 20) {
                            log.info("=======查询共20次，跳出循环！taskId:{}", nft035ReqDto.getTaskId());
                            break;
                        }
                    }

                    //赋值返回参数
                    nftId = nftIdBegin;
                    nftOrderBo.setNftId(nftId);
                    log.info("发行NFT后返回给前端nftID:{}", nftIdBegin);
                    log.info("总共执行了{}次查询 总耗时:{} MS", count, (System.currentTimeMillis() - timeStart));
                }catch (GalaxyNftPublishException e){
                    throw new GalaxyNftPublishException(e.getCode(),e.getMessage());
                }catch(Exception e){
                    log.error(e.getMessage(),e);
                    //发行失败
                    throw new GalaxyNftPublishException(GalaxyErrorEnum.NFT_PUBLISH_ERROR.getCode(),"nft035PublishResult_exception:"+e.getMessage());
                }
            }else{
                //发行失败
                throw new GalaxyNftPublishException(GalaxyErrorEnum.NFT_PUBLISH_ERROR.getCode(),"nft034Publish_resp:taskId : "+publishTaskId);
            }
        }catch (GalaxyNftPublishException e) {
            failDesc = e.getMessage();
        }catch(Exception e){
            failDesc = e.getMessage();
            log.error(e.getMessage(),e);

        }

        if(StringUtil.isNotEmpty(failDesc)){
            //记录发行异常信息
            try{
                //发行异常或者失败记录任务id
                if(StringUtil.isNotNull(nftOrderBo)&&StringUtil.isNotEmpty(nftOrderBo.getNftPublishTaskId())){
                    nftOrderBo.setNftPublishStatus(GalaxyEnum.TaskStatusEnum.PROCESSING.getCode());
                    nftOrderBo.setUpdatedAt(LocalDateTime.now());
                    //更新nft发行状态为处理中
                    dataUtils.updateNftOrderPublishInfo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBo);
                }else{
                    //记录错误信息
                    GalaxyNftOrderFailLogVo nftOrderFailLogVo = galaxyBeanTransferBiz.buildNftOrderFailLogVo(GalaxyEnum.TradeTypeEnum.TRADE_PUBLISH,reqDto,GalaxyEnum.OrderDealWithStatusEnum.DATA_INIT,failDesc,null
                            ,userInfoBo,seriesNftInfoBo,nftOrderBo);
                    dataUtils.setNftOrderFailLogVo(reqDto.getRouterType(),nftOrderFailLogVo);
                }
            }catch(Exception e){
                log.error(reqDto.getNftOrderPayId()+"发行setNftOrderFailLogVo记录异常："+e.getMessage(),e);
            }
            return ResponseDto.failure(GalaxyErrorEnum.PUBLISH_FAIL.getCode(), GalaxyErrorEnum.PUBLISH_FAIL.getMessage());
        }

        //更新订单缓存数据状态
        if(StringUtil.isNotEmpty(nftOrderBo.getNftId())){
            if(StringUtil.isNotNull(nftPublishChainTimestamp)){
                //设置时间
                String nftPublishChainTimestampStr = DateUtil.format(new Date(nftPublishChainTimestamp*1000),DateUtil.Formatter.yyyyMMddHHmmss);
                nftOrderBo.setNftPublishChainTimestamp(nftPublishChainTimestampStr);
            }
            if(StringUtil.isNotNull(nftPublishStatus)){
                //转换任务状态
                String nftPublishStatusStr = GalaxyEnumBiz.getTaskStatusEnum(reqDto.getRouterType(),nftPublishStatus.toString()).getCode();
                nftOrderBo.setNftPublishStatus(nftPublishStatusStr);
            }
            nftOrderBo.setNftPublishTradeHash(nftPublishTradeHash);
            nftOrderBo.setUpdatedAt(LocalDateTime.now());
            //先更新nft发行数据
            dataUtils.updateNftOrderPublishInfo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBo);
        }

        //第二步：执行购买逻辑
        if(StringUtil.isNotEmpty(nftOrderBo.getNftId())){
            GalaxyNftPublishAndBuyRespDto nftPublishAndBuyRespDto = this.executeBuyBusiness(reqDto,userInfoBo,seriesNftInfoBo,nftOrderBo);
            if(StringUtil.isNotNull(nftPublishAndBuyRespDto)&&StringUtil.isNotEmpty(nftPublishAndBuyRespDto.getNftId())){
                return ResponseDto.success(nftPublishAndBuyRespDto);
            }else{
                return ResponseDto.failure(GalaxyErrorEnum.NFT_BUY_FAIL.getCode(),GalaxyErrorEnum.NFT_BUY_FAIL.getMessage());
            }
        }
        return ResponseDto.failure(GalaxyErrorEnum.PUBLISH_FAIL.getCode(), GalaxyErrorEnum.PUBLISH_FAIL.getMessage());
    }

    private GalaxyNftPublishAndBuyRespDto executeBuyBusiness(GalaxyNftPublishAndBuyReqDto reqDto,GalaxyUserInfoBo userInfoBo, GalaxySeriesNftInfoBo seriesNftInfoBo,GalaxyNftOrderBo nftOrderBo){
        String buyFailDesc = null;
        //执行购买逻辑
        GalaxyNftPublishAndBuyRespDto nftPublishAndBuyRespDto = GalaxyNftPublishAndBuyRespDto.getNew();
        try{
            GalaxyNftBuyRespDto nftBuyRespDto = this.nftBuyBusinessSync(reqDto.getRouterType(),nftOrderBo.getNftId(),userInfoBo,seriesNftInfoBo,nftOrderBo);
            BeanUtil.copy(nftBuyRespDto,nftPublishAndBuyRespDto);
        }catch (GalaxyNftBuyException e){
            buyFailDesc = e.getMessage();
        }catch(Exception e){
            buyFailDesc = e.getMessage();
            log.error(e.getMessage(),e);
        }

        if(StringUtil.isNotEmpty(buyFailDesc)){
            //记录购买异常信息
            try{
                GalaxyNftOrderFailLogVo nftOrderFailLogVo = galaxyBeanTransferBiz.buildNftOrderFailLogVo(GalaxyEnum.TradeTypeEnum.TRADE_BUY,reqDto,GalaxyEnum.OrderDealWithStatusEnum.DATA_INIT,buyFailDesc,null
                        ,userInfoBo,seriesNftInfoBo,nftOrderBo);
                dataUtils.setNftOrderFailLogVo(reqDto.getRouterType(),nftOrderFailLogVo);
            }catch(Exception e){
                log.error(reqDto.getNftOrderPayId()+"购买setNftOrderFailLogVo记录异常："+e.getMessage(),e);
            }
        }
        return nftPublishAndBuyRespDto;
    }
    /**
     * 保持线程循环查询
     * @param nftId
     * @param userInfoBo
     * @param seriesNftInfoBo
     * @return
     */
    private GalaxyNftBuyRespDto nftBuyBusinessSync(String routerType,String nftId,GalaxyUserInfoBo userInfoBo, GalaxySeriesNftInfoBo seriesNftInfoBo,GalaxyNftOrderBo nftOrderBo){
        //定义返回参数
        String nftBuyTaskId = null;
        Long nftBuyChainTimestamp = null;
        Integer nftBuyStatus = null;
        String nftBuyTradeHash = null;
        String nftBuyPayTaskId = null;

        //如果购买任务不为空，则直接进行购买任务查询
        if(StringUtil.isNotEmpty(nftOrderBo.getNftBuyTaskId())){
            nftBuyTaskId = nftOrderBo.getNftBuyTaskId();
        }

        if(StringUtil.isEmpty(nftBuyTaskId)){
            //        3.2.2调用购买NFT接口
            Nft043BuyReqDto nft043BuyReqDto = Nft043BuyReqDto.getNew();
            nft043BuyReqDto.setNftId(nftId);
            nft043BuyReqDto.setApplyScore(seriesNftInfoBo.getSellCount().intValue());
            try {
                nft043BuyReqDto.setReceiverPubKey(BASE64Util.decode(userInfoBo.getUserPubKey()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            nft043BuyReqDto.setPointReceiverAddr(zxlnftConfig.getNftPlatformAddress());
            nft043BuyReqDto.setOfferCount(seriesNftInfoBo.getSellCount().longValue());
            nft043BuyReqDto.setOperateId(IDGenerator.get32UUID());

            /**
             * 接收人的私钥签名，签名对象是(platformPubKey_receiverPubKey_pointReceiverAddr_applyScore_接口名_nftId_offerCount_operateId)
             * 接口名：buy_nft
             */
            String signMetaData = zxlnftConfig.getNftPlatformPubKey()
                    .concat("_").concat(nft043BuyReqDto.getReceiverPubKey())
                    .concat("_").concat(nft043BuyReqDto.getPointReceiverAddr())
                    .concat("_").concat(nft043BuyReqDto.getApplyScore().toString())
                    .concat("_").concat("buy_nft")
                    .concat("_").concat(nft043BuyReqDto.getNftId())
                    .concat("_").concat(nft043BuyReqDto.getOfferCount().toString())
                    .concat("_").concat(nft043BuyReqDto.getOperateId());
            String signature = null;
            try {
                signature = zxlnftBiz.createSign(BASE64Util.decode(userInfoBo.getUserPriKey()),signMetaData);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            nft043BuyReqDto.setSignature(signature);

            ZxlnftResponseDto<Nft043BuyRespDto> nft043RespDto = zxlnftSdkUtil.nft043Buy(nft043BuyReqDto);
            if(nft043RespDto.isSuccess()){
                nftBuyTaskId = nft043RespDto.getData().getTaskId();
                nftOrderBo.setNftBuyTaskId(nftBuyTaskId);
            }
        }

        //如果购买任务id不为空
        if(StringUtil.isNotEmpty(nftBuyTaskId)){
            try{
                //3.2.4查询NFT购买结果
                Nft044BuyResultReqDto nft044ReqDto = Nft044BuyResultReqDto.getNew();
                nft044ReqDto.setTaskId(nftBuyTaskId);

                long timeStart = System.currentTimeMillis();

                int count  = 0;
                while(nftBuyPayTaskId == null){
                    Thread.sleep(500l);
                    count++;
                    log.info("=======执行第{}次查询,taskId:{}",count,nft044ReqDto.getTaskId());
                    ZxlnftResponseDto<Nft044BuyResultRespDto> nft044RespDto = zxlnftSdkUtil.nft044BuyResult(nft044ReqDto);
                    if(nft044RespDto.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.TASK_SUCCESS.getCode())){
                        nftBuyPayTaskId = nft044RespDto.getData().getPayTaskId();
                        nftBuyChainTimestamp = nft044RespDto.getData().getChainTimestamp();
                        nftBuyStatus = nft044RespDto.getData().getTaskStatus();
                        nftBuyTradeHash = nft044RespDto.getData().getTxHash();
                    }else if(nft044RespDto.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.TASK_FAIL.getCode())){
                        log.info("任务执行失败！taskId:{}",nft044ReqDto.getTaskId());
                        nftBuyStatus = nft044RespDto.getData().getTaskStatus();

                        //购买失败
                        throw new GalaxyNftBuyException(GalaxyErrorEnum.NFT_BUY_FAIL.getCode(), "nft044BuyResult_resp:"+GalaxyErrorEnum.NFT_BUY_FAIL.getMessage());
                    }else if(nft044RespDto.getData().getTaskStatus().toString().equals(ZxlnftEnum.TaskStatusEnum.PROCESSING.getCode())){
                        log.info("任务执行中！taskId:{}",nft044ReqDto.getTaskId());
                        nftBuyStatus = nft044RespDto.getData().getTaskStatus();
                    }
                    if(count==20){
                        //查询超过20次，则把nftId设置为空，为后续重新入队
                        nftId = null;
                        log.info("=======查询共5次，跳出循环！taskId:{}",nft044ReqDto.getTaskId());
                        break;
                    }
                }
                log.info("总共执行了多少次查询：{} 总耗时:{}",count,System.currentTimeMillis() - timeStart);
//            if(StringUtil.isNotEmpty(payTaskId)){
//                //3.2.5查询NFT购买支付结果
//                Nft045BuyPayResultReqDto nft045ReqDto = Nft045BuyPayResultReqDto.getNew();
//                nft045ReqDto.setTaskId(payTaskId);
//                ZxlnftResponseDto<Nft045BuyPayResultRespDto> nft045RespDto = zxlnftSdkUtil.nft045BuyPayResult(nft045ReqDto);
//            }
            }catch (GalaxyNftBuyException e){
                throw new GalaxyNftBuyException(e.getCode(),e.getMessage());
            }catch(Exception e){
                log.error(e.getMessage(),e);
                //发行失败
                throw new GalaxyNftBuyException(GalaxyErrorEnum.NFT_BUY_ERROR.getCode(),"nft044BuyResult_exception:"+e.getMessage());
            }

            //更新订单缓存数据状态
            if(StringUtil.isNotNull(nftBuyChainTimestamp)){
                //设置时间
                String nftBuyChainTimestampStr = DateUtil.format(new Date(nftBuyChainTimestamp*1000),DateUtil.Formatter.yyyyMMddHHmmss);
                nftOrderBo.setNftBuyChainTimestamp(nftBuyChainTimestampStr);
            }
            if(StringUtil.isNotNull(nftBuyStatus)){
                //转换任务状态
                String nftBuyStatusStr = GalaxyEnumBiz.getTaskStatusEnum(routerType,nftBuyStatus.toString()).getCode();

                nftOrderBo.setNftBuyStatus(nftBuyStatusStr);
            }
            nftOrderBo.setNftBuyTradeHash(nftBuyTradeHash);
            nftOrderBo.setNftBuyPayTaskId(nftBuyPayTaskId);
            nftOrderBo.setUpdatedAt(LocalDateTime.now());
            //先更新nft购买数据
            dataUtils.updateNftOrderBuyInfo(routerType,nftOrderBo.getNftOrderPayId(),nftOrderBo);
        }else{
            //购买失败
            throw new GalaxyNftBuyException(GalaxyErrorEnum.NFT_BUY_ERROR.getCode(),"nft043Buy_resp: nftBuyTaskId："+nftBuyTaskId);
        }

        GalaxyNftBuyRespDto nftBuyRespDto = GalaxyNftBuyRespDto.getNew();
        nftBuyRespDto.setUserId(userInfoBo.getUserId());
        nftBuyRespDto.setNftId(nftId);
        return nftBuyRespDto;
    }
}
