package com.kym.service.jobs;

import jakarta.validation.constraints.NotNull;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author skyline
 * @description 延迟执行
 * @date 2023-10-08 21:43
 */
public class DelayedItem<T> implements Delayed {
    /**
     * 业务对象
     */
    public final T data;

    /**
     * 定时时间
     */
    public LocalDateTime delayTime = LocalDateTime.MIN;

    public DelayedItem(T data, LocalDateTime delayTime) {
        this.data = data;
        this.delayTime = delayTime;
    }


    /**
     * 获取过期时间
     *
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(@NotNull TimeUnit unit) {
        return unit.convert(delayTime.toInstant(ZoneOffset.ofHours(+8)).toEpochMilli() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 比较排序
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(@NotNull Delayed o) {
        var flag = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        return flag > 0 ? 1 : flag < 0 ? -1 : 0;
    }
}
