package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.sop.business.bean.result.SysLogResult;
import com.qmth.sop.business.entity.SysLog;
import com.qmth.sop.business.entity.SysRole;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.SysLogMapper;
import com.qmth.sop.business.service.SysLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.sop.business.service.SysUserRoleService;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.LogTypeEnum;
import com.qmth.sop.common.util.ServletUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统日志 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-08-01
 */
@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    public IPage<SysLogResult> page(Long startTime, Long endTime, String content, int pageNumber, int pageSize) {
        if (content != null && content.length() > 0) {
            content = SystemConstant.translateSpecificSign(content);
        }
        return this.baseMapper.page(new Page<>(pageNumber, pageSize), startTime, endTime, content);
    }

    @Transactional
    @Override
    public void saveLogWithNoAuth(Long userId, String detail, LogTypeEnum logType) {
        HttpServletRequest request = ServletUtil.getRequest();
        SysUser requestUser = sysUserService.getById(userId);
        if (Objects.isNull(requestUser)) {
            throw ExceptionResultEnum.ERROR.exception("用户不存在");
        }

        List<SysRole> sysRoleList = sysUserRoleService.listRoleByUserId(requestUser.getId());
        detail = requestUser.getRealName() + " " + detail;
        if (CollectionUtils.isNotEmpty(sysRoleList)) {
            String roleNames = sysRoleList.stream().map(SysRole::getName).collect(Collectors.joining(","));
            detail = "[" + roleNames + "] " + detail;
        }

        SysLog sysLog = new SysLog();
        sysLog.setId(SystemConstant.getDbUuid());
        sysLog.setUrl(request.getServletPath());
        sysLog.setUserId(userId);
        sysLog.setUserName(requestUser.getRealName());
        sysLog.setContent(detail);
        sysLog.setType(logType);
        sysLog.setCreateTime(System.currentTimeMillis());
        this.save(sysLog);
    }
}
