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.ZxlErrorEnum;
import com.liquidnet.common.third.zxlnft.dto.*;
import com.liquidnet.common.third.zxlnft.dto.nft.Nft016QueryRsData;
import com.liquidnet.common.third.zxlnft.dto.wallet.CreateMnemonicReq;
import com.liquidnet.common.third.zxlnft.dto.wallet.CreateMnemonicResp;
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.bo.GalaxyUserInfoBo;
import com.liquidnet.service.galaxy.dto.param.GalaxyUserRegisterReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyUserRegisterRespDto;
import com.liquidnet.service.galaxy.utils.DataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;

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

    @Autowired
    private ZxlWalletSdkUtil zxlWalletSdkUtil;

    @Autowired
    private ZxlnftBiz zxlnftBiz;

    @Autowired
    private ZxlnftConfig zxlnftConfig;

    @Autowired
    private DataUtils dataUtils;

    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 = null;
        Long index = 0L;
        String userIdentification = null;
        String address = null;
        String userPubKey = null;
        String userPriKey = null;

        GalaxyUserInfoBo userInfoBo = dataUtils.getGalaxyUserInfo(reqDto.getRouteType(),userId);
        if(userInfoBo!=null){
            mnemonic = userInfoBo.getMnemonic();
        }else{
            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 返回结果：{}",nft014Resp.toJson());
                return ResponseDto.failure(nft014Resp.getCode(),nft014Resp.getMessage());
            }

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


            //构造缓存数据
            if(userInfoBo==null){
                userInfoBo = GalaxyUserInfoBo.getNew();
                userInfoBo.setUserId(userId);
                userInfoBo.setUserName(userName);
                userInfoBo.setMobile(mobile);
                userInfoBo.setIdCardType(idCardType);
                userInfoBo.setIdCard(idCard);
                userInfoBo.setMnemonic(mnemonic);
                userInfoBo.setIndex(index.toString());
                userInfoBo.setUserIdentification(userIdentification);
                userInfoBo.setUserPubKey(userPubKey);
                userInfoBo.setUserPriKey(userPriKey);
                userInfoBo.setRouterType(GalaxyConstant.RouterTypeEnum.ZXINCHAIN.getCode());
                userInfoBo.setBlockChainAddress(address);
                dataUtils.setGalaxyUserInfo(reqDto.getRouteType(),reqDto.getUserId(),userInfoBo);
            }
        }
        return ResponseDto.success(respDto);
    }
}
