package com.qmth.teachcloud.common.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.bean.dto.DataPermissionRule;
import com.qmth.teachcloud.common.bean.result.BasicOperationLogResult;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicOperationLog;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.log.OperationTypeEnum;
import com.qmth.teachcloud.common.mapper.BasicOperationLogMapper;
import com.qmth.teachcloud.common.service.BasicOperationLogService;
import com.qmth.teachcloud.common.service.BasicRoleDataPermissionService;
import com.qmth.teachcloud.common.util.ServletUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 基础操作日志服务实现类
 * @Author: CaoZixuan
 * @Date: 2022-02-15
 */
@Service
public class BasicOperationLogServiceImpl extends ServiceImpl<BasicOperationLogMapper, BasicOperationLog> implements BasicOperationLogService {
    @Resource
    private BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Override
    public IPage<BasicOperationLogResult> findOperationLogPage(OperationTypeEnum operationType, Long startTime, Long endTime, String operatorName, SysUser requestUser, int pageNumber, int pageSize) {
        Long schoolId = requestUser.getSchoolId();
        if (SystemConstant.strNotNull(operatorName)) {
            operatorName = SystemConstant.translateSpecificSign(operatorName);
        }
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, requestUser.getId(), ServletUtil.getRequest().getServletPath());
        return this.baseMapper.findOperationLogPage(new Page<>(pageNumber, pageSize), schoolId, operationType, startTime, endTime, operatorName, dpr);
    }

    @Override
    public void saveOperateLogWithNoAuth(Long schoolId, Long userId, String detail, OperationTypeEnum operationTypeEnum, String args) {
        HttpServletRequest request = ServletUtil.getRequest();
        BasicOperationLog operationLog = new BasicOperationLog();
        operationLog.setId(SystemConstant.getDbUuid());
        operationLog.setOperationType(operationTypeEnum);
        operationLog.setDetail(detail);
        operationLog.setSchoolId(schoolId);
        operationLog.setUrl(request.getServletPath());
        operationLog.setUserId(userId);
        operationLog.setArgs(args);
        operationLog.setRunStatus("成功");
        operationLog.setIp(ServletUtil.getIP());
        operationLog.setCreateTime(System.currentTimeMillis());
        this.save(operationLog);
    }
}
