package com.lideeyunji.service.infra.service.impl;

import com.lideeyunji.tool.framework.common.pojo.PageResult;
import com.lideeyunji.tool.framework.common.util.object.BeanUtils;
import com.lideeyunji.service.infra.dto.ApiAccessLogCreateReqDTO;
import com.lideeyunji.service.infra.controller.vo.logger.ApiAccessLogPageReqVO;
import com.lideeyunji.service.infra.entity.ApiAccessLogDO;
import com.lideeyunji.service.infra.mapper.ApiAccessLogMapper;
import com.lideeyunji.service.infra.service.IApiAccessLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * API 访问日志 Service 实现类
 *
 * @author 金灯剑客
 */
@Slf4j
@Service
@Validated
public class ApiAccessLogServiceImpl implements IApiAccessLogService {

    @Resource
    private ApiAccessLogMapper apiAccessLogMapper;

    @Override
    public void createApiAccessLog(ApiAccessLogCreateReqDTO createDTO) {
        ApiAccessLogDO apiAccessLog = BeanUtils.toBean(createDTO, ApiAccessLogDO.class);
        apiAccessLogMapper.insert(apiAccessLog);
    }

    @Override
    public PageResult<ApiAccessLogDO> getApiAccessLogPage(ApiAccessLogPageReqVO pageReqVO) {
        return apiAccessLogMapper.selectPage(pageReqVO);
    }

    @Override
    @SuppressWarnings("DuplicatedCode")
    public Integer cleanAccessLog(Integer exceedDay, Integer deleteLimit) {
        int count = 0;
        LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
        // 循环删除，直到没有满足条件的数据
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            int deleteCount = apiAccessLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
            count += deleteCount;
            // 达到删除预期条数，说明到底了
            if (deleteCount < deleteLimit) {
                break;
            }
        }
        return count;
    }

}
