package org.xyzh.system.service.log.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xyzh.api.system.log.LoginLogService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.dto.system.TbSysLoginLog;
import org.xyzh.common.vo.UserDeptRoleVO;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xyzh.system.mapper.SysLoginLogMapper;
import org.xyzh.system.utils.LoginUtil;

@Service
public class LoginLogServiceImpl implements LoginLogService {

    private static final Logger logger = LoggerFactory.getLogger(LoginLogServiceImpl.class);

    @Autowired
    private SysLoginLogMapper sysLoginLogMapper;

    @Override
    public ResultDomain<TbSysLoginLog> insertLoginLog(TbSysLoginLog loginLog) {
        ResultDomain<TbSysLoginLog> result = new ResultDomain<>();
        int rows = sysLoginLogMapper.insertLoginLog(loginLog);
        if (rows > 0) {
            result.success("插入登录日志成功", loginLog);
        } else {
            result.fail( "插入登录日志失败");
        }
        logger.info("insertLoginLog: {}", loginLog);
        return result;
    }

    @Override
    public ResultDomain<TbSysLoginLog> selectLoginLogList(TbSysLoginLog loginLog) {
        ResultDomain<TbSysLoginLog> result = new ResultDomain<>();
        List<UserDeptRoleVO> userDeptRoles = LoginUtil.getCurrentDeptRole();
        List<TbSysLoginLog> list = sysLoginLogMapper.selectLoginLogList(loginLog, userDeptRoles);
        if (list != null) {
            result.success("查询登录日志成功", list);
        } else {
            result.fail("查询登录日志失败");
        }
        return result;
    }

    @Override
    public ResultDomain<TbSysLoginLog> selectLoginLogPage(TbSysLoginLog loginLog, PageParam pageParam) {
        ResultDomain<TbSysLoginLog> result = new ResultDomain<>();
        List<UserDeptRoleVO> userDeptRoles = LoginUtil.getCurrentDeptRole();
        List<TbSysLoginLog> list = sysLoginLogMapper.selectLoginLogPage(loginLog, pageParam, userDeptRoles);
        PageDomain<TbSysLoginLog> pageDomain = new PageDomain<>();
        int count = sysLoginLogMapper.countLoginLog(loginLog, userDeptRoles);
        pageParam.setTotalElements(count);
        pageParam.setTotalPages((int)Math.ceil(count / pageParam.getPageSize() ));

        pageDomain.setPageParam(pageParam);
        pageDomain.setDataList(list);
        if (list != null) {
            result.success("查询登录日志成功", pageDomain);
        } else {
            result.fail("查询登录日志失败");
        }
        return result;

    }

}
