package com.xy.job;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xy.entity.DeviceFaultLog;
import com.xy.entity.SysDictRedis;
import com.xy.service.DeviceFaultLogServiceImpl;
import com.xy.sys.EnumDataClearSize;
import com.xy.utils.RecursionUtils;
import com.xy.utils.SysDictUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 设备故障job
 *
 * @author 谭斌
 * @date 2024/01/08
 */
@Slf4j
@Component
@AllArgsConstructor
public class DeviceFaultJob {

    private DeviceFaultLogServiceImpl deviceFaultLogService;

    /**
     * 故障日志清理 默认保留n天
     *
     * @return
     */
    @XxlJob("delDeviceFaultLog")
    public ReturnT<String> delDeviceFaultLog() {
        SysDictRedis sysDictRedis = SysDictUtils.get(EnumDataClearSize.Code.CODE.getCode(), EnumDataClearSize.DEVICE_FAULT_LOG_DAY.getCode());
        Integer saveDay = Integer.valueOf(sysDictRedis.getValue());
        // 获取当前日期
        Date today = DateUtil.date();
        // 获取n天前的日期的开始时间（包含今天）
        Date daysAgo = DateUtil.beginOfDay(DateUtil.offsetDay(today, -(saveDay - 1)));
        LambdaQueryWrapper<DeviceFaultLog> lambdaQueryWrapper = new LambdaQueryWrapper<DeviceFaultLog>()
                .lt(DeviceFaultLog::getEventTime, daysAgo)
                .last("limit 10000");
        RecursionUtils.recursion(current -> {
            boolean remove = deviceFaultLogService.remove(lambdaQueryWrapper);
            if (!remove) {
                return false;
            }
            return true;
        });
        return ReturnT.SUCCESS;
    }
}
