package com.xunhong.erp.turbo.job.handler;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author shenyifei
 * @date 2022/3/22 11:18
 */
@Slf4j
@ConditionalOnMissingBean(JobGroupRunner.class)
@RequiredArgsConstructor
public class JobGroupRunner implements ApplicationRunner {

	private static final ConcurrentHashMap<String, Integer> JOB_GROUP_MAP = new ConcurrentHashMap<>();
	private final XxlJobHandler xxlJobHandler;
	@Value("${spring.profiles.active:local}")
	private String active;
	@Value("${spring.application.name:}")
	private String applicationName;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		xxlJobHandler.getCookie();
		List<JobGroupDto> jobGroupDtoList = xxlJobHandler.pageList(0, 100);

		jobGroupDtoList.forEach(jobGroupDto -> JOB_GROUP_MAP.put(jobGroupDto.getAppname(), jobGroupDto.getId()));

		log.info("----JOB_GROUP_MAP----:{}", JSONObject.toJSONString(JOB_GROUP_MAP));
	}

	/**
	 * 获取默认的执行器
	 *
	 * @return 返回默认执行器
	 */
	@SuppressWarnings("unused")
	public Integer getJobGroup() {
		return JOB_GROUP_MAP.get(applicationName + "-" + active);
	}
}
