/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.ema.common.tools.timer.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.extra.spring.SpringUtil;
import com.ema.common.exceptions.MyAssert;
import com.ema.common.exceptions.MyException;
import com.ema.common.tools.redis.RedisService;
import com.ema.common.tools.timer.TimerExeService;
import com.ema.common.tools.timer.TimerTaskRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * hutool方式的定时任务执行
 *
 * @author yubaoshan
 * @date 2020/7/1 13:48
 */
@Slf4j
@Service
public class HutoolTimerExeServiceImpl implements TimerExeService {

    @Resource
    private RedisService redisService;

    @Override
    public synchronized boolean startTimer(String taskId, String cron, String className) {

        MyAssert.isTrue(!ObjectUtil.hasEmpty(taskId, cron, className), "定时任务id，定时任务cron表达式，定时任务执行类不能为空！");

        // 预加载类看是否存在此定时任务类
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new MyException("定时任务执行类不存在！");
        }
        // 先停止上次定时器，防止重复启动
        this.stopTimer(taskId);

        // 如果调度器未启动则启动
        boolean wasStarted = CronUtil.getScheduler().isStarted();
        if (!wasStarted) {
            // 设置秒级别的启用
            CronUtil.setMatchSecond(true);
            // 启动调度器（如果之前是运行状态则恢复，否则首次启动）
            CronUtil.start();
        }

        // 添加定时任务
        CronUtil.schedule(taskId, cron, new Task() {
            @Override
            public void execute() {
                String timerLock = null;
                TimerTaskRunner timerTaskRunner = null;
                try {
                    timerTaskRunner = (TimerTaskRunner) SpringUtil.getBean(Class.forName(className));
                    //加锁防止重复执行
                    timerLock = redisService.tryLock(taskId, 600 * 1000);
                    if (StrUtil.isNotBlank(timerLock)) { // 获取到锁，执行任务
                        try {
                            timerTaskRunner.action();
                            timerTaskRunner.afterAction(taskId, true, "执行成功");
                        } catch (Exception e) {
                            log.error(">>>>>> 定时任务执行异常：{}", e.getMessage());
                            timerTaskRunner.afterAction(taskId, false, "执行异常：" + StrUtil.maxLength(e.getMessage(), 1000));
                        }
                    }
                } catch (Exception e) {
                    log.error(">>>>>> 定时任务启动异常：{}", e.getMessage());
                    if (timerTaskRunner != null) {
                        timerTaskRunner.afterAction(taskId, false, "启动异常：" + StrUtil.maxLength(e.getMessage(), 1000));
                    }
                } finally {
                    if (StrUtil.isNotBlank(timerLock)) {
                        redisService.unlock(taskId, timerLock);
                    }
                }
            }
        });

        return true;
    }

    @Override
    public synchronized boolean stopTimer(String taskId) {
        return CronUtil.remove(taskId);
    }

}
