package com.yfd.platform.component.sntp;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetAddress;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Date;
import java.util.Locale;

//@Component
@Slf4j
public class SNTPClient {

    @Value("${sntp.server-ip}")
    private String server_ip;
    @Value("${sntp.server-port}")
    private int server_port;

    public void syncServerTime(String serverAddress, int serverPort) {
        //String host = "ntp.aliyun.com"; // 可以替换为具体的NTP服务器地址
        NTPUDPClient client = new NTPUDPClient();         // 创建SNTP客户端
        client.setDefaultTimeout(5000); // 设置超时时间为5秒
        try {
            client.open();
            // 获取阿里云公网NTP服务器地址
            InetAddress hostAddr = InetAddress.getByName(serverAddress);
            TimeInfo info = client.getTime(hostAddr, serverPort);
            info.computeDetails(); // 计算时间差
            // 获取网络时间
            long serverTime = System.currentTimeMillis() + info.getOffset();
            Date currentdate = new Date(serverTime);
            // 设置系统时间
            Date newTime = new Date(serverTime);
            setSystemTime(newTime);
        } catch (IOException e) {
            log.error(e.getMessage());;
            throw new RuntimeException("同步失败");
        } finally {
            client.close();
        }
    }

    //    @Scheduled(initialDelay = 20000, fixedRate = 10000)
    //@Scheduled(fixedRate = 60000)
    public void syncTimeTask() {
        SNTPClient sntpClient = new SNTPClient();
        //sntpClient.syncServerTime("time1.aliyun.com", server_port);
        sntpClient.syncServerTime(server_ip, server_port);
    }

    public JSONObject getCurrentSystemTime() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取年份
        int year; // 注意：从Java 9开始，应该使用 currentDate.getYearValue()

        // 但在Java 8及以后版本中，应该使用以下方式
        year = currentDate.getYear();

        // 获取月份（月份从1开始计数，不是从0）
        int month = currentDate.getMonthValue();

        // 获取日期（日）
        int dayOfMonth = currentDate.getDayOfMonth();

        String monthStr = month > 9 ? month + "" : "0" + month;
        String dayStr = dayOfMonth > 9 ? dayOfMonth + "" : "0" + dayOfMonth;

        // 获取星期几
        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("year", year);
        jsonObject.put("month", monthStr);
        jsonObject.put("dayOfMonth", dayStr);
        jsonObject.put("dayOfWeek", dayOfWeek.getValue());
        jsonObject.put("weekName", dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()));
        return jsonObject;

    }

    public static void setSystemTime(Date newTime) {
        try {
            //时间转换
            Instant instant = newTime.toInstant(); // 将java.util.Date转换为java.time.Instant
            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); // 转换为本地日期时间
            //linux修改时间
            String timeStr = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            //windows修改时间年-月-日
            String setDateCommand = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //windows修改时间时-分-秒
            String setDateProcess = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));

            if (isWindows()) {
                // 使用Windows系统命令设置时间
                execCmd("cmd /c date " + setDateCommand);
                execCmd("cmd /c time " + setDateProcess);
            } else if (isLinux()) {
                // 使用Linux系统命令设置时间
                execCmd("sudo date -s \"" + timeStr + "\"");
            }
        } catch (Exception e) {
            log.error(e.getMessage());;
        }
    }

    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }

    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }

    public static void execCmd(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("系统时间修改成功！");
            } else {
                log.error("系统时间修改失败！");
            }
        } catch (Exception e) {
            log.error(e.getMessage());;
        }
    }
}


