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

import com.fasterxml.jackson.databind.JsonNode;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.constant.AdamConst;
import com.liquidnet.service.adam.dto.AdamThirdPartParam;
import com.liquidnet.service.adam.dto.vo.AdamRealInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamThirdPartInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
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;



    private static final String PHP_API_REAL_NAME = "/IdCardCheckVerification";

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AdamUserInfoVo register(String mobile) {
        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(0);
        userInfoVo.setQrCode("lN".concat(userInfoVo.getUid()).concat(RandomStringUtils.randomAlphanumeric(5).toUpperCase()));

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

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

        s = System.currentTimeMillis();
        toMqSqls.add(SqlMapping.get("adam_user.add"));
        initUserObjs.add(new Object[]{userInfoVo.getUid(), userInfoVo.getMobile(), userInfoVo.getState(), 0, now});
        toMqSqls.add(SqlMapping.get("adam_user_info.add"));
        initUserInfoObjs.add(new Object[]{userInfoVo.getUid(), userInfoVo.getNickname(), null, userInfoVo.getQrCode()});
        log.debug("#SQL.GET耗时:{}ms", System.currentTimeMillis() - s);

        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UREGISTER.getKey(),
                SqlMapping.gets(toMqSqls, 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();
        if (StringUtils.isEmpty(uid)) {// 手机号未注册
            userInfoVo = AdamUserInfoVo.getNew();

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

            adamRdmService.setUserInfoVoByUid(userInfoVo.getUid(), userInfoVo);

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

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

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

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

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

        } else {// 手机号已注册
            // 判断已注册用户是否绑定同平台的第三方账号
            AdamThirdPartInfoVo thirdPartVo = adamRdmService.getThirdPartVoByUidPlatform(uid, param.getPlatform());
            if (null == thirdPartVo) {// 未绑定
                this.bindTpa(uid, param);
                userInfoVo = adamRdmService.getUserInfoVoByUid(uid);
            } else if (thirdPartVo.getOpenId().equals(param.getOpenId())) {
                userInfoVo = adamRdmService.getUserInfoVoByUid(uid);
            } else {
                return ResponseDto.failure(ErrorMapping.get("10010"));
            }
        }
        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",
                        thirdPartInfoVo.getUid(), 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",
                        bindThirdPartVo.getUid(), 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(),
                objsAddresses = CollectionUtil.linkedListObjectArr();

        long s = System.currentTimeMillis();
        AdamUserInfoVo userInfoVo = adamRdmService.getUserInfoVoByUid(uid);

        adamRdmService.delUidByMobile(userInfoVo.getMobile());
        List<AdamThirdPartInfoVo> thirdPartInfoVos = adamRdmService.getThirdPartVoListByUid(uid);
        if (!CollectionUtils.isEmpty(thirdPartInfoVos)) {
            thirdPartInfoVos.forEach(r -> {
                adamRdmService.delUidByPlatformOpenId(r.getPlatform(), r.getOpenId());
            });
            adamRdmService.delThirdPartVoListByUid(uid);
        }
        adamRdmService.delUserInfoVoByUid(uid);
        adamRdmService.delUserMemberVoByUid(uid);
        adamRdmService.delAddressesVoByUid(uid);
        adamRdmService.delEntersVoByUid(uid);
        log.debug("##RDS耗时:{}ms", System.currentTimeMillis() - s);

        toMqSqls.add(SqlMapping.get("adam_user.close"));
        objsUser.add(new Object[]{now, now, uid});

        /* ---------------------- 三方账号信息 */
        if (!CollectionUtils.isEmpty(thirdPartInfoVos)) {
            toMqSqls.add(SqlMapping.get("adam_third_party.close"));
            objsThirdPart.add(new Object[]{now, uid});
        }

        /* ---------------------- 用户会员信息 */
        toMqSqls.add(SqlMapping.get("adam_user_member.close"));
        objsThirdPart.add(new Object[]{now, uid});

        /* ---------------------- 收货地址信息 */
        toMqSqls.add(SqlMapping.get("adam_addresses.close"));
        objsAddresses.add(new Object[]{now, now, uid});

        /* ---------------------- 入场人信息 */
        toMqSqls.add(SqlMapping.get("adam_enters.close"));
        objsAddresses.add(new Object[]{now, now, uid});

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

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AdamRealInfoVo identity(String uid, String name, String idCard) {
        AdamRealInfoVo vo = null;
        if (!adamRdmService.isCertification(1, idCard, name)) {
            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);
                ErrorMapping.ErrorMessage errorMessage = ErrorMapping.get("10102");
                throw new LiquidnetServiceException(errorMessage.getCode(), errorMessage.getMessage());
            }
            adamRdmService.setCertification(1, idCard, name);
        }

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

        vo = AdamRealInfoVo.getNew();
        vo.setUid(uid);
        vo.setName(name);
        vo.setIdCard(idCard);
        vo.setType(realName.getType());
        vo.setState(1);

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