package com.sonic.pigeon.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.common.utils.RedisLock;
import com.sonic.pigeon.dao.MessageStatDao;
import com.sonic.pigeon.domain.entity.MessageStat;
import com.sonic.pigeon.domain.output.MessageStatOutput;
import com.sonic.pigeon.service.MessageStatService;
import com.sonic.pigeon.utils.BeanConver;
import com.sonic.pigeon.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class MessageStatServiceImpl extends ServiceImpl<MessageStatDao, MessageStat> implements MessageStatService {

    @Autowired
    private MessageStatDao messageStatDao;
    @Autowired
    private RedisLock.RedisWrapper redisWrapper;
    @Autowired
    private RedisKeyUtils redisKeyUtils;


    @Override
    public MessageStatOutput messageStat(Long userId) {
        MessageStat messageStat = getOne(Wrappers.<MessageStat>lambdaQuery().eq(MessageStat::getUserId, userId).last("limit 1"));
        MessageStatOutput output = new MessageStatOutput();
        if (messageStat != null) {
            output = BeanConver.copeBean(messageStat, MessageStatOutput.class);
        }
        return output;
    }

    @Override
    public void updateUnread(Long userId, int unreadNum, String latestContent) {
        //redis键
        String messageStatLockKey = redisKeyUtils.messageStatLockKey(userId);
        //加锁处理 防止并发问题
        RedisLock redisLock = new RedisLock(messageStatLockKey, redisWrapper);
        redisLock.tryAcquireRun(() -> {
            //获取是否有对应用户的消息统计
            MessageStat messageStat = getOne(Wrappers.<MessageStat>lambdaQuery().eq(MessageStat::getUserId, userId).last("limit 1"));
            if (messageStat == null) {
                //没有就初始化一个
                messageStat = new MessageStat();
                messageStat.setUserId(userId);
                messageStat.setCreateTime(LocalDateTime.now());
                messageStat.setEditTime(LocalDateTime.now());
                save(messageStat);
            }
            //更新未读消息数，最近未读消息内容及时间
            messageStatDao.updateUnread(userId, unreadNum, latestContent);
            return true;
        });
    }
}