package cn.iocoder.yudao.module.system.service.log;

import cn.iocoder.yudao.module.system.controller.admin.log.vo.UserOperationLogPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.log.vo.UserOperationLogSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.log.UserOperationLogDO;
import cn.iocoder.yudao.module.system.dal.mysql.log.UserOperationLogMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_OPERATION_LOG_NOT_EXISTS;

/**
 * 用户操作记录 Service 实现类
 *
 * @author 陈宾顺
 */
@Service
@Validated
public class UserOperationLogServiceImpl implements UserOperationLogService {

    @Resource
    private UserOperationLogMapper userOperationLogMapper;

    @Override
    public Long createUserOperationLog(UserOperationLogSaveReqVO createReqVO) {
        // 插入
        if (createReqVO.getOperateAction().length() > 95) {
            createReqVO.setOperateAction(createReqVO.getOperateAction().substring(0,95));
        }
        UserOperationLogDO userOperationLog = BeanUtils.toBean(createReqVO, UserOperationLogDO.class);
        userOperationLogMapper.insert(userOperationLog);
        // 返回
        return userOperationLog.getId();
    }

    @Override
    public void updateUserOperationLog(UserOperationLogSaveReqVO updateReqVO) {
        // 校验存在
        validateUserOperationLogExists(updateReqVO.getId());
        // 更新
        UserOperationLogDO updateObj = BeanUtils.toBean(updateReqVO, UserOperationLogDO.class);
        userOperationLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserOperationLog(Long id) {
        // 校验存在
        validateUserOperationLogExists(id);
        // 删除
        userOperationLogMapper.deleteById(id);
    }

    private void validateUserOperationLogExists(Long id) {
        if (userOperationLogMapper.selectById(id) == null) {
            throw exception(USER_OPERATION_LOG_NOT_EXISTS);
        }
    }

    @Override
    public UserOperationLogDO getUserOperationLog(Long id) {
        return userOperationLogMapper.selectById(id);
    }

    @Override
    public PageResult<UserOperationLogDO> getUserOperationLogPage(UserOperationLogPageReqVO pageReqVO) {
        return userOperationLogMapper.selectPage(pageReqVO);
    }

}