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

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) {
        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()));

        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(),
                initUserMobileLocateObjs = CollectionUtil.linkedListObjectArr();

        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()});

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

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UREGISTER.getKey(),
                SqlMapping.gets(toMqSqls, initUserObjs, initUserInfoObjs, initUserMobileLocateObjs)
        );
        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();

            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);

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

            s = System.currentTimeMillis();
            queueUtils.sendMsgByRedis(MQConst.AdamQueue.SQL_UREGISTER.getKey(),
                    SqlMapping.gets(toMqSqls, initUserObjs, initUserInfoObjs, initThirdPartObjs, initUserMobileLocateObjs)
            );
            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 {
                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(),
                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});

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

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AdamRealInfoVo identity(String uid, String name, String idCard) {
//        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);

        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);

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

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