package com.sonic.bear.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.bear.dao.UserDao;
import com.sonic.bear.domain.entity.User;
import com.sonic.bear.domain.entity.UserInfoBo;
import com.sonic.bear.domain.entity.UserThird;
import com.sonic.bear.enums.ThirdTypeEnum;
import com.sonic.bear.enums.ToastResultCode;
import com.sonic.bear.service.CommonMessageService;
import com.sonic.bear.service.CommonSendMqService;
import com.sonic.bear.service.UserService;
import com.sonic.bear.service.UserThirdService;
import com.sonic.bear.utils.BeanConver;
import com.sonic.bear.utils.IdCardGenerator;
import com.sonic.lion.lib.client.PayClient;
import com.sonic.pigeon.lib.client.ImUserClient;
import com.sonic.pigeon.lib.enums.ImUserTypeEnum;
import com.sonic.pigeon.lib.input.CreateImUserInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author code
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserThirdService userThirdService;
    @Autowired
    private IdCardGenerator idCardGenerator;

    /**
     * 构造ID生成器的对象
     */
    private final Sequence sequence = new Sequence();

    @Autowired
    private CommonSendMqService commonSendMqService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long thirdLoginOrRegister(ThirdTypeEnum thirdType, String openId, String email, String nickname) {
        UserThird userThird = userThirdService.queryByOpenId(thirdType, openId);
        if(userThird == null) {
            //直接走注册的流程，并快速返回
            Long userId = sequence.nextId();
            registerThirdUser(userId, thirdType, openId, email, nickname);
            //用户注册后发送MQ
            commonSendMqService.userCreatedSendMq(userId);
            return userId;
        }
        User user = getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getIsDelete, false)
                .eq(User::getUserId, userThird.getUserId()));
        //判断用户是否存在
        ToastResultCode.USER_NOT_EXIST.check(user == null);
        //判断账号状态
        ToastResultCode.USER_FROZEN.check(user.getAccountStatus() != 0);
        return user.getUserId();
    }

    /**
     * 三方用户注册
     * @param userId
     * @param thirdType
     * @param openId
     * @param email
     * @param nickname
     */
    private UserThird registerThirdUser(Long userId, ThirdTypeEnum thirdType, String openId, String email, String nickname) {
        User user = new User();
        user.setUserId(userId);
        //idCard的生成逻辑
        user.setIdCard(idCardGenerator.generateIdCard());
        user.setAccountStatus(0);
        user.setSex(0);
        user.setHeadImage("https://hhb.crushlevel.ai/static/img/dfhig.jpg");
        user.setLastAccessTime(LocalDateTime.now());
        user.setIsDelete(false);
        user.setCreateTime(LocalDateTime.now());
        user.setEditId(userId);
        user.setEditTime(LocalDateTime.now());
        userDao.insert(user);
        UserThird userThird = new UserThird();
        userThird.setUserId(userId);
        userThird.setThirdType(thirdType.name());
        userThird.setOpenId(openId);
        userThird.setNickname(nickname);
        userThird.setEmail(email);
        userThird.setIsDelete(false);
        userThird.setCreateTime(LocalDateTime.now());
        userThird.setEditId(userId);
        userThird.setEditTime(LocalDateTime.now());
        userThirdService.save(userThird);
        log.info("===> 用户{}注册成功", userId);
        return userThird;
    }

    @Override
    public UserInfoBo queryUserInfo(Long userId) {
        User user = getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getIsDelete, false)
                .eq(User::getUserId, userId));
        //判断用户是否存在
        ToastResultCode.USER_NOT_EXIST.check(user == null);
        //判断账号状态
        ToastResultCode.USER_FROZEN.check(user.getAccountStatus() != 0);
        return BeanConver.copeBean(user, UserInfoBo.class);
    }
}
