package com.ytpm.hydtw.utils

import org.threeten.bp.LocalDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.ZoneId
import org.threeten.bp.Instant

/**
 * Android API < 26 下的时间工具类
 */
object DateTimeUtils {
    // 标准时间格式 yyyy-MM-dd HH:mm:ss
    private const val STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss"

    /**
     * 获取当前时间字符串
     */
    fun getCurrentDateTime(): String {
        val now = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern(STANDARD_FORMAT)
        return now.format(formatter)
    }

    /**
     * 获取指定时区的当前时间
     */
    fun getCurrentDateTimeInZone(zoneId: String = "Asia/Shanghai"): String {
        val now = Instant.now().atZone(ZoneId.of(zoneId))
        val formatter = DateTimeFormatter.ofPattern(STANDARD_FORMAT)
        return now.format(formatter)
    }

    fun getCurrentDateTimeIso(): String? {
        val instant = Instant.now()
        val formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME
        val answerTime = instant.atZone(ZoneId.of("UTC")).format(formatter)
        return answerTime
    }

    /**
     * 时间戳转换为指定格式
     */
    fun timestampToFormattedString(timestamp: Long): String {
        val instant = Instant.ofEpochMilli(timestamp)
        val localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime()
        val formatter = DateTimeFormatter.ofPattern(STANDARD_FORMAT)
        return localDateTime.format(formatter)
    }

    /**
     * 解析时间字符串
     */
    fun parseDateTime(dateTimeString: String): LocalDateTime? {
        return try {
            val formatter = DateTimeFormatter.ofPattern(STANDARD_FORMAT)
            LocalDateTime.parse(dateTimeString, formatter)
        } catch (e: Exception) {
            null
        }
    }
}