package com.xty.network.model

import android.os.Build
import androidx.annotation.RequiresApi
import com.google.gson.annotations.SerializedName
import java.nio.DoubleBuffer
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt

data class BloodLipidDataBean(
    val ldlContent:String,
    val hdlContent:String,
    val tcContent:String,
    val tgContent:String,
    val comprehensiveContent:String,
    val valueCompare:ValueCompare,
    val value:ValueCompare,
    var modelCompare: MutableList<ModelBean>,
    var model: MutableList<ModelBean>

){
    data class ValueCompare(
        val maxHdl:Float,
        val minHdl:Float,
        val tcAbnormal:Int,
        val count:Int,
        val avgHdl:Float,
        val tcNormal:Int,
        val avgTg:Float,
        val avgTc:Float,
        val tgNormal:Int,
        val minTc:Float,
        val minTg:Float,
        val hdlAbnormal:Int,
        val avgLdl:Float,
        val hdlNormal:Int,
        val minLdl:Float,
        val maxTg:Float,
        val ldlNormal:Int,
        val ldlAbnormal:Int,
        val maxTc:Float,
        val maxLdl:Float,
        val tgAbnormal:Int
    )


    data class ModelBean(
        @SerializedName("hdl", alternate = ["avgHdl"])
        var hdl:Float,
        @SerializedName("tg", alternate = ["avgTg"])
        var tg:Float,
        @SerializedName("ldl", alternate = ["avgLdl"])
        var ldl:Float,
        @SerializedName("tc", alternate = ["avgTc"])
        var tc:Float,
        var time:String
    )

    @RequiresApi(Build.VERSION_CODES.O)
    fun mapDataToTime(dataList: MutableList<ModelBean>): MutableList<ModelBean> {
        val mappedData = mutableListOf<ModelBean>()
        val dateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        // 创建一天的时间节点
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 5)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        val startTime = calendar.time

        calendar.add(Calendar.HOUR_OF_DAY, 4)
        calendar.add(Calendar.MINUTE, 0)
        var endTime = calendar.time

        // 如果是时间是今天，endTime为最近的时间
        /*    val now = Calendar.getInstance()
            val today = now.clone() as Calendar
            now.timeInMillis =
                if (dataList.isEmpty()) System.currentTimeMillis() else dataList.first().time.toLong() * 1000

            if (today.get(Calendar.YEAR) == now.get(Calendar.YEAR) &&
                today.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR)
            ) {
                // If today, use the last time in the range
                endTime = now.time
            }*/

        // 初始化时间节点和默认值
        var currentTime = startTime
        while (currentTime <= endTime) {
            mappedData.add(ModelBean(0f,0f,0f,0f,dateFormat.format(currentTime)))
            calendar.time = currentTime
            calendar.add(Calendar.HOUR_OF_DAY, 1)
            currentTime = calendar.time
        }
        val timestamp = 1688631900L
        val time = Date(timestamp * 1000)
        // 将数据集合中的时间映射到时间节点上
        for (model in dataList) {

            val timestamp = model.time.toLong() // 将时间戳字符串转换为长整型
            val time = Date.from(Instant.ofEpochSecond(timestamp)) // 使用 Instant 类转换为 Date 对象
            calendar.time = time
            // 舍弃分钟数为 10 的倍数以外的部分，进行四舍五入
            val minute = calendar.get(Calendar.MINUTE)
            val roundedMinute = (minute / 10.0).roundToInt() * 10
            calendar.set(Calendar.MINUTE, roundedMinute.toInt())
            calendar.set(Calendar.SECOND, 0)
            calendar.set(Calendar.MILLISECOND, 0)

            // 查找对应的时间节点并更新值
            val index = mappedData.indexOfFirst {
                it.time == dateFormat.format(calendar.time)
            }
            if (index != -1) {
                mappedData[index] = ModelBean(model.hdl,model.tg,model.ldl,model.tc,dateFormat.format(calendar.time))
            }
        }
        return mappedData
    }

    fun fillMissingData(dataList: MutableList<ModelBean>, startDate: String, endDate: String): MutableList<ModelBean> {
        val filledDataList = mutableListOf<ModelBean>()

        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        // 解析开始日期和结束日期
        val start = dateFormat.parse(startDate) ?: return filledDataList
        val end = dateFormat.parse(endDate) ?: return filledDataList

        // 初始化日期范围
        val calendar = Calendar.getInstance()
        calendar.time = start

        // 循环遍历日期范围，直到结束日期
        while (!calendar.time.after(end)) {
            val currentDate = calendar.time
            val formattedDate = dateFormat.format(currentDate)

            // 查找数据集合中是否存在当前日期的数据
            val matchingData = dataList.find {

                formattedDate.contains(timestampToMonthDay(it.time.toLong(),"MM-dd"))   }

            // 如果存在匹配的数据，则添加到补全后的列表中
            if (matchingData != null) {
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(ModelBean(0f,0f,0f,0f,formattedDate))
            }

            // 增加一天
            calendar.add(Calendar.DAY_OF_YEAR, 1)
        }

        return filledDataList
    }

    fun fillMissingData(dataList: MutableList<ModelBean>, month: String): MutableList<ModelBean> {
        val filledDataList = mutableListOf<ModelBean>()

        val dateFormat = SimpleDateFormat("MM-dd", Locale.getDefault())

        val calendar = Calendar.getInstance()

        // 设置日历实例的年份和月份
        val yearMonthFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        calendar.time = yearMonthFormat.parse(month) ?: return filledDataList

        // 获取指定月份的天数
        val maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)

        // 循环遍历整个月份的每一天
        for (day in 1..maxDay) {
            calendar.set(Calendar.DAY_OF_MONTH, day)
            val currentDate = calendar.time
            var formattedDate = dateFormat.format(currentDate)

            // 查找数据集合中是否存在当前日期的数据
            val matchingData = dataList.find {
                val time = it.time
                if (time.contains("-")) {
                    formattedDate.equals(time)
                } else {
                    formattedDate.contains(timestampToMonthDay(time.toLong(), "MM-dd"))
                }
            }

            // 如果存在匹配的数据，则添加到补全后的列表中
            if (matchingData != null) {
                matchingData.time = formattedDate.substring(3) // 修改时间格式为 "dd"
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(ModelBean(0f,0f,0f,0f,formattedDate.substring(3)))
            }
        }

        return convertMonthFormat(filledDataList,"week")
    }

    fun   convertMonthFormat(dataList: MutableList<ModelBean>, type: String): MutableList<ModelBean> {
        val convertedDataList = mutableListOf<ModelBean>()

        for (model in dataList) {
            val formattedTime = if (type == "month") {
                getFormattedMonth(model.time.toInt())
            } else {
                getFormattedDay(model.time.toInt())
            }
            val convertedModel =
                ModelBean(model.hdl,model.tg,model.ldl,model.tc,formattedTime)
            convertedDataList.add(convertedModel)
        }

        return convertedDataList
    }

    private fun getFormattedDay(day: Int): String {
        return "${day}日"
    }

    private fun getFormattedMonth(month: Int): String {
        return "${month}月"
    }

    fun fillMissingData(dataList: MutableList<ModelBean>): MutableList<ModelBean> {
        val filledDataList = mutableListOf<ModelBean>()

        // 初始化日期范围
        val calendar = Calendar.getInstance()

        // 循环遍历12个月
        for (month in 1..12) {
            val formattedMonth = String.format("%02d", month)

            // 查找数据集合中是否存在当前月份的数据
            val matchingData = dataList.find {
                timestampToMonthDay(it.time.toLong(),"MM" ) == formattedMonth }

            // 如果存在匹配的数据，则添加到补全后的列表中
            if (matchingData != null) {
                matchingData.time = formattedMonth
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(ModelBean(0f,0f,0f,0f,formattedMonth))
            }
        }

        return convertMonthFormat(filledDataList,"month")
    }

    private fun timestampToMonthDay(timestamp: Long, type :String): String {
        val dateFormat = SimpleDateFormat(type, Locale.getDefault())
        val date = Date(timestamp * 1000L) //
        return dateFormat.format(date)
    }
}

