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

import com.xunhong.erp.turbo.job.handler.XxlJobHandler;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author shenyifei
 */
@Configuration
@EnableConfigurationProperties(XxlJobProperties.class)
@RequiredArgsConstructor
public class XxlJobConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(XxlJobConfiguration.class);

	private final XxlJobProperties properties;

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = XxlJobProperties.PREFIX, value = "enabled", havingValue = "true")
	public XxlJobSpringExecutor xxlJobExecutor() {
		logger.info(">>>>>>>>>>> xxl-job config init.");
		XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
		xxlJobSpringExecutor.setAdminAddresses(properties.getAdminAddresses());
		xxlJobSpringExecutor.setAppname(properties.getAppName());
		xxlJobSpringExecutor.setIp(properties.getIp());
		xxlJobSpringExecutor.setPort(properties.getPort());
		xxlJobSpringExecutor.setAccessToken(properties.getAccessToken());
		xxlJobSpringExecutor.setLogPath(properties.getLogPath());
		xxlJobSpringExecutor.setLogRetentionDays(properties.getLogRetentionDays());
		return xxlJobSpringExecutor;
	}

	@Bean
	@ConditionalOnProperty(prefix = XxlJobProperties.PREFIX, value = "enabled", havingValue = "true")
	public XxlJobHandler xxlJobHandler() {
		XxlJobHandler xxlJobHandler = new XxlJobHandler();
		xxlJobHandler.setAdminAddresses(properties.getAdminAddresses());
		xxlJobHandler.setUserName(properties.getUserName());
		xxlJobHandler.setPassword(properties.getPassword());

		return xxlJobHandler;
	}
}
