package user.common;

import com.alibaba.fastjson.JSONObject;
import common.Constant;
import config.Config;
import common.Resp;
import exception.ZXChainException;
import util.HttpUtil;
import util.Tools;
import util.ZxlSDKUtil;
import util.model.CreatePriAndPubKeyResp;

public class AddressBind {
    String userIdentification;
    String platformPubKey = Config.platformPubKey;
    String platformSignData;
    String userPubKey;
    String userSignData;

    public AddressBind() {
    }

    public AddressBind(String userIdentification) {
        this.userIdentification = userIdentification;
    }

    public String getUserIdentification() {
        return userIdentification;
    }

    public void setUserIdentification(String userIdentification) {
        this.userIdentification = userIdentification;
    }

    public String getPlatformPubKey() {
        return platformPubKey;
    }

    public void setPlatformPubKey(String platformPubKey) {
        this.platformPubKey = platformPubKey;
    }

    public String getPlatformSignData() {
        return platformSignData;
    }

    public void setPlatformSignData(String platformSignData) {
        this.platformSignData = platformSignData;
    }

    public String getUserPubKey() {
        return userPubKey;
    }

    public void setUserPubKey(String userPubKey) {
        this.userPubKey = userPubKey;
    }

    public String getUserSignData() {
        return userSignData;
    }

    public void setUserSignData(String userSignData) {
        this.userSignData = userSignData;
    }

    public String addressBind() throws Exception {
        if (this.userIdentification.length() != 64) {
            throw new RuntimeException("userIdentification错误: "+ this.userIdentification);
        }

        //todo 持久化助记词
        String mnemonic = ZxlSDKUtil.createMnemonic();
        //todo 持久化公私钥
        CreatePriAndPubKeyResp keyPair = ZxlSDKUtil.deriveKeyPair(mnemonic, 0);

        this.setUserPubKey(keyPair.getPubKey());
        //用户签名
        String userSignData = ZxlSDKUtil.signByPriKey(keyPair.getPriKey(), this.userIdentification);
        this.setUserSignData(userSignData);
        //平台签名
        String platformSignData = ZxlSDKUtil.signByPriKey(Config.platformPrivateKey, userSignData);
        this.setPlatformSignData(platformSignData);

        JSONObject param = Tools.getJson(this);

        //调用接口
        Resp resp = HttpUtil.apiPostJsonX("https://open.zxchain.qq.com/api/v1/user/identity/bind/submit_by_trusted_platform", param, ZxlSDKUtil.generateApiSign());
        if (resp.getRetCode() != Constant.ZXL_OK) {
            throw new ZXChainException(resp.getRetMsg());
        }

        return resp.getData(AddressBindResp.class).address;
    }
}
