package com.chushang.job.core.config;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import io.netty.util.internal.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;


/**
 * xxl-job config
 *
 * @author xuxueli 2017-04-28
 */
@Data
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "xxl.job")
public class XxlJobConfig {

    private String adminAddresses;

    private String accessToken;

    private Executor executor;

    @Data
    public static class Executor {
        private String appName;

        private String address;

        private String ip;

        private int port;

        private String logPath = "xxl-job/jobhandler";

        private int logRetentionDays = 30;
    }

    @Bean
    public XxlJobSpringExecutor xxlJobExecutor() {
        String ip = executor.ip;
        if (StringUtil.isNullOrEmpty(ip)){
            ip = getServerIp();
        }
        log.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
        xxlJobSpringExecutor.setAccessToken(accessToken);

        xxlJobSpringExecutor.setAppname(executor.appName);
        xxlJobSpringExecutor.setAddress(executor.address);

        xxlJobSpringExecutor.setIp(ip);
        xxlJobSpringExecutor.setPort(executor.port);

        xxlJobSpringExecutor.setLogPath(executor.logPath);
        xxlJobSpringExecutor.setLogRetentionDays(executor.logRetentionDays);
        return xxlJobSpringExecutor;
    }

    /**
     * 获取本地IP地址
     */
    public static String getServerIp() {
        if (isWindowsOs()) {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                return "";
            }
        } else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 判断操作系统是否是Windows
     */
    public static boolean isWindowsOs() {
        boolean isWindowsOs = false;
        String osName = System.getProperty("os.name");
        if ("WINDOWS".contains(osName.toLowerCase())) {
            isWindowsOs = true;
        }
        return isWindowsOs;
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     */
    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface networkInterface = en.nextElement();
                String name = networkInterface.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipaddress = inetAddress.getHostAddress();
                            if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                                ip = ipaddress;
                            }
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            log.error("获取ip地址异常", ex);
        }
        return ip;
    }

}