package com.liquidnet.service.adam.service.impl;

import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.constant.AdamConst;
import com.liquidnet.service.adam.dto.AdamThirdPartParam;
import com.liquidnet.service.adam.dto.vo.*;
import com.liquidnet.service.adam.entity.AdamRealName;
import com.liquidnet.service.adam.service.AdamRdmService;
import com.liquidnet.service.adam.service.IAdamEntersService;
import com.liquidnet.service.adam.service.IAdamRealNameService;
import com.liquidnet.service.adam.service.IAdamUserService;
import com.liquidnet.service.adam.util.NknameUtil;
import com.liquidnet.service.adam.util.QueueUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-10
 */
@Slf4j
@Service
public class AdamUserServiceImpl implements IAdamUserService {
    @Autowired
    Environment env;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    IAdamEntersService adamEntersService;
    @Autowired
    IAdamRealNameService adamRealNameService;
    @Autowired
    AdamRdmService adamRdmService;

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AdamUserInfoVo register(String mobile) {
        return this.register(mobile, 0);
    }

    @Override
    public AdamUserInfoVo register(String mobile, int isComplete) {
        return this.register(mobile, isComplete, null);
    }

    @Override
    public AdamUserInfoVo register(String mobile, int isComplete, String registSource) {
        LocalDateTime now = LocalDateTime.now();

        AdamUserInfoVo userInfoVo = AdamUserInfoVo.getNew();
        userInfoVo.setUid(IDGenerator.nextSnowId());
        userInfoVo.setMobile(mobile);
        userInfoVo.setNickname(NknameUtil.randomNkname());
        userInfoVo.setState(1);
        userInfoVo.setAvatar(AdamConst.DEF_URL_AVATAR);
        userInfoVo.setBackground(AdamConst.DEF_URL_BACKGROUND);
        userInfoVo.setCreateAt(now);
        userInfoVo.setIsComplete(isComplete);
        userInfoVo.setQrCode("lN".concat(userInfoVo.getUid()).concat(RandomStringUtils.randomAlphanumeric(5).toUpperCase()));

        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> initUserObjs = CollectionUtil.linkedListObjectArr(),
                initUserInfoObjs = CollectionUtil.linkedListObjectArr(),
                initUserMobileLocateObjs = CollectionUtil.linkedListObjectArr();

        String[] mobileLocateArr = adamRdmService.getMobileLocateArr(mobile);
        toMqSqls.add(SqlMapping.get("adam_user_mobile_locate.add"));
        String cliIpAddr = CurrentUtil.getCliIpAddr();
        String cliSource = StringUtils.isNotBlank(registSource) ? registSource : CurrentUtil.getHeaderCliSource();
        if (null != mobileLocateArr && mobileLocateArr.length > 0) {
            initUserMobileLocateObjs.add(new Object[]{
                    userInfoVo.getUid(), mobile, 1,
                    mobileLocateArr[0], mobileLocateArr[1], mobileLocateArr[2], mobileLocateArr[3], mobileLocateArr[4],
                    mobile, cliIpAddr, cliSource, now, cliIpAddr, cliSource, now, now
            });
            userInfoVo.setProvince(mobileLocateArr[0]);
            userInfoVo.setCity(mobileLocateArr[1]);
        } else {
            initUserMobileLocateObjs.add(new Object[]{
                    userInfoVo.getUid(), mobile, 1,
                    null, null, null, null, null,
                    mobile, cliIpAddr, cliSource, now, cliIpAddr, cliSource, now, now
            });
        }

        long s = System.currentTimeMillis();
        adamRdmService.setUidByMobile(mobile, userInfoVo.getUid());
        adamRdmService.setUserInfoVoByUid(userInfoVo.getUid(), userInfoVo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

        toMqSqls.add(SqlMapping.get("adam_user.add"));
        initUserObjs.add(new Object[]{userInfoVo.getUid(), userInfoVo.getMobile(), userInfoVo.getState(), userInfoVo.getIsComplete(), now});
        toMqSqls.add(SqlMapping.get("adam_user_info.add"));
        initUserInfoObjs.add(new Object[]{userInfoVo.getUid(), userInfoVo.getNickname(), userInfoVo.getAvatar(), userInfoVo.getBackground(), userInfoVo.getQrCode()});

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UREGISTER.getKey(),
                SqlMapping.gets(toMqSqls, initUserMobileLocateObjs, initUserObjs, initUserInfoObjs)
        );
        log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);
        return userInfoVo;
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseDto<AdamUserInfoVo> register(AdamThirdPartParam param) {
        LocalDateTime now = LocalDateTime.now();
        AdamUserInfoVo userInfoVo = null;

        long s = System.currentTimeMillis();
        String uid = adamRdmService.getUidByMobile(param.getMobile());
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> initUserObjs = CollectionUtil.linkedListObjectArr(),
                initUserInfoObjs = CollectionUtil.linkedListObjectArr(),
                initThirdPartObjs = CollectionUtil.linkedListObjectArr(),
                initUserMobileLocateObjs = CollectionUtil.linkedListObjectArr();
        if (StringUtils.isEmpty(uid)) {// 不存在UID，手机号未注册
            userInfoVo = AdamUserInfoVo.getNew();
            String registerUid = IDGenerator.nextSnowId();

            userInfoVo.setUid(registerUid);
            userInfoVo.setMobile(param.getMobile());
            userInfoVo.setNickname(param.getNickname());
            userInfoVo.setAvatar(param.getAvatar());
            userInfoVo.setIsComplete(0);
            userInfoVo.setState(1);
            userInfoVo.setQrCode("lN".concat(registerUid).concat(RandomStringUtils.randomAlphanumeric(5).toUpperCase()));
            userInfoVo.setCreateAt(now);

            String[] mobileLocateArr = adamRdmService.getMobileLocateArr(param.getMobile());
            toMqSqls.add(SqlMapping.get("adam_user_mobile_locate.add"));
            String cliIpAddr = CurrentUtil.getCliIpAddr();
            String headerCliSource = CurrentUtil.getHeaderCliSource();
            if (null != mobileLocateArr && mobileLocateArr.length > 0) {
                initUserMobileLocateObjs.add(new Object[]{
                        registerUid, userInfoVo.getMobile(), 1,
                        mobileLocateArr[0], mobileLocateArr[1], mobileLocateArr[2], mobileLocateArr[3], mobileLocateArr[4],
                        userInfoVo.getMobile(), cliIpAddr, headerCliSource, now, cliIpAddr, headerCliSource, now, now
                });
                userInfoVo.setProvince(mobileLocateArr[0]);
                userInfoVo.setCity(mobileLocateArr[1]);
            } else {
                initUserMobileLocateObjs.add(new Object[]{
                        registerUid, userInfoVo.getMobile(), 1,
                        null, null, null, null, null,
                        userInfoVo.getMobile(), cliIpAddr, headerCliSource, now, cliIpAddr, headerCliSource, now, now
                });
            }

            adamRdmService.setUserInfoVoByUid(registerUid, userInfoVo);

            toMqSqls.add(SqlMapping.get("adam_user.add"));
            initUserObjs.add(new Object[]{registerUid, userInfoVo.getMobile(), userInfoVo.getState(), userInfoVo.getIsComplete(), now});
            toMqSqls.add(SqlMapping.get("adam_user_info.add"));
            initUserInfoObjs.add(new Object[]{registerUid, userInfoVo.getNickname(), userInfoVo.getAvatar(), userInfoVo.getBackground(), userInfoVo.getQrCode()});

            AdamThirdPartInfoVo thirdPartInfoVo = AdamThirdPartInfoVo.getNew();
            BeanUtils.copyProperties(param, thirdPartInfoVo);
            thirdPartInfoVo.setCreatedAt(now);
            thirdPartInfoVo.setUid(registerUid);
            thirdPartInfoVo.setState(1);// 1-绑定

            toMqSqls.add(SqlMapping.get("adam_third_party.add"));
            initThirdPartObjs.add(new Object[]{registerUid, thirdPartInfoVo.getOpenId(), thirdPartInfoVo.getAvatar(), thirdPartInfoVo.getNickname(), thirdPartInfoVo.getPlatform(), thirdPartInfoVo.getState(), thirdPartInfoVo.getCreatedAt()});

            s = System.currentTimeMillis();
            adamRdmService.addThirdPartVoListByUid(registerUid, null, thirdPartInfoVo);
            adamRdmService.setUidByPlatformOpenId(param.getPlatform(), param.getOpenId(), registerUid);
            adamRdmService.setUidByMobile(param.getMobile(), registerUid);
            log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

            s = System.currentTimeMillis();
            queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UREGISTER.getKey(),
                    SqlMapping.gets(toMqSqls, initUserMobileLocateObjs, initUserObjs, initUserInfoObjs, initThirdPartObjs)
            );
            log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);

        } else {// 存在UID，手机号已注册
            // 判断已注册用户是否绑定同平台的第三方账号
            AdamThirdPartInfoVo thirdPartVo = adamRdmService.getThirdPartVoByUidPlatform(uid, param.getPlatform());
            if (null == thirdPartVo) {// 未绑定
                userInfoVo = adamRdmService.getUserInfoVoByUid(uid);
                if (null == userInfoVo || userInfoVo.getState() == 2) {
                    log.warn("Cancelled mobile:{}", param.getMobile());
                    return ResponseDto.failure(ErrorMapping.get("10024"));
                }
                this.bindTpa(uid, param);
            } else if (thirdPartVo.getOpenId().equals(param.getOpenId())) {
                userInfoVo = adamRdmService.getUserInfoVoByUid(uid);
            } else {
                // login/tpa 带手机号：仅 QQ 允许同一 uid 下 openId 变更时无感知换绑；其它平台仍走原校验
                if (!"QQ".equals(param.getPlatform())) {
                    return ResponseDto.failure(ErrorMapping.get("10010"));
                }
                String existUidForOpenId = adamRdmService.getUidByPlatformOpenId(param.getPlatform(), param.getOpenId());
                if (StringUtils.isNotEmpty(existUidForOpenId) && !existUidForOpenId.equals(uid)) {
                    return ResponseDto.failure(ErrorMapping.get("10007"));
                }
                userInfoVo = adamRdmService.getUserInfoVoByUid(uid);
                if (null == userInfoVo || userInfoVo.getState() == 2) {
                    log.warn("Cancelled mobile:{}", param.getMobile());
                    return ResponseDto.failure(ErrorMapping.get("10024"));
                }
                this.unBindTpa(uid, param.getPlatform());
                this.bindTpa(uid, param);
            }
        }
        return ResponseDto.success(userInfoVo);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void bindTpa(String uid, AdamThirdPartParam param) {
        LocalDateTime now = LocalDateTime.now();

        AdamThirdPartInfoVo thirdPartInfoVo = AdamThirdPartInfoVo.getNew();
        BeanUtils.copyProperties(param, thirdPartInfoVo);
        thirdPartInfoVo.setCreatedAt(now);
        thirdPartInfoVo.setUid(uid);
        thirdPartInfoVo.setState(1);// 1-绑定

//        long s = System.currentTimeMillis();
//        mongoTemplate.insert(thirdPartInfoVo, AdamThirdPartInfoVo.class.getSimpleName());
//        log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);

        long s = System.currentTimeMillis();
        adamRdmService.setUidByPlatformOpenId(param.getPlatform(), param.getOpenId(), uid);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

        s = System.currentTimeMillis();
//        adamRdmService.delThirdPartVoListByUid(uid);
        adamRdmService.addThirdPartVoListByUid(uid, adamRdmService.getThirdPartVoListByUid(uid), thirdPartInfoVo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UCENTER.getKey(),
                SqlMapping.get(
                        "adam_third_party.add",
                        uid, thirdPartInfoVo.getOpenId(), thirdPartInfoVo.getAvatar(), thirdPartInfoVo.getNickname(), thirdPartInfoVo.getPlatform(), thirdPartInfoVo.getState(), thirdPartInfoVo.getCreatedAt()
                )
        );
        log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void bindTpaForce(String bindUid, String unBindUid, AdamThirdPartParam param) {
        this.unBindTpaProcess(unBindUid, param.getPlatform());

        LocalDateTime now = LocalDateTime.now();

        AdamThirdPartInfoVo bindThirdPartVo = AdamThirdPartInfoVo.getNew();
        BeanUtils.copyProperties(param, bindThirdPartVo);
        bindThirdPartVo.setCreatedAt(now);
        bindThirdPartVo.setUid(bindUid);
        bindThirdPartVo.setState(1);// 1-绑定

        adamRdmService.setUidByPlatformOpenId(param.getPlatform(), param.getOpenId(), bindUid);

//        adamRdmService.delThirdPartVoListByUid(bindUid);
        adamRdmService.rmvThirdPartVoListByUid(unBindUid, adamRdmService.getThirdPartVoListByUid(unBindUid), param.getPlatform());
        adamRdmService.addThirdPartVoListByUid(bindUid, adamRdmService.getThirdPartVoListByUid(bindUid), bindThirdPartVo);

        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UCENTER.getKey(),
                SqlMapping.get(
                        "adam_third_party.add",
                        bindUid, bindThirdPartVo.getOpenId(), bindThirdPartVo.getAvatar(), bindThirdPartVo.getNickname(), bindThirdPartVo.getPlatform(), bindThirdPartVo.getState(), bindThirdPartVo.getCreatedAt()
                )
        );
    }

    /**
     * 解绑第三方账号操作
     *
     * @param uid
     * @param platform
     */
    private void unBindTpaProcess(String uid, String platform) {
        LocalDateTime now = LocalDateTime.now();
        long s = System.currentTimeMillis();
        List<AdamThirdPartInfoVo> vos = adamRdmService.getThirdPartVoListByUid(uid);
        if (!CollectionUtils.isEmpty(vos)) {
            AdamThirdPartInfoVo unBindTpaVo = adamRdmService.getThirdPartVoByUidPlatform(vos, platform);
            if (null != unBindTpaVo) {
                adamRdmService.delUidByPlatformOpenId(platform, unBindTpaVo.getOpenId());

                adamRdmService.rmvThirdPartVoListByUid(uid, vos, platform);

                s = System.currentTimeMillis();
                queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UCENTER.getKey(),
                        SqlMapping.get("adam_third_party.unbind", now, uid, platform)
                );
                log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);
            }
        }
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void unBindTpa(String uid, String platform) {
        this.unBindTpaProcess(uid, platform);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void close(String uid) {
        LocalDateTime now = LocalDateTime.now();
        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> objsUser = CollectionUtil.linkedListObjectArr(),
                objsThirdPart = CollectionUtil.linkedListObjectArr(),
                objsUserMember = CollectionUtil.linkedListObjectArr(),
                objsRealInfo = CollectionUtil.linkedListObjectArr(),
                objsAddresses = CollectionUtil.linkedListObjectArr(),
                objsEnters = CollectionUtil.linkedListObjectArr(),
                objsMobileLocate = CollectionUtil.linkedListObjectArr();

        long s = System.currentTimeMillis();
        log.debug("##RDS耗时:{}ms", System.currentTimeMillis() - s);

        /* ---------------------- 账号基础信息 */
//        AdamUserInfoVo userInfoVoByUid = adamRdmService.getUserInfoVoByUid(uid);
//        if (null != userInfoVoByUid) {
//            userInfoVoByUid.setState(2);
//            userInfoVoByUid.setUpdatedAt(now);
//            userInfoVoByUid.setClosedAt(now);
//            adamRdmService.setUserInfoVoByUid(uid, userInfoVoByUid);
//        }
        adamRdmService.delUserInfoVoByUid(uid);
        toMqSqls.add(SqlMapping.get("adam_user.close"));
        objsUser.add(new Object[]{now, now, uid});

        /* ---------------------- 三方账号信息 */
        List<AdamThirdPartInfoVo> thirdPartInfoVos = adamRdmService.getThirdPartVoListByUid(uid);
        if (!CollectionUtils.isEmpty(thirdPartInfoVos)) {
            adamRdmService.delThirdPartVoListByUid(uid);
            thirdPartInfoVos.forEach(r -> {
//                r.setState(2);
//                r.setUpdatedAt(now);

                if (null != r) {
                    adamRdmService.delUidByPlatformOpenId(r.getPlatform(), r.getOpenId());
                }
            });
//            adamRdmService.setThirdPartVoListByUid(uid, thirdPartInfoVos);
        }
        toMqSqls.add(SqlMapping.get("adam_third_party.close"));
        objsThirdPart.add(new Object[]{now, uid});

        /* ---------------------- 用户会员信息 */
//        AdamUserMemberVo userMemberVoByUid = adamRdmService.getUserMemberVoByUid(uid);
//        if (null != userMemberVoByUid) {
//            userMemberVoByUid.setState(2);
//            userMemberVoByUid.setUpdatedAt(now);
//
//            adamRdmService.setUserMemberVoByUid(uid, userMemberVoByUid);
//        }
        adamRdmService.delUserMemberVoByUid(uid);
        adamRdmService.delMemberOrderVoByUid(uid);
        toMqSqls.add(SqlMapping.get("adam_user_member.close"));
        objsUserMember.add(new Object[]{now, uid});

        /* ---------------------- 用户实名信息 */
//        AdamRealInfoVo realInfoVoByUid = adamRdmService.getRealInfoVoByUid(uid);
//        if (null != realInfoVoByUid) {
//            realInfoVoByUid.setState(2);
//
//            adamRdmService.setRealInfoVoByUid(uid, realInfoVoByUid);
//        }
        adamRdmService.delRealInfoVoByUid(uid);
        toMqSqls.add(SqlMapping.get("adam_real_name.close"));
        objsRealInfo.add(new Object[]{now, uid});

        /* ---------------------- 收货地址信息 */
//        List<AdamAddressesVo> addressesVoByUid = adamRdmService.getAddressesVoByUid(uid);
//        if (!CollectionUtils.isEmpty(addressesVoByUid)) {
//            addressesVoByUid.forEach(r -> {
//                r.setState(2);
//                r.setUpdatedAt(now);
//                r.setDeletedAt(now);
//            });
//
//            adamRdmService.setAddressesVoByUid(uid, addressesVoByUid);
//        }
        adamRdmService.delAddressesVoByUid(uid);
        toMqSqls.add(SqlMapping.get("adam_addresses.close"));
        objsAddresses.add(new Object[]{now, now, uid});

        /* ---------------------- 入场人信息 */
//        List<AdamEntersVo> entersVoByUid = adamRdmService.getEntersVoByUid(uid);
//        if (!CollectionUtils.isEmpty(entersVoByUid)) {
//            entersVoByUid.forEach(r -> {
//                r.setState(2);
//                r.setUpdatedAt(now);
//                r.setDeletedAt(now);
//            });
//
//            adamRdmService.setEntersVoByUid(uid, entersVoByUid);
//        }
        adamRdmService.delEntersVoByUid(uid);
        toMqSqls.add(SqlMapping.get("adam_enters.close"));
        objsEnters.add(new Object[]{now, now, uid});

        /* ---------------------- 用户手机地域信息 */
        toMqSqls.add(SqlMapping.get("adam_user_mobile_locate.close"));
        objsMobileLocate.add(new Object[]{now, uid});

        /* ---------------------- 用户平台券信息 */
        toMqSqls.add(SqlMapping.get("candy_user_coupon.close"));
        LinkedList<Object[]> objsCandyUserCoupon = CollectionUtil.linkedListObjectArr();
        objsCandyUserCoupon.add(new Object[]{uid});

        /* ---------------------- 用户商城券信息 */
        toMqSqls.add(SqlMapping.get("goblin_user_coupon.close"));
        LinkedList<Object[]> objsGoblinUserCoupon = CollectionUtil.linkedListObjectArr();
        objsGoblinUserCoupon.add(new Object[]{uid});

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UCENTER.getKey(),
                SqlMapping.gets(toMqSqls, objsUser, objsThirdPart, objsUserMember, objsRealInfo,
                        objsAddresses, objsEnters, objsMobileLocate, objsCandyUserCoupon, objsGoblinUserCoupon)
        );
        log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);
    }

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AdamRealInfoVo identity(String uid, String name, String idCard, String mobile) {
//        if (!adamRdmService.isCertification(1, idCard, name)) {
//            if (adamRdmService.isCertificationJunk(1, idCard, name)) {
//                ErrorMapping.ErrorMessage errorMessage = ErrorMapping.get("10102");
//                throw new LiquidnetServiceException(errorMessage.getCode(), errorMessage.getMessage());
//            }
//
//            String respStr = IdentityUtils.aliThird(name, idCard);
//            JsonNode respJNode = JsonUtils.fromJson(respStr, JsonNode.class);
//            if (null == respJNode || !"0".equals(respJNode.get("error_code").asText())) {
//                log.info("###实名认证失败[{}]", respStr);
//                adamRdmService.setCertificationJunk(1, idCard, name);
//                ErrorMapping.ErrorMessage errorMessage = ErrorMapping.get("10102");
//                throw new LiquidnetServiceException(errorMessage.getCode(), errorMessage.getMessage());
//            }
//            adamRdmService.setCertification(1, idCard, name);
//        }
//        adamRdmService.identityHandler1(uid, name, idCard);
        // 优先校验身份证是否已绑定其他账号（需要优先于三方三要素校验提示）
        if (StringUtils.isNotBlank(idCard)) {
            String boundUid = adamRdmService.getRealNameBoundUidByIdCard(idCard);
            if (StringUtils.isNotBlank(boundUid) && !boundUid.equals(uid)) {
                ErrorMapping.ErrorMessage errorMessage = ErrorMapping.get("10614");
                throw new LiquidnetServiceException(errorMessage.getCode(), errorMessage.getMessage());
            }
        }

        adamRdmService.identityHandler3(name, idCard, mobile);

        AdamRealName realName = new AdamRealName();
        realName.setRealNameId(IDGenerator.nextSnowId() + "");
        realName.setUid(uid);
        realName.setType(1);
        realName.setNode(3);
        realName.setName(name);
        realName.setIdCard(idCard);
        realName.setState(1);
        realName.setCreatedAt(LocalDateTime.now());
        adamRealNameService.add(realName);

        AdamRealInfoVo vo = AdamRealInfoVo.getNew().copy(realName);

        long s = System.currentTimeMillis();
        adamRdmService.setRealInfoVoByUid(uid, vo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
        return vo;
    }

    @Override
    public AdamRealInfoVo identityForUpsert(String uid, String name, String idCard, String mobile, boolean updateFlg) {
        adamRdmService.identityHandler3(name, idCard, mobile);

        AdamRealName realName = new AdamRealName();
        realName.setRealNameId(IDGenerator.nextSnowId() + "");
        realName.setUid(uid);
        realName.setType(1);
        realName.setNode(3);
        realName.setName(name);
        realName.setIdCard(idCard);
        realName.setState(1);
        realName.setCreatedAt(LocalDateTime.now());
        adamRealNameService.upsert(realName, updateFlg);

        AdamRealInfoVo vo = AdamRealInfoVo.getNew().copy(realName);

        long s = System.currentTimeMillis();
        adamRdmService.setRealInfoVoByUid(uid, vo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
        return vo;
    }

    @Override
    public AdamRealInfoVo identityForUpdate(String uid, String mobile, int idType, int node, String idCard, String idName) {
        AdamRealName realName = new AdamRealName();
        realName.setRealNameId(IDGenerator.nextSnowId() + "");
        realName.setUid(uid);
        realName.setType(idType);
        realName.setNode(node);
        realName.setName(idName);
        realName.setIdCard(idCard);
        realName.setState(1);
        realName.setCreatedAt(LocalDateTime.now());
        adamRealNameService.update(realName, mobile);

        AdamRealInfoVo vo = AdamRealInfoVo.getNew().copy(realName);

        long s = System.currentTimeMillis();
        adamRdmService.setRealInfoVoByUid(uid, vo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
        return vo;
    }

    @Override
    public AdamRealInfoVo verifyTwoElements(String uid, String name, String idCard) {
        try {
            adamRdmService.identityHandler1(uid, name, idCard);

            AdamRealName realName = new AdamRealName();
            realName.setRealNameId(IDGenerator.nextSnowId() + "");
            realName.setUid(uid);
            realName.setType(1);
            realName.setNode(2);
            realName.setName(name);
            realName.setIdCard(idCard);
            realName.setState(1);
            realName.setCreatedAt(LocalDateTime.now());
            adamRealNameService.add(realName);

            AdamRealInfoVo vo = AdamRealInfoVo.getNew().copy(realName);

            long s = System.currentTimeMillis();
            adamRdmService.setRealInfoVoByUid(uid, vo);
            log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);
            return vo;
        }catch (Exception e) {
            log.error("error", e);
            return null;
        }
    }
}
