package com.xty.common.util

import java.util.Calendar

object SolarTermUtil {

    private val SOLAR_TERMS = arrayOf(
        "立春", "雨水", "惊蛰", "春分",
        "清明", "谷雨", "立夏", "小满", "芒种", "夏至",
        "小暑", "大暑", "立秋", "处暑", "白露", "秋分",
        "寒露", "霜降", "立冬", "小雪", "大雪", "冬至",
        "小寒", "大寒"
    )

    private val SOLAR_TERM_ANGLE = doubleArrayOf(
        345.0, 0.0, 15.0, 30.0,
        45.0, 60.0, 75.0, 90.0, 105.0, 120.0,
        135.0, 150.0, 165.0, 180.0, 195.0, 210.0,
        225.0, 240.0, 255.0, 270.0, 285.0, 300.0,
        315.0, 330.0
    )

    fun getCurrentSolarTerm(): String {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)

        var index = -1
        val currentAngle = calculateSolarTermAngle(year, month, day, hour, minute, second)

        for (i in SOLAR_TERM_ANGLE.indices) {
            if (currentAngle < SOLAR_TERM_ANGLE[i]) {
                index = i
                break
            }
        }

        if (index == -1) {
            index = 0 // 如果没有匹配的索引，默认为立春
        }

        return SOLAR_TERMS[index]
    }

    fun getCurrentSolarTermIndex(): Int {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)

        var index = -1
        val currentAngle = calculateSolarTermAngle(year, month, day, hour, minute, second)

        for (i in SOLAR_TERM_ANGLE.indices) {
            if (currentAngle < SOLAR_TERM_ANGLE[i]) {
                index = i
                break
            }
        }

        if (index == -1) {
            index = 0 // 如果没有匹配的索引，默认为立春
        }

        return index
    }

    private fun calculateSolarTermAngle(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Double {
        // 根据具体的算法计算当前时间对应的太阳黄道上的角度
        // 这里使用一个简化的算法，具体算法可能会更复杂
        // 返回一个0-360的角度值
        // 这里仅为示例，并非准确的算法实现
        return ((month - 2 + 24) % 24) * 15.0 + (day - 1) * 1.0
    }
}