package com.chushang.common.log.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chushang.common.core.web.EnumUtils;
import com.chushang.common.log.entity.SysLogEntity;
import com.chushang.common.log.entity.dto.ListLogDTO;
import com.chushang.common.log.enums.LogTypeEnum;
import com.chushang.common.mybatis.utils.PageResult;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * by zhaowenyuan create 2022/3/16 15:35
 */
public interface SysLogService extends IService<SysLogEntity> {

    default PageResult queryPage(ListLogDTO params){
        String operation = params.getOperation();
        LambdaQueryWrapper<SysLogEntity> lambdaQueryWrapper = new QueryWrapper<SysLogEntity>()
                .orderBy(true, "asc".equals(params.getIsAsc()), params.getOrderBy())
                .lambda()
                .eq(null != params.getType(), SysLogEntity::getType, EnumUtils.getByCode(params.getType(), LogTypeEnum.class))
                .like(StringUtils.isNotBlank(operation), SysLogEntity::getOperation, operation)
                .like(StringUtils.isNotEmpty(params.getRemoteAddr()), SysLogEntity::getRemoteAddr, params.getRemoteAddr())
                .like(StringUtils.isNotEmpty(params.getUsername()), SysLogEntity::getUsername, params.getUsername())
                ;
        if (StringUtils.isNotEmpty(params.getBusinessType())){
            lambdaQueryWrapper.in(SysLogEntity::getOperationType, Arrays.asList(params.getBusinessType().split(",")));
        }
        if (null != params.getBeginTime() && null != params.getEndTime()){
            lambdaQueryWrapper.between(SysLogEntity::getCreateTime,params.getBeginTime(), params.getEndTime());
        }else if (null != params.getBeginTime()){
            lambdaQueryWrapper.ge(SysLogEntity::getCreateTime, params.getBeginTime());
        }else if (null != params.getEndTime()){
            lambdaQueryWrapper.le(SysLogEntity::getCreateTime, params.getEndTime());
        }

        IPage<SysLogEntity> page = this.page(
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(params.getPage(), params.getLimit()),lambdaQueryWrapper
        );
        return new PageResult(page);
    }

    void cleanLog();
}
