package xtools.boot.job.xxl.init;

import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.NonNull;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import xtools.base.config.BaseParams;
import xtools.boot.core.interfaces.JobInterface;
import xtools.boot.core.utils.SpringContextUtils;
import xtools.boot.job.xxl.config.XxlJobConfig;
import xtools.core.CollectionUtils;

import java.util.Collection;
import java.util.Objects;

/**
 * <p>Title : InitIp</p>
 * <p>Description : InitIp</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/2/16 10:21
 */
@Slf4j
@Component
@RequiredArgsConstructor
@Order(BaseParams.CP_NUM90)
public class InitXxlJob implements ApplicationRunner, BaseParams {

    private final XxlJobConfig xxlJobConfig;

    @Override
    public void run(@NonNull ApplicationArguments args) {
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        Boolean enabled = xxlJobConfig.getEnabled();
        if (Objects.isNull(enabled) || !enabled) {
            log.info("xxl-job未启用");
            return;
        }
        Collection<JobInterface> beanList = SpringContextUtils.getBeanList(JobInterface.class);
        if (CollectionUtils.isEmpty(beanList)) {
            log.info("没有需要执行xxl-job的任务");
            return;
        }
        beanList.forEach(item -> {
            try {
                String name = item.getClass().getSimpleName();
                name = Character.toLowerCase(name.charAt(CP_NUM0)) + name.substring(CP_NUM1);
                registerXxlJob(name, item);
                log.info("注册xxl-job任务成功：{}", name);
            } catch (Exception e) {
                log.error("注册xxl-job任务异常", e);
            }
        });
    }

    /**
     * 注册任务
     *
     * @param name 任务名称
     * @param job  任务
     */
    private void registerXxlJob(String name, JobInterface job) {
        IJobHandler handler = new IJobHandler() {
            @Override
            public void execute() throws Exception {
                job.execute();
            }

            @Override
            public void init() {
                job.init();
            }

            @Override
            public void destroy() {
                job.destroy();
            }
        };
        // 注册到XXL-JOB
        XxlJobExecutor.registryJobHandler(name, handler);
    }
}
