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

import com.baidu.xuper.api.Account;
import com.liquidnet.common.third.xuper.dto.Xuper000CreateAccountReqDto;
import com.liquidnet.common.third.xuper.dto.Xuper000CreateAccountRespDto;
import com.liquidnet.common.third.xuper.dto.XuperResponseDto;
import com.liquidnet.common.third.xuper.exception.XupterException;
import com.liquidnet.common.third.xuper.util.XuperSdkUtil;
import com.liquidnet.common.third.zxlnft.constant.ZxlErrorEnum;
import com.liquidnet.commons.lang.util.BASE64Util;
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.constant.GalaxyEnum;
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.exception.GalaxyNftUserException;
import com.liquidnet.service.galaxy.utils.GalaxyDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

    @Autowired
    private GalaxyDataUtils dataUtils;

    @Value("${liquidnet.service.adam.url}")
    private String adamUrl;

    public ResponseDto<GalaxyUserRegisterRespDto> userRegister(GalaxyUserRegisterReqDto reqDto) {
        long startTime = System.currentTimeMillis();
        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;

        //业务失败信息
        String bizFailDesc = null;
        //系统失败信息
        String sysFailDesc = null;
        //是否实名认证成功
        boolean isRealNameAuthSuccess = true;
        //是否绑定区块链地址
        boolean isBindBlockAddressSuccess = false;
        GalaxyUserRegisterRespDto respDto = GalaxyUserRegisterRespDto.getNew();

        //用户信息
        GalaxyUserInfoBo userInfoBo = null;
        try{
            /**
             * todo 把助记词进行redis存储  key=userID  mnemonic/index/userIdentification/address
             */
            userInfoBo = dataUtils.getGalaxyUserInfo(reqDto.getRouterType(),userId);
            if(userInfoBo!=null){
                mnemonic = userInfoBo.getMnemonic();
            }else{
                Xuper000CreateAccountReqDto xuper000CreateAccountReqDto = Xuper000CreateAccountReqDto.getNew();
                // 创建区块链账户
                Xuper000CreateAccountRespDto xuper000CreateAccountRespDto = null;
                try {
                    XuperResponseDto<Xuper000CreateAccountRespDto> xuperResponseDto = xuperSdkUtil.xuper000CreateAccount(xuper000CreateAccountReqDto);
                    if(xuperResponseDto.isSuccess()){
                        xuper000CreateAccountRespDto = xuperResponseDto.getParseData(Xuper000CreateAccountRespDto.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("testXuper000CreateAccount resp : "+ JsonUtils.toJson(xuper000CreateAccountRespDto));
                mnemonic = xuper000CreateAccountRespDto.getMnemonic();
            }
            if(StringUtil.isNotEmpty(mnemonic)){
                Account account = xuperSdkUtil.getAccount(mnemonic);
                userPubKey = BASE64Util.encoded(account.getKeyPair().getJSONPublicKey());
                userPriKey = BASE64Util.encoded(account.getKeyPair().getJSONPrivateKey());
                userIdentification = account.getAddress();
                address = account.getAddress();
            }

            if(StringUtil.isNull(userInfoBo)){
                //初始化用户信息
                try{
                    //构造缓存数据
                    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(reqDto.getRouterType());
                    userInfoBo.setBlockChainAddress(address);
                    dataUtils.setGalaxyUserInfo(reqDto.getRouterType(),reqDto.getUserId(),userInfoBo);
                }catch(Exception e){
                    log.error("xuper设置用户信息异常 msg：{}",e.getMessage(),e);
                    throw new XupterException(ZxlErrorEnum.FAILURE.getCode(),"xuper设置用户信息异常");
                }
            }
        }catch (GalaxyNftUserException e) {
            bizFailDesc = e.getMessage();
            log.info(e.getMessage());
        }catch(XupterException e){
            sysFailDesc = e.getMessage();
            log.error(e.getMessage(),e);
        }catch(Exception e){
            sysFailDesc = e.getMessage();
            log.error(e.getMessage(),e);
        }

        //如果实名认证成功-更新数据库
        if(isRealNameAuthSuccess){
            if(StringUtil.isNotNull(userInfoBo)&&StringUtil.isNotEmpty(userInfoBo.getBlockChainAddress())){
                //构造返回参数
                respDto.setUserId(userId);
                respDto.setBlockChainType(GalaxyEnum.RouterTypeEnum.XUPER.getCode());
                respDto.setBlockChainAddress(userInfoBo.getBlockChainAddress());
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("开通数字账户userRegister总耗时:{} ",endTime-startTime);

        if(StringUtil.isNotEmpty(sysFailDesc)){
            return ResponseDto.failure(sysFailDesc);
        }
        if(StringUtil.isNotEmpty(bizFailDesc)){
            return ResponseDto.failure(bizFailDesc);
        }
        return ResponseDto.success(respDto);
    }
}
