package com.ruoyi.quartz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.SysJobLog;
import com.ruoyi.quartz.mapper.SysJobLogMapper;
import com.ruoyi.quartz.service.ISysJobLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 定时任务调度日志信息 服务层
 * 
 * @author ruoyi
 */
@Service
public class SysJobLogServiceImpl extends MPJBaseServiceImpl<SysJobLogMapper, SysJobLog> implements ISysJobLogService
{

    /**
     * 获取quartz调度器日志的计划任务
     * 
     * @param jobLog 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public List<SysJobLog> selectJobLogList(SysJobLog jobLog)
    {
        LambdaQueryWrapper<SysJobLog> list = new LambdaQueryWrapper<SysJobLog>()
                .like(StringUtils.isNotBlank(jobLog.getJobName()), SysJobLog::getJobName, jobLog.getJobName())
                .eq(StringUtils.isNotBlank(jobLog.getJobGroup()), SysJobLog::getJobGroup, jobLog.getJobGroup())
                .eq(StringUtils.isNotBlank(jobLog.getStatus()), SysJobLog::getStatus, jobLog.getStatus())
                .like(StringUtils.isNotBlank(jobLog.getInvokeTarget()), SysJobLog::getInvokeTarget, jobLog.getInvokeTarget())
                .apply(StringUtils.isNotNull(jobLog.getParams().get("beginTime")),
                        "date_format(create_time,'%y%m%d') >= date_format('" + jobLog.getParams().get("beginTime") + "','%y%m%d')")
                .apply(StringUtils.isNotNull(jobLog.getParams().get("endTime")),
                        "date_format(create_time,'%y%m%d') <= date_format('" + jobLog.getParams().get("endTime") + "','%y%m%d')");
        return list(list);
    }

    /**
     * 通过调度任务日志ID查询调度信息
     * 
     * @param jobLogId 调度任务日志ID
     * @return 调度任务日志对象信息
     */
    @Override
    public SysJobLog selectJobLogById(Long jobLogId)
    {
        return getById(jobLogId);
    }

    /**
     * 新增任务日志
     * 
     * @param jobLog 调度日志信息
     */
    @Override
    public void addJobLog(SysJobLog jobLog)
    {
        save(jobLog);
    }

    /**
     * 批量删除调度日志信息
     * 
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public boolean deleteJobLogByIds(Long[] logIds)
    {
        return removeBatchByIds(Arrays.asList(logIds));
    }

    /**
     * 删除任务日志
     * 
     * @param jobId 调度日志ID
     */
    @Override
    public boolean deleteJobLogById(Long jobId)
    {
        return removeById(jobId);
    }

    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog()
    {
        remove(new LambdaQueryWrapper<SysJobLog>().le(SysJobLog::getCreateTime,
                DateUtil.date()));
    }
}
