package com.liquidnet.service.galaxy.service.impl;

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.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.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.StringUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.galaxy.constant.GalaxyConstant;
import com.liquidnet.service.galaxy.dto.GalaxyUserRegisterReqDto;
import com.liquidnet.service.galaxy.dto.GalaxyUserRegisterRespDto;
import com.liquidnet.service.galaxy.service.IGalaxyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: GalaxyUserServiceImpl
 * @Package com.liquidnet.service.galaxy.service.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2022/3/11 12:09
 */
@Slf4j
@Service
public class GalaxyUserServiceImpl implements IGalaxyUserService {
    @Autowired
    private ZxlnftSdkUtil zxlnftSdkUtil;

    @Autowired
    private ZxlWalletSdkUtil zxlWalletSdkUtil;

    @Autowired
    private ZxlnftBiz zxlnftBiz;

    @Autowired
    private ZxlnftConfig zxlnftConfig;
    @Override
    public ResponseDto<GalaxyUserRegisterRespDto> userRegister(GalaxyUserRegisterReqDto reqDto) {
        String userId = reqDto.getUserId();
        String userName = reqDto.getUserName();
        String mobile = reqDto.getMobile();
        String idCardType = reqDto.getIdCardType();
        String idCard = reqDto.getIdCard();

        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 = 0L;
        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();
        }else{
            return ResponseDto.failure(nft003Resp.getCode(),nft003Resp.getMessage());
        }

        GalaxyUserRegisterRespDto respDto = GalaxyUserRegisterRespDto.getNew();

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

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

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

            ZxlnftResponseDto<Nft014IdentityBindSubmitByTrustedRespDto> nft014Resp = zxlnftSdkUtil.nft014IdentityBindSubmitByTrusted(nft014ReqDto);

            ZxlnftResponseDto<Nft016IdentityBindQueryRespDto> nft016Resp = null;
            if(nft014Resp.isSuccess()){
                //1.2.3调用绑定状态批量查询
                Nft016IdentityBindQueryReqDto nft016ReqDto = Nft016IdentityBindQueryReqDto.getNew();
                nft016ReqDto.setAddressList(nft014Resp.getData().getAddress());
                nft016Resp = zxlnftSdkUtil.nft016IdentityBindQuery(nft016ReqDto);
            }else{
                log.info("返回结果：{}",nft014Resp.toJson());
                return ResponseDto.failure(nft014Resp.getCode(),nft014Resp.getMessage());
            }

            if(StringUtil.isNotNull(nft016Resp)&&nft016Resp.isSuccess()){
                log.info("返回结果：{}",nft016Resp.toJson());
                //构造返回参数
                respDto.setUserId(userId);
                respDto.setBlockChainType(GalaxyConstant.RouterEnum.ZXINCHAIN.getCode());
                respDto.setBlockChainAddress(nft016Resp.getData().getList().get(0).getAddress());
            }else{
                return ResponseDto.failure(nft016Resp.getMessage());
            }
        }
        return ResponseDto.success(respDto);
    }
}
