package com.ruoyi.xq.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.xq.domain.User;
import com.ruoyi.xq.domain.UserVisitor;
import com.ruoyi.xq.dto.app.uservisitor.UserVisitorQuery;
import com.ruoyi.xq.dto.app.uservisitor.vo.UserVisitorListVo;
import com.ruoyi.xq.lock.LockKey;
import com.ruoyi.xq.mapper.UserVisitorMapper;
import com.ruoyi.xq.service.UserService;
import com.ruoyi.xq.service.UserVisitorService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户来访记录Service业务层处理
 *
 * @author 77
 * @date 2024-03-18
 */
@Service
public class UserVisitorServiceImpl extends ServiceImpl<UserVisitorMapper,UserVisitor> implements UserVisitorService {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private UserService userService;
    @Override
    public void visitor(Long userId, Long tarUserId) {
        User user = userService.getById(userId);
        User tarUser = userService.getById(tarUserId);
        if(user == null || tarUser == null){
            return;
        }
        UserVisitor one = this.getOne(Wrappers.lambdaQuery(UserVisitor.class).eq(UserVisitor::getUserId, userId)
                .eq(UserVisitor::getTarId, tarUserId).last("limit 1"));
        if(one != null){
            baseMapper.incsVisitorCount(one.getId());
            return;
        }
        RLock lock = redissonClient.getLock(LockKey.getUserVisitorAddLockKey(userId, tarUserId));
        try {
            lock.lock();
            one = this.getOne(Wrappers.lambdaQuery(UserVisitor.class).eq(UserVisitor::getUserId, userId)
                    .eq(UserVisitor::getTarId, tarUserId).last("limit 1"));
            if(one != null){
                return;
            }
            UserVisitor userVisitor = new UserVisitor();
            userVisitor.setUserId(user.getId());
            userVisitor.setUsercode(user.getUsercode());
            userVisitor.setTarId(tarUser.getId());
            userVisitor.setTarUsercode(tarUser.getUsercode());
            userVisitor.setVisitorNum(1);
            this.save(userVisitor);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public Page<UserVisitorListVo> pageApp(PageQuery pageQuery, UserVisitorQuery query) {
        return baseMapper.pageApp(pageQuery.build(), query);
    }

}
