package com.qiaoba.module.monitor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiaoba.api.monitor.entity.SysLoginLog;
import com.qiaoba.api.monitor.entity.param.LoginLogParam;
import com.qiaoba.common.database.entity.PageQuery;
import com.qiaoba.common.database.entity.TableDataInfo;
import com.qiaoba.module.monitor.mapper.SysLoginLogMapper;
import com.qiaoba.module.monitor.service.SysLoginLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 登录日志 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/19 14:39
 */
@Service
@RequiredArgsConstructor
public class SysLoginLogServiceImpl implements SysLoginLogService {

    private final SysLoginLogMapper sysLoginLogMapper;

    @Override
    public Integer insert(SysLoginLog sysLoginLog) {
        return sysLoginLogMapper.insert(sysLoginLog);
    }

    @Override
    public TableDataInfo<SysLoginLog> selectPageList(LoginLogParam param, PageQuery pageQuery) {
        return TableDataInfo.build(sysLoginLogMapper.selectPage(pageQuery.build(), param2Wrapper(param)));
    }

    @Override
    public void cleanLoginLog() {
        sysLoginLogMapper.delete(new QueryWrapper<>());
    }

    @Override
    public List<SysLoginLog> selectList(LoginLogParam param) {
        return sysLoginLogMapper.selectList(param2Wrapper(param));
    }

    private QueryWrapper<SysLoginLog> param2Wrapper(LoginLogParam param) {
        QueryWrapper<SysLoginLog> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .orderByDesc(SysLoginLog::getLoginTime)
                .ge(Objects.nonNull(param.getBeginTime()), SysLoginLog::getLoginTime, param.getBeginTime())
                .le(Objects.nonNull(param.getEndTime()), SysLoginLog::getLoginTime, param.getEndTime())
                .like(StrUtil.isNotBlank(param.getNickname()), SysLoginLog::getNickname, param.getNickname())
                .like(StrUtil.isNotBlank(param.getUsername()), SysLoginLog::getUsername, param.getUsername())
                .like(StrUtil.isNotBlank(param.getIp()), SysLoginLog::getIp, param.getIp());

        return wrapper;
    }
}
