package com.xty.network.model

import android.os.Build
import androidx.annotation.RequiresApi
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 BloodFatBean(
    val model: MutableList<Model>,
    val value: Value,
) {
    var tcTempData: MutableList<ModelCompare> = mutableListOf()
    var tgTempData: MutableList<ModelCompare> = mutableListOf()
    var hdlTempData: MutableList<ModelCompare> = mutableListOf()
    var ldlempData: MutableList<ModelCompare> = mutableListOf()


    var tcModel: MutableList<ModelCompare> = mutableListOf()
        get() {
            val tcList = mutableListOf<ModelCompare>()
            model.forEach {
                tcList.add(ModelCompare(it.tc, it.time))
            }
            return tcList
        }

    var tgModel: MutableList<ModelCompare> = mutableListOf()
        get() {
            val tgList = mutableListOf<ModelCompare>()
            model.forEach {
                tgList.add(ModelCompare(it.tg, it.time))
            }
            return tgList
        }

    var ldlModel: MutableList<ModelCompare> = mutableListOf()
        get() {
            val ldlList = mutableListOf<ModelCompare>()
            model.forEach {
                ldlList.add(ModelCompare(it.ldl, it.time))
            }
            return ldlList
        }

    var hdlModel: MutableList<ModelCompare> = mutableListOf()
        get() {
            val hdlList = mutableListOf<ModelCompare>()
            model.forEach {
                hdlList.add(ModelCompare(it.hdl, it.time))
            }
            return hdlList
        }

    data class Model(
        var hdl: Float,
        var ldl: Float,
        var tc: Float,
        var tg: Float,
        var time: String
    )

    data class Value(
        val avgHdl: Float,
        val avgLdl: Float,
        val avgTc: Float,
        val avgTg: Float,
        val maxHdl: Float,
        val maxLdl: Float,
        val maxTc: Float,
        val maxTg: Float,
        val minHdl: Float,
        val minLdl: Float,
        val minTc: Float,
        val minTg: Float
    )

    data class ModelCompare(
        var uaValue: Float,
        var time: String,
        var formatTime: String = "",
        var index: Int = 0
    )


    @RequiresApi(Build.VERSION_CODES.O)
    fun mapDataToTime(dataList: MutableList<ModelCompare>): MutableList<ModelCompare> {
        if (dataList.isEmpty()) {
            return mutableListOf()
        }
        val mappedData = mutableListOf<ModelCompare>()
        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)
        val endTime = calendar.time

        // 初始化时间节点和默认值
        var currentTime = startTime
        while (currentTime <= endTime) {
            mappedData.add(
                ModelCompare(
                    0f,
                    dateFormat.format(currentTime),
                    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] = ModelCompare(
                    model.uaValue,
                    dateFormat.format(calendar.time),
                    dateFormat.format(calendar.time)
                )
            }
        }
        return mappedData
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun mapDataToTimeNodes(dataList: MutableList<ModelCompare>): MutableList<ModelCompare> {
        val mappedData = mutableListOf<ModelCompare>()
        // 将数据集合中的时间映射到时间节点上
        for (model in dataList) {
            mappedData.add(
                ModelCompare(
                    model.uaValue,
                    model.time,
                    timestampToMonthDay(model.time.toLong(), "HH:mm")
                )
            )
        }
        return mappedData
    }

    fun fillMissingData(
        dataList: MutableList<ModelCompare>,
        month: String
    ): MutableList<ModelCompare> {
        if (dataList.isEmpty()) {
            return mutableListOf()
        }
        val filledDataList = mutableListOf<ModelCompare>()

        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.formatTime = formattedDate
                matchingData.time = formattedDate.substring(3) // 修改时间格式为 "dd"
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(ModelCompare(0f, formattedDate.substring(3), formattedDate))
            }
        }

        return convertMonthFormat(filledDataList, "week")
    }


    fun fillMissingData(
        dataList: MutableList<ModelCompare>,
        startDate: String,
        endDate: String
    ): MutableList<ModelCompare> {
        if (dataList.isEmpty()) {
            return mutableListOf()
        }
        val filledDataList = mutableListOf<ModelCompare>()

        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) {
                matchingData.formatTime =
                    timestampToMonthDay(matchingData.time.toLong(), "yyyy-MM-dd")
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(ModelCompare(0f, formattedDate, formattedDate))
            }

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

        return filledDataList
    }

    private fun timestampToMonthDay(timestamp: Long, type: String): String {
        val dateFormat = SimpleDateFormat(type, Locale.getDefault())
        val date = Date(timestamp * 1000L) // 将时间戳转换为毫秒
        return dateFormat.format(date)
    }

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

        for (model in dataList) {
            val formattedTime = if (type == "month") {
                getFormattedMonth(model.time.toInt())
            } else {
                getFormattedDay(model.time.toInt())
            }
            val convertedModel =
                ModelCompare(model.uaValue, formattedTime, model.formatTime)
            convertedDataList.add(convertedModel)
        }

        return convertedDataList
    }

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

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

    fun fillMissingData(dataList: MutableList<ModelCompare>): MutableList<ModelCompare> {
        if (dataList.isEmpty()) {
            return mutableListOf()
        }
        val filledDataList = mutableListOf<ModelCompare>()

        // 初始化日期范围
        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(ModelCompare(0f, formattedMonth))
            }
        }
        return filledDataList
    }
}



