package com.sw.common.accessory.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * xxl-job config
 * spring.factories 自动注入
 *
 * @author zhaowenjie 2022-08-10
 */
@ConfigurationProperties(prefix = "xxl.job")
@Configuration
@Data
@ComponentScan("com.sw.common.accessory.config")
public class XxlJobConfig {
    private final Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);

    private String accessToken;
    private final Admin admin = new Admin();
    private final Executor executor = new Executor();

    @Data
    public static class Admin {
        private String addresses;
    }

    @Data
    public static class Executor {
        private String appname;
        private String address;
        private String ip;
        private int port;
        private String logpath;
        private int logretentiondays;
    }

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(getAdmin().getAddresses());
        xxlJobSpringExecutor.setAppname(getExecutor().getAppname());
        xxlJobSpringExecutor.setAddress(getExecutor().getAddress());
        xxlJobSpringExecutor.setIp(getExecutor().getIp());
        xxlJobSpringExecutor.setPort(getExecutor().getPort());
        xxlJobSpringExecutor.setAccessToken(getAccessToken());
        xxlJobSpringExecutor.setLogPath(getExecutor().getLogpath());
        xxlJobSpringExecutor.setLogRetentionDays(getExecutor().getLogretentiondays());

        return xxlJobSpringExecutor;
    }

    /**
     * 针对多网卡、容器内部署等情况，可借助 "spring-cloud-commons" 提供的 "InetUtils" 组件灵活定制注册IP；
     *
     *      1、引入依赖：
     *          <dependency>
     *             <groupId>org.springframework.cloud</groupId>
     *             <artifactId>spring-cloud-commons</artifactId>
     *             <version>${version}</version>
     *         </dependency>
     *
     *      2、配置文件，或者容器启动变量
     *          spring.cloud.inetutils.preferred-networks: 'xxx.xxx.xxx.'
     *
     *      3、获取IP
     *          String ip_ = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
     */
}