package com.sonic.bear.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.bear.dao.UserNicknamePoolDao;
import com.sonic.bear.domain.entity.UserNicknamePool;
import com.sonic.bear.domain.output.NicknameOutput;
import com.sonic.bear.lib.enums.OptTypeEnum;
import com.sonic.bear.service.UserNicknamePoolService;
import com.sonic.bear.utils.BeanConver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

/**
 * @author code
 */
@Slf4j
@Service
public class UserNicknamePoolServiceImpl extends ServiceImpl<UserNicknamePoolDao, UserNicknamePool> implements UserNicknamePoolService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncPool(Long userId, Integer userType, String nickname, String optType) {
        if(StringUtils.isEmpty(nickname)) {
            return;
        }
        if(OptTypeEnum.ADD.name().equals(optType)) {
            save(UserNicknamePool.builder().userId(userId).userType(userType).nickname(nickname).createTime(LocalDateTime.now()).build());
        } else if (OptTypeEnum.DEL.name().equals(optType)) {
            //删除历史数据
            remove(Wrappers.<UserNicknamePool>lambdaQuery().eq(UserNicknamePool::getUserId, userId).eq(UserNicknamePool::getUserType, userType));
        } else if (OptTypeEnum.UPD.name().equals(optType)) {
            //先删除历史数据
            remove(Wrappers.<UserNicknamePool>lambdaQuery().eq(UserNicknamePool::getUserId, userId).eq(UserNicknamePool::getUserType, userType));
            //再写入数据
            save(UserNicknamePool.builder().userId(userId).userType(userType).nickname(nickname).createTime(LocalDateTime.now()).build());
        }
    }

    @Override
    public List<NicknameOutput> batchGetNickname(List<Long> userIdList) {
        List<UserNicknamePool> list = list(Wrappers.<UserNicknamePool>lambdaQuery()
                .select(UserNicknamePool::getUserId, UserNicknamePool::getNickname)
                .in(UserNicknamePool::getUserId, userIdList));
        return BeanConver.copeList(list, NicknameOutput.class);
    }

    @Override
    public boolean existCheck(Long userId, String nickname) {
        int count = count(Wrappers.<UserNicknamePool>lambdaQuery().eq(UserNicknamePool::getNickname, nickname).ne(userId != null, UserNicknamePool::getUserId, userId));
        return count > 0;
    }

}
