package jnpf.cultivate.utils;

import jnpf.model.cultivate.vo.learn.info.TimeDifference;

import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @Author: peng.hao
 * @create: 2024/9/11:18:08
 */
public class CultivateDateTimeUtils {

    /**
     * 计算两个时间之间的剩余值。
     *
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param type (0:天,1:小时)
     * @return 剩余值
     */
    public static String calculateRemainingValue(Date startTime, Date endTime, Integer type) {
        if (startTime == null || endTime == null) {
            throw new IllegalArgumentException("Start time and end time cannot be null");
        }
        LocalDateTime start = getLocalDateTime(startTime);
        LocalDateTime end = getLocalDateTime(endTime);
        if (start.isAfter(end)) {
            return "";
        }
        if (type == 0){
            long remainingDays = ChronoUnit.DAYS.between(start, end);
            if (remainingDays >= 1) {
                return String.valueOf(remainingDays);
            } else {
                // 计算剩余的毫秒数
                long between = ChronoUnit.HOURS.between(start, end);
                double remainingHours = between % 24; // 计算剩余小时数
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                return  decimalFormat.format(remainingHours / 24);
            }
        }else {
            return String.valueOf(ChronoUnit.HOURS.between(start, end));
        }
    }
    /**
     * 计算两个日期之间的差值，返回时分秒。
     *
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 返回一个包含小时数、分钟数和秒数的对象
     */
    public static TimeDifference calculateDifference(Date startDate, Date endDate) {
        long diffInMillies = endDate.getTime() - startDate.getTime();

        long hours = diffInMillies / (60 * 60 * 1000);
        diffInMillies %= (60 * 60 * 1000);

        long minutes = diffInMillies / (60 * 1000);
        diffInMillies %= (60 * 1000);

        long seconds = diffInMillies / 1000;

        return new TimeDifference(hours, minutes, seconds);
    }

    /**
     * 转换时间
     * @param startTime
     * @return
     */
    private  static LocalDateTime getLocalDateTime(Date startTime) {
        // 获取 Instant 对象
        Instant instant = startTime.toInstant();
        // 指定时区，这里假设为中国标准时间 CST
        ZoneId zoneId = ZoneId.systemDefault(); // 或者使用 ZoneId.of("Asia/Shanghai");
        // 将 Instant 与时区结合，创建 ZonedDateTime
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);
        // 提取 LocalDateTime
        return zonedDateTime.toLocalDateTime();
    }
}
