package com.ruoyi.cai.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.cai.domain.UserVisitor;
import com.ruoyi.cai.dto.app.query.StarOrVisitorReq;
import com.ruoyi.cai.dto.app.query.VisitorQuery;
import com.ruoyi.cai.dto.app.vo.user.UserStarOrVisitorList;
import com.ruoyi.cai.mapper.UserVisitorMapper;
import com.ruoyi.cai.service.UserCountService;
import com.ruoyi.cai.service.UserVisitorService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户来访记录Service业务层处理
 *
 * @author 77
 * @date 2023-12-24
 */
@RequiredArgsConstructor
@Service
public class UserVisitorServiceImpl extends ServiceImpl<UserVisitorMapper, UserVisitor> implements UserVisitorService {
    @Autowired
    private UserCountService userCountService;
    @Override
    public boolean visitor(StarOrVisitorReq starOrVisitorReq) {
        Long fromUserId = LoginHelper.getUserId();
        UserVisitor userVisitor = this.getOne(Wrappers.lambdaQuery(UserVisitor.class)
                .eq(UserVisitor::getVisitorId, fromUserId)
                .eq(UserVisitor::getUserId, starOrVisitorReq.getToUserId())
                .last("limit 1"));
        if(userVisitor == null){
            userVisitor = new UserVisitor();
            userVisitor.setVisitorId(fromUserId);
            userVisitor.setUserId(starOrVisitorReq.getToUserId());
        }
        userVisitor.setCreateTime(LocalDateTime.now());
        this.saveOrUpdate(userVisitor);
        userCountService.visitor(fromUserId, starOrVisitorReq.getToUserId());
        return true;
    }

    @Override
    public Page<UserStarOrVisitorList> pageApp(PageQuery pageQuery, VisitorQuery query) {
        query.setUserId(LoginHelper.getUserId());
        return baseMapper.pageApp(pageQuery.build(),query);
    }
}
