package org.linlinjava.jz.db.service;

import com.google.common.collect.Lists;
import org.linlinjava.jz.db.dao.SysUserOnlineMapper;
import org.linlinjava.jz.db.domain.SysUserOnline;
import org.linlinjava.jz.db.domain.SysUserOnlineExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 系统用户在线状态表
 * 前端页面每30秒提交一次 如果last_online_time超过30秒 表示掉线
 */
@Service
public class JzSysUserOnlineService {

    @Resource
    private SysUserOnlineMapper onlineMapper;

    public void add(SysUserOnline online) {
        online.setLastOnlineTime(LocalDateTime.now());
        onlineMapper.insertSelective(online);
    }

    public void update(SysUserOnline online) {
        online.setLastOnlineTime(LocalDateTime.now());

        SysUserOnlineExample example = new SysUserOnlineExample();
        example.or().andUserIdEqualTo(online.getUserId());
        int value = onlineMapper.updateByExampleSelective(online, example);
        if (value == 0)//没有查询到需要更新数据
            add(online);
    }

    public SysUserOnline findById(Integer online) {
        SysUserOnlineExample example = new SysUserOnlineExample();
        example.or().andUserIdEqualTo(online);
        return onlineMapper.selectOneByExample(example);
    }

    /**
     * 获取所有在线客服
     * 前端每30秒报告一次状态 这个地方给个冗余 只要最后更新状态的时间小于等于1分钟 均算在线状态
     *
     * @return
     */
    public List<Integer> queryAllOnline() {
        SysUserOnlineExample example = new SysUserOnlineExample();
        example.or().andLastOnlineTimeGreaterThan(LocalDateTime.now().plusMinutes(-1));

        List<SysUserOnline> onlines = onlineMapper.selectByExample(example);
        List<Integer> lists = Lists.newArrayList();

        for (SysUserOnline online : onlines)
            lists.add(online.getUserId());

        return lists;
    }
}
