package com.ema.admin.modules.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ema.admin.modules.system.entity.SysTimersJob;
import com.ema.admin.modules.system.enums.SysTimerJobEnum;
import com.ema.admin.modules.system.mapper.SysTimersJobMapper;
import com.ema.admin.modules.system.service.SysTimersJobService;
import com.ema.admin.modules.system.vo.SysTimersJobQueryVo;
import com.ema.common.domain.enums.BooleanEnum;
import com.ema.common.tools.timer.TimerExeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 定时任务 服务层实现。
 *
 * @author LIJIAN
 * @since 2026-03-24
 */
@Slf4j
@Service
public class SysTimersJobServiceImpl extends ServiceImpl<SysTimersJobMapper, SysTimersJob>  implements SysTimersJobService{

    @Resource
    private TimerExeService timerExeService;

    @Override
    public Page<SysTimersJob> page(SysTimersJobQueryVo queryVo) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.like(SysTimersJob::getTimerName, queryVo.getTimerName(), StrUtil.isNotBlank(queryVo.getTimerName()));
        queryWrapper.like(SysTimersJob::getActionClass, queryVo.getActionClass(), StrUtil.isNotBlank(queryVo.getActionClass()));
        queryWrapper.eq(SysTimersJob::getJobStatus, queryVo.getJobStatus(), StrUtil.isNotBlank(queryVo.getJobStatus()));
        queryWrapper.eq(SysTimersJob::getLastStatus, queryVo.getLastStatus(), StrUtil.isNotBlank(queryVo.getLastStatus()));
        return this.page(new Page<>(queryVo.getPageNumber(), queryVo.getPageSize()), queryWrapper);
    }


    @Override
    public void initAllTimerJob() {
        // 获取所有开启状态的任务
        List<SysTimersJob> list = this.queryChain()
                .eq(SysTimersJob::getJobStatus, SysTimerJobEnum.Status.RUNNING.getCode())
                .list();
        // 添加定时任务到调度器（使用顺序流，避免并行导致调度器启动冲突）
        list.forEach(sysTimersJob -> {
            try {
                timerExeService.startTimer(sysTimersJob.getId(), sysTimersJob.getCron(), sysTimersJob.getActionClass());
                log.info(">>>>>> ✓ 定时任务恢复成功：[{}] {}", sysTimersJob.getId(), sysTimersJob.getTimerName());
            } catch (Exception e) {
                log.error(">>>>>> ✗ 定时任务启动失败：[{}] {} - {}", sysTimersJob.getId(), sysTimersJob.getTimerName(), e.getMessage());
                this.updateActionResult(sysTimersJob.getId(), false, "定时任务启动失败: "+e.getMessage());
            }
        });
    }

    @Override
    public void updateActionResult(String taskId, boolean isSuccess, String msg) {
        this.updateChain().set(SysTimersJob::getLastTime, new Date())
                .set(SysTimersJob::getLastStatus, isSuccess ? BooleanEnum.TRUE.getValue() : BooleanEnum.FALSE.getValue())
                .set(SysTimersJob::getLastMsg, msg)
                .eq(SysTimersJob::getId, taskId)
                .eq(SysTimersJob::getUpdateBy,"system")
                .update();
    }

}
