package com.liquidnet.service.zxlnft;

import com.liquidnet.common.third.zxlnft.biz.ZxlnftBiz;
import com.liquidnet.common.third.zxlnft.config.ZxlnftConfig;
import com.liquidnet.common.third.zxlnft.constant.ZxlErrorEnum;
import com.liquidnet.common.third.zxlnft.constant.ZxlnftEnum;
import com.liquidnet.common.third.zxlnft.dto.*;
import com.liquidnet.common.third.zxlnft.dto.wallet.DeriveKeyPairReq;
import com.liquidnet.common.third.zxlnft.dto.wallet.DeriveKeyPairResp;
import com.liquidnet.common.third.zxlnft.dto.wallet.UploadToCosReq;
import com.liquidnet.common.third.zxlnft.dto.wallet.UploadToCosResp;
import com.liquidnet.common.third.zxlnft.exception.ZxlNftException;
import com.liquidnet.common.third.zxlnft.util.ZxlWalletSdkUtil;
import com.liquidnet.common.third.zxlnft.util.ZxlnftSdkUtil;
import com.liquidnet.commons.lang.util.BASE64Util;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.UnsupportedEncodingException;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: TestZxlnftService
 * @Package com.liquidnet.service.zxlnft
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2022/3/3 16:55
 */
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TestZxlnftService {
    @Autowired
    private ZxlnftSdkUtil zxlnftSdkUtil;

    @Autowired
    private ZxlWalletSdkUtil zxlWalletSdkUtil;

    @Autowired
    private ZxlnftBiz zxlnftBiz;

    @Autowired
    private ZxlnftConfig zxlnftConfig;
    /**
     * 1、NFT平台在至信链的注册、审核
     */
    @Test
    public void platformRegister(){

//        1.1.2调用下发查询用户信息验证码接口
//        1.1.3调用查询用户信息接口
//        1.1.4调用下发用户信息查询验证码接口
//        1.1.5调用NFT平台自身地址绑定接口
//        1.1.6调用绑定状态批量查询接口

    }

    /**
     * 2、自然人用户通过NFT平台注册绑定
     */
    @Test
    public void personRegisterBind(){
        String userId = "310508344264376327445470";
        String userName = "安家宾";
        String mobile = "13811314082";
        String idCardType = ZxlnftEnum.CardTypeEnum.ID_CARD.getCode();
        String idCard = "142323198302062216";

//        String userName = "周焕";
//        String mobile = "18548596019";
//        String idCardType = ZxlnftEnum.CardTypeEnum.ID_CARD.getCode();
//        String idCard = "150422199805206019";

        String mnemonic = "stuff name goat health siren dumb gorilla antique board tenant buffalo present"; //安家宾
//        String mnemonic = "economy cost balance weapon flight also nut biology very sun slight about"; //周焕
        Long index = 1L;
        String userIdentification = null;
        String address = null;
        String userPubKey = null;
        String userPriKey = null;

//        try{
//            //生成助记词
//            CreateMnemonicReq req = CreateMnemonicReq.getNew();
//            CreateMnemonicResp createMnemonicResp = zxlWalletSdkUtil.createMnemonic(req);
//            mnemonic = createMnemonicResp.getMnemonic();
//        }catch(Exception e){
//            throw new ZxlNftException(ZxlErrorEnum.FAILURE.getCode(),"生成助记词失败！");
//        }

        /**
         * todo 把助记词进行redis存储  key=userID  mnemonic/index/userIdentification/address
         */

        if(StringUtil.isNotEmpty(mnemonic)){
            //生成公私钥
            DeriveKeyPairReq deriveKeyPairReq = DeriveKeyPairReq.getNew();
            deriveKeyPairReq.setMnemonic(mnemonic);
//        deriveKeyPairReq.setMnemonic(createMnemonicResp.getMnemonic());
            deriveKeyPairReq.setIndex(index);
            try{
                DeriveKeyPairResp deriveKeyPairResp = zxlWalletSdkUtil.deriveKeyPair(deriveKeyPairReq);
                if(!deriveKeyPairResp.getErr().equals("")) throw new Exception("生成公私钥失败！");
                userPubKey = BASE64Util.encoded(deriveKeyPairResp.getPubKey());
                userPriKey = BASE64Util.encoded(deriveKeyPairResp.getPriKey());
            }catch(Exception e){
                throw new ZxlNftException(ZxlErrorEnum.FAILURE.getCode(),e.getMessage());
            }
        }

        //1.2.1调用自然人注册实名(使用NFT平台签名)接口
        Nft003RegisterPersonPlatformReqDto nft003ReqDto = Nft003RegisterPersonPlatformReqDto.getNew();
        nft003ReqDto.setPersonName(userName);
//        reqDto.setEmail("");
        nft003ReqDto.setMobile(mobile);
        nft003ReqDto.setIdCard(idCard);

        nft003ReqDto.setCardType(Integer.valueOf(idCardType));
        ZxlnftResponseDto<Nft003RegisterPersonPlatformRespDto> nft003Resp = zxlnftSdkUtil.nft003RegisterPersonPlatform(nft003ReqDto);

        if(nft003Resp.isSuccess()){
            userIdentification = nft003Resp.getData().getUserIdentification();
        }

        //
        if(StringUtil.isNotEmpty(userPubKey)&&StringUtil.isNotEmpty(userPriKey)&&StringUtil.isNotEmpty(userIdentification)){
            //1.2.2调用授信平台NFT地址绑定接口
            Nft014IdentityBindSubmitByTrustedReqDto nft004ReqDto = Nft014IdentityBindSubmitByTrustedReqDto.getNew();

            try {
                nft004ReqDto.setUserPubKey(BASE64Util.decode(userPubKey));
                nft004ReqDto.setUserIdentification(nft003Resp.getData().getUserIdentification());

                String signature = zxlnftBiz.createSign(BASE64Util.decode(userPriKey),nft004ReqDto.getUserIdentification());
                nft004ReqDto.setUserSignData(signature);
            } catch (UnsupportedEncodingException e) {
                log.error("公私钥解密错误！");
            }

            ZxlnftResponseDto<Nft014IdentityBindSubmitByTrustedRespDto> nft004Resp = zxlnftSdkUtil.nft014IdentityBindSubmitByTrusted(nft004ReqDto);

            if(nft004Resp.isSuccess()){
                //1.2.3调用绑定状态批量查询
                Nft016IdentityBindQueryReqDto nft016ReqDto = Nft016IdentityBindQueryReqDto.getNew();
                nft016ReqDto.setAddressList(nft004Resp.getData().getAddress());
                ZxlnftResponseDto<Nft016IdentityBindQueryRespDto> nft016Resp = zxlnftSdkUtil.nft016IdentityBindQuery(nft016ReqDto);

                if(nft016Resp.isSuccess()){
                    log.info("返回结果：{}",nft016Resp.toJson());
                }
            }else{
                log.info("返回结果：{}",nft004Resp.toJson());
            }
        }
    }

    /**
     * 3、素材上传操作
     */
    @Test
    public void nftUpload(){
        String imageUrl = "https://zhixinliantest-1302317679.cos.ap-guangzhou.myqcloud.com/nft/4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef/ZXLNFTIMAGE202202241512003609141721.jpg";
        String seriesName = "NOW_ZXL_NFT_PIC_skuId001"; //系列名字 skuId
//        String filePath = "/Users/anjiabin/Downloads/zxl_image_test_002.jpeg";
//        String filePath = "/Users/anjiabin/Downloads/zxl_image_series_test_001.jpeg";
        String filePath = "/Users/anjiabin/Downloads/zxl_image_test_001.jpg";
        String fileName = DateUtil.getNowTime(DateUtil.DATE_SMALL_STR)+"/"+ IDGenerator.getZxlNftImageCosCode() +".jpg";

        //完整全路径 https://zhixinliantest-1302317679.cos.ap-guangzhou.myqcloud.com/nft/4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef/NOW_ZXL_NFT_PIC001_test_skuId001/2022-03-04/ZXLNFTIMAGE202203041707466694345291.jpg
        String fullFilePath = null; //需要保存,返回给调用者
        String seriesId = null;

//        1.4.1调用图片内容检测接口
        Nft008QueryImageModerationReqDto nft008ReqDto = Nft008QueryImageModerationReqDto.getNew();
        nft008ReqDto.setImageUrl(imageUrl);
        ZxlnftResponseDto<Nft008QueryImageModerationRespDto> nft008RespDto = zxlnftSdkUtil.nft008QueryImageModeration(nft008ReqDto);
        if(!nft008RespDto.getData().getSuggestion().equals(ZxlnftEnum.SuggestionEnum.PASS.getCode())){
           throw new ZxlNftException(ZxlErrorEnum.IMAGE_CHECK_ERROR.getCode(),ZxlErrorEnum.IMAGE_CHECK_ERROR.getMsg());
        }

//        1.4.2调用生成素材上传临时密钥接口
        Nft022UploadSecretReqDto nft022ReqDto = Nft022UploadSecretReqDto.getNew();
        nft022ReqDto.setSeriesName(seriesName);
        nft022ReqDto.setTimestamp(DateUtil.getNowSeconds().toString());
        nft022ReqDto.setUserPubKey(zxlnftConfig.getNftPlatformPubKey());

        //系列为空
        String userData = nft022ReqDto.getTimestamp();
        //系列不为空
        if(StringUtil.isNotEmpty(nft022ReqDto.getSeriesName())){
            userData = nft022ReqDto.getTimestamp() + "_" + nft022ReqDto.getSeriesName();
        }

        nft022ReqDto.setUserSignedData(zxlnftBiz.createSign(zxlnftConfig.getNftPlatformPriKey(),userData));

        ZxlnftResponseDto<Nft022UploadSecretRespDto> nft022RespDto = zxlnftSdkUtil.nft022UploadSecret(nft022ReqDto);

        if(!nft022RespDto.isSuccess()){
            throw new ZxlNftException(ZxlErrorEnum.UPLOAD_TEMP_SECRET.getCode(),ZxlErrorEnum.UPLOAD_TEMP_SECRET.getMsg());
        }
//        1.4.3调用sdk接口-上传cos接口
        if(nft022RespDto.isSuccess()){
            fullFilePath = nft022RespDto.getData().getUploadAddress().concat(fileName);
            UploadToCosReq req = UploadToCosReq.getNew();
            req.setCosPath(fullFilePath);
            req.setTempSecretId(nft022RespDto.getData().getTempSecretId());
            req.setTempSecretKey(nft022RespDto.getData().getTempSecretKey());
            req.setSessionToken(nft022RespDto.getData().getSessionToken());
            req.setFilePath(filePath);
            UploadToCosResp uploadToCosResp = zxlWalletSdkUtil.uploadToCos(req);
        }

        log.info("完整的素材访问fullFilePath url：{}",fullFilePath);

//        1.4.4调用查询素材地址接口 -- 非必需
//        Nft021UploadUrlReqDto nft021ReqDto = Nft021UploadUrlReqDto.getNew();
//        nft021ReqDto.setSeriesName(seriesName);
//        nft021ReqDto.setPlatformIdentification(zxlnftConfig.getPlatformIdentification());
//        //如果上传人就是平台管理员，以下需要注释掉，因为会导致返回的地址多了一级目录
////        nft021ReqDto.setUserIdentification(zxlnftConfig.getPlatformIdentification());
//        ZxlnftResponseDto<Nft021UploadUrlRespDto> resp = zxlnftSdkUtil.nft021UploadUrl(nft021ReqDto);

        /**
         * 进行系列声明
         */
        Nft030SeriesClaimReqDto reqDto = Nft030SeriesClaimReqDto.getNew();
        reqDto.setPubKey(zxlnftConfig.getNftPlatformPubKey());
        reqDto.setSeriesName(seriesName);
        //无限制系列 设置为0
        reqDto.setTotalCount(0l);
        reqDto.setOperateId(IDGenerator.get32UUID());
        //系列封面
        reqDto.setCoverUrl("https://zhixinliantest-1302317679.cos.ap-guangzhou.myqcloud.com/nft/4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef/ZXLNFTIMAGE202202241512003609141721.jpg");
        reqDto.setDesc("系列描述信息不超过500字符");
        reqDto.setMaxPublishCount(0);
        reqDto.setSeriesBeginFromZero(false);
        ZxlnftResponseDto<Nft030SeriesClaimRespDto> nft30RespDto = zxlnftSdkUtil.nft030SeriesClaim(reqDto);

        //{"taskId":"49d1cccc-e62c-40bc-923c-bfac31325351_nft-series-claim_1"}
        if(nft30RespDto.isSuccess()){
            //系列声明结果查询
            Nft031SeriesClaimResultReqDto nft031ReqDto = Nft031SeriesClaimResultReqDto.getNew();
            //第零个系列 无限制系列
            nft031ReqDto.setTaskId(nft30RespDto.getData().getTaskId());
            ZxlnftResponseDto<Nft031SeriesClaimResultRespDto> nft031RespDto = zxlnftSdkUtil.nft031SeriesClaimResult(nft031ReqDto);
            if(nft031RespDto.isSuccess()){
                log.info("系列声明结果查询 ：{}",nft031RespDto.toJson());
                if(nft031RespDto.getData().getTaskStatus().equals(ZxlnftEnum.TaskStatusEnum.TASK_SECCESS.getCode())){
                    seriesId = nft031RespDto.getData().getSeriesId();
                }
//                {
//                    "code": "0",
//                        "data": {
//                              "taskStatus": 7,
//                            "taskMsg": "{\"TraceId\":\"046ed85b-b690-4137-92ce-838d93f693e5\",\"ErrMsg\":\"\",\"Cost\":\"400ms\"}",
//                            "seriesId": "4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef_d55d3746e1a2720345e620c5fbf68515b1d8db284abbda84f202b79260b55a6d",
//                            "txHash": "f0f3bb9a49f20c0c90b7e58d71f9eeb283e163543a05e4d8d32d0b929835651f",
//                            "chainTimestamp": 1646386972
//                      },
//                    "success": true
//                }
            }

            log.info("系列声明结果查询 seriesId :{}",seriesId);
        }
    }

    @Test
    public void SeriesClaimResultQuery(){
        String taskId = "49d1cccc-e62c-40bc-923c-bfac31325351_nft-series-claim_1";

        Nft031SeriesClaimResultReqDto reqDto = Nft031SeriesClaimResultReqDto.getNew();
        //第零个系列 无限制系列
        reqDto.setTaskId(taskId);
        ZxlnftResponseDto<Nft031SeriesClaimResultRespDto> resp = zxlnftSdkUtil.nft031SeriesClaimResult(reqDto);
        System.out.println(resp.toJson());
    }

    /**
     * 4、发行NFT
     */
    @Test
    public void nftPublish(){
        String author = "正在现场创作者001";
        String name = "上海草莓音乐节2022";
        String url = "https://zhixinliantest-1302317679.cos.ap-guangzhou.myqcloud.com/nft/4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef/ZXLNFTIMAGE202202241512003609141721.jpg";
        String displayUrl = "https://zhixinliantest-1302317679.cos.ap-guangzhou.myqcloud.com/nft/4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef/ZXLNFTIMAGE202202241512003609141721.jpg";
        String desc = "NFT描述信息";
        String flag = "文创";
        //发行个数
        Long publishCount = 1L;
        //开始索引
        Integer seriesBeginIndex = 1;
        Long sellCount = 1000L; //积分
        //无限制系列
        String seriesId = "4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef_8a827e181b695fb8d9b081d3855d2895ced1d003ee186622a005cec37ea77e59";
        //系列001
        //String seriesId = "4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef_ca49b5ebadd5f73ab057fe869bf897cbcc0f31e0b89db71cc3ec78bca2d16ed6";
        //系列002
        //String seriesId = "4e40d5f6f65aa8ec9bc33ab424e0167e68783bbe95d4d265086314d749808eef_31ff9f7d4c33c98518e095fec6cecdab8d337751602cf6e651eb7d131cff5b61";

        //3.1.2调用NFT发行接口
        /**
         * 发行无限制系列
         */
        Nft034PublishReqDto reqDto = Nft034PublishReqDto.getNew();
        reqDto.setAuthor(author);
        reqDto.setName(name);
        reqDto.setUrl(url);
        reqDto.setDisplayUrl(displayUrl);
        reqDto.setDesc(desc);
        reqDto.setFlag(flag);
        reqDto.setPublishCount(publishCount);
        //无限制零系列
        reqDto.setSeriesId(seriesId);
        reqDto.setSeriesBeginIndex(seriesBeginIndex);
        reqDto.setSellStatus(Integer.parseInt(ZxlnftEnum.SellStatusEnum.CAN_SELL.getCode()));
        reqDto.setSellCount(sellCount);
        reqDto.setOperateId(IDGenerator.get32UUID());
        reqDto.setMetaData("");

        ZxlnftResponseDto<Nft034PublishRespDto> nft034RespDto = zxlnftSdkUtil.nft034Publish(reqDto);
//        3.1.3调用NFT查询接口
//        3.1.4查询 NFT发行结果
    }

    /**
     * 5、购买NFT
     */
    @Test
    public void nftBuy(){
//        3.2.1调用积分申请接口
//        3.2.2调用购买NFT接口
//        3.2.3调用NFT查询接口
//        3.2.4查询NFT购买支付结果
    }

    /**
     * 6、查询NFT相关信息
     */
    @Test
    public void nftQuery(){

    }

}
