package com.zksy.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.domain.Result;
import com.zksy.data.domain.dto.TimeTaskDto;
import com.zksy.data.domain.po.XhTimeTask;
import com.zksy.data.service.XhTimeTaskService;
import com.zksy.data.mapper.XhTimeTaskMapper;
import com.zksy.data.utils.TaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author hxb
* @description 针对表【xh_time_task】的数据库操作Service实现
* @createDate 2024-11-07 11:03:48
*/
@Service
public class XhTimeTaskServiceImpl extends ServiceImpl<XhTimeTaskMapper, XhTimeTask>
    implements XhTimeTaskService{
    @Autowired
    private TaskManager taskManager;
    @Override
    public Result<String> saveTimeTask(TimeTaskDto timeTaskDto) {
        XhTimeTask task = new XhTimeTask();
        task.setCreatedAt(new Date());
        task.setUpdatedAt(new Date());
        task.setTaskName(timeTaskDto.getTaskName());
        task.setServiceName(timeTaskDto.getServiceName());
        task.setCronExpression(timeTaskDto.getCronExpression());
        task.setScheduleType(timeTaskDto.getScheduleType());
        task.setEnabled(1);
        this.save(task);
        taskManager.addTask(task.getTaskName(), () -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("执行任务");
        }, timeTaskDto.getCronExpression());
        return Result.ok("添加定时任务成功");
    }

    @Override
    public Result<String> removeTimeTask(String taskName) {
        taskManager.removeTask(taskName);
        LambdaQueryWrapper<XhTimeTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XhTimeTask::getTaskName, taskName);
        this.remove(wrapper);
        return Result.ok("删除定时任务成功");
    }

    @Override
    public Result<String> stopAllTasks() {
        taskManager.stopAllTasks();
        LambdaUpdateWrapper<XhTimeTask> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(XhTimeTask::getEnabled, 1);
        wrapper.set(XhTimeTask::getEnabled, 0);
        this.update(wrapper);
        return Result.ok("停止所有定时任务成功");
    }

    @Override
    public Result<List<XhTimeTask>> getAllTask() {
        List<XhTimeTask> list = this.list();
        return Result.ok(list);
    }
}




