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

import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.third.xuper.config.XuperConfig;
import com.liquidnet.common.third.xuper.dto.*;
import com.liquidnet.common.third.xuper.exception.XupterException;
import com.liquidnet.common.third.xuper.util.XuperSdkUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.StringUtil;
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.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.GalaxyNftPublishReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishRespDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishResultQueryReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishResultQueryRespDto;
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.time.LocalDateTime;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: XuperPublishBiz
 * @Package com.liquidnet.service.galaxy.router.xuper.biz
 * @Copyright: LightNet @ Copyright (c) 2022
 * @date 2022/6/27 11:10
 */
@Slf4j
@Component
public class XuperPublishBiz {
    @Autowired
    private XuperSdkUtil xuperSdkUtil;

    @Autowired
    private XuperConfig xuperConfig;

    @Autowired
    private GalaxyDataUtils dataUtils;

    @Autowired
    private GalaxyBeanTransferBiz galaxyBeanTransferBiz;

    /**
     * nft发行
     * @param reqDto
     * @return
     */
    public ResponseDto<GalaxyNftPublishRespDto> nftPublish(GalaxyNftPublishReqDto reqDto) {
        //获取订单信息
        GalaxyNftOrderBo nftOrderBo = dataUtils.getNftOrderBo(reqDto.getRouterType(),reqDto.getNftOrderPayId());
        if(StringUtil.isNotNull(nftOrderBo)){
            return ResponseDto.failure(GalaxyErrorEnum.PUBLISH_FAIL_ALREADY_EXIST.getCode(), GalaxyErrorEnum.PUBLISH_FAIL_ALREADY_EXIST.getMessage());
        }

        //获取sku信息
        GalaxySeriesNftInfoBo seriesNftInfoBo = dataUtils.getSeriesNftInfoBo(reqDto.getRouterType(),reqDto.getSkuId());
        if(StringUtil.isNull(seriesNftInfoBo)){
            return ResponseDto.failure(GalaxyErrorEnum.SERIES_NFT_INFO_NOT_EXIST.getCode(), GalaxyErrorEnum.SERIES_NFT_INFO_NOT_EXIST.getMessage());
        }

        /**
         * 获取订单和nft绑定信息
         */
        GalaxyNftOrderBindBo nftOrderBindBo = dataUtils.getGalaxyNftOrderBindBo(reqDto.getRouterType(),reqDto.getNftOrderPayId());
        if(StringUtil.isNull(nftOrderBindBo)){
            //获取发行索引
            long 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);
        }

        //获取用户信息
        GalaxyUserInfoBo userInfoBo = dataUtils.getGalaxyUserInfo(reqDto.getRouterType(),reqDto.getUserId());

        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 = nftOrderBindBo.getNftIdIndex();;
        Long sellCount = seriesNftInfoBo.getSellCount().longValue(); //积分
        /**
         * 根据sku获取系列Id
         */
        String seriesId = seriesNftInfoBo.getSeriesId();
        //返回参数nftId
        String nftId = null;
        String taskId = null;

        //发行
        Xuper004PublishAssetReqDto xuper004PublishAssetReqDto = Xuper004PublishAssetReqDto.getNew();
        // 定义返回结果对象
        Xuper004PublishAssetRespDto xuper004PublishAssetRespDto = null;
        long assetId = Long.parseLong(seriesNftInfoBo.getSeriesId());
        try {
            xuper004PublishAssetReqDto.setMnemonic(xuperConfig.getNftPlatformMnemonic());
            xuper004PublishAssetReqDto.setAssetId(assetId);
            XuperResponseDto<Xuper004PublishAssetRespDto> xuperResponseDto = xuperSdkUtil.xuper004PublishAsset(xuper004PublishAssetReqDto);
            if(xuperResponseDto.isSuccess()){
                xuper004PublishAssetRespDto = xuperResponseDto.getParseData(Xuper004PublishAssetRespDto.class);
            }
        }catch (XupterException e) {
            log.error("biz error msg "+e.getMessage(),e);
        }catch (Exception e) {
            log.error("sys error msg "+e.getMessage(),e);
        }
        log.info("xuper004PublishAsset resp : "+ JsonUtils.toJson(xuper004PublishAssetRespDto));

        if (Integer.parseInt(ErrorCode.SUCCESS.getCode()) == xuper004PublishAssetRespDto.errNo){
            //赋值返回参数
            taskId = String.valueOf(assetId);
            nftId = seriesId.concat("_").concat(seriesBeginIndex.toString());

            nftOrderBo.setNftId(nftId);
            nftOrderBo.setNftPublishTaskId(taskId);
        }

        GalaxyNftPublishRespDto nftPublishRespDto = GalaxyNftPublishRespDto.getNew();
        nftPublishRespDto.setUserId(reqDto.getUserId());
        nftPublishRespDto.setNftId(nftId);

        //构造缓存数据
        if(nftOrderBo==null){
            nftOrderBo = galaxyBeanTransferBiz.buildNftOrderBo(reqDto.getNftOrderPayId(),userInfoBo,seriesNftInfoBo);
            nftOrderBo.setNftId(nftId);
            nftOrderBo.setNftPublishTaskId(taskId);
            nftOrderBo.setNftPublishStatus(GalaxyEnum.TaskStatusEnum.PROCESSING.getCode());
            dataUtils.setNftOrderBo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBo);
        }
        return ResponseDto.success(nftPublishRespDto);
    }

    /**
     * nft发行结果查询
     * @param reqDto
     * @return
     */
    public ResponseDto<GalaxyNftPublishResultQueryRespDto> nftPublishResultQuery(GalaxyNftPublishResultQueryReqDto reqDto){
        //获取订单信息
        GalaxyNftOrderBo nftOrderBo = dataUtils.getNftOrderBo(reqDto.getRouterType(),reqDto.getNftOrderPayId());
        if(StringUtil.isNull(nftOrderBo)){
            return ResponseDto.failure(GalaxyErrorEnum.PUBLISH_ORDER_NOT_EXIST.getCode(), GalaxyErrorEnum.PUBLISH_ORDER_NOT_EXIST.getMessage());
        }

        //NFT发行结果查询
        Xuper005QueryAssetReqDto xuper005QueryAssetReqDto = Xuper005QueryAssetReqDto.getNew();
        xuper005QueryAssetReqDto.setAssetId(Long.parseLong(nftOrderBo.getSeriesId()));
        // 定义返回结果对象
        Xuper005QueryAssetRespDto xuper005QueryAssetRespDto = null;
        try {
            XuperResponseDto<Xuper005QueryAssetRespDto>  xuperResponseDto = xuperSdkUtil.xuper005QueryAsset(xuper005QueryAssetReqDto);
            if(xuperResponseDto.isSuccess()){
                xuper005QueryAssetRespDto = xuperResponseDto.getParseData(Xuper005QueryAssetRespDto.class);
            }
        }catch (XupterException e) {
            log.error("biz error msg "+e.getMessage(),e);
        }catch (Exception e) {
            log.error("sys error msg "+e.getMessage(),e);
        }
        log.info("xuper005QueryAsset resp : "+ JsonUtils.toJson(xuper005QueryAssetRespDto));

        if (Integer.parseInt(ErrorCode.SUCCESS.getCode()) == xuper005QueryAssetRespDto.getErrNo()){
            //获取资产信息
            Xuper005QueryAssetRespDto.AssetMeta assetMeta = xuper005QueryAssetRespDto.getMeta();
            //设置时间
            String nftPublishChainTimestampStr = DateUtil.getNowTime();
            //转换任务状态
            String nftPublishStatusStr = GalaxyEnumBiz.getAssetPublishStatusEnum(reqDto.getRouterType(),String.valueOf(assetMeta.getStatus())).getCode();

            //更新缓存数据状态
            nftOrderBo.setNftId(nftOrderBo.getNftId());
            nftOrderBo.setNftPublishChainTimestamp(nftPublishChainTimestampStr);
            nftOrderBo.setNftPublishStatus(nftPublishStatusStr);
            nftOrderBo.setNftPublishTradeHash(assetMeta.getTxId());
            nftOrderBo.setUpdatedAt(LocalDateTime.now());
            dataUtils.updateNftOrderPublishInfo(reqDto.getRouterType(),reqDto.getNftOrderPayId(),nftOrderBo);

            //构造返回结果
            GalaxyNftPublishResultQueryRespDto nftPublishResultQueryRespDto = GalaxyNftPublishResultQueryRespDto.getNew();
            nftPublishResultQueryRespDto.setNftIdBegin(nftOrderBo.getNftId());
            nftPublishResultQueryRespDto.setTaskMsg(nftOrderBo.getNftId());
            nftPublishResultQueryRespDto.setTxHash(nftOrderBo.getNftPublishTradeHash());
            nftPublishResultQueryRespDto.setChainTimestamp(nftPublishChainTimestampStr);
            nftPublishResultQueryRespDto.setTaskStatus(Integer.valueOf(nftPublishStatusStr));

            return ResponseDto.success(nftPublishResultQueryRespDto);
        }else{
            return ResponseDto.failure(GalaxyErrorEnum.PUBLISH_FAIL.getCode(), GalaxyErrorEnum.PUBLISH_FAIL.getMessage());
        }
    }
}
