package com.xty.network.model

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.text.isDigitsOnly
import com.blankj.utilcode.util.LogUtils
import com.xty.network.utils.TimeTransformUtils
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt

/*
var respiratory:String?=null
var time:String?=null

var avg=0
var max=0
var min=0
*/
data class BreathBean(
    var model: MutableList<Model>,
    var value: Value
) {

    data class Model(
        var respiratory: Float,
        var time: String,
        var timeValue: Long = 0
    )

    data class Value(
        var avg: Int = 0,
        var max: Int = 0,
        var min: Int = 0

    )


    @RequiresApi(Build.VERSION_CODES.O)
    fun mapDataToTimeNodes(dataList: MutableList<Model>): MutableList<Model> {
        if (dataList.isEmpty()) {
            return mutableListOf()
        }

        val calendarMin = Calendar.getInstance()
        calendarMin.timeInMillis = dataList[0].time.toLong() * 1000

        val mappedData = mutableListOf<Model>()
        val dateFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
        // 创建一天的时间节点
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, calendarMin.get(Calendar.MINUTE))
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
//        val startTime = calendar.time

        calendar.add(Calendar.DAY_OF_MONTH, 1)
        calendar.add(Calendar.MINUTE, -1)
//        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
        }
        var (startTime, endTime) = TimeTransformUtils.calculateStartTimeAndEndTime(
            dataList[0].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(
                Model(
                    Float.NaN,
                    dateFormat.format(currentTime),
                    currentTime.time
                )
            )
            calendar.time = currentTime
            calendar.add(Calendar.MINUTE, 10)
            currentTime = calendar.time
        }
//        val timestamp = 1688631900L
//        val time = Date(timestamp * 1000)
        // 将数据集合中的时间映射到时间节点上
        for (model in dataList) {
            calendar.timeInMillis = model.time.toLong() * 1000

//            val timestamp = model.time.toLong() // 将时间戳字符串转换为长整型
//            val time = Date.from(Instant.ofEpochSecond(timestamp)) // 使用 Instant 类转换为 Date 对象
//            calendar.time = time
//
////            val timeStr = model.time
////            val time = dateFormat.parse(timeStr) // 将字符串转换为 Date 类型
////            calendar.time = time as Date
//
//            // 舍弃分钟数为 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 time = model.time.toLong() * 1000
            var mIndex = -1
            run breaking@{
                for (i in 0 until mappedData.size) {
                    if (mappedData[i].timeValue == time) {
                        mIndex = i
                        return@breaking
                    } else if (time >= (mappedData[i].timeValue - 5 * 60 * 1000) && time <= (mappedData[i].timeValue + 4 * 60 * 1000)) {
                        mIndex = i
                        return@breaking
                    }
                    mIndex = -1
                }
            }


            if (mIndex != -1) {
                val time = mappedData[mIndex].time
                val lowDbp = model.respiratory

                mappedData[mIndex] =
                    Model(lowDbp, time)
            }
            /*val index = mappedData.indexOfFirst {
                it.time == dateFormat.format(calendar.time)
            }
            if (index != -1) {
                val time = dateFormat.format(calendar.time)
                val lowDbp = model.respiratory

                mappedData[index] =
                    Model(lowDbp, time)
            }*/
        }
        return mappedData
    }

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

        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

        // 循环遍历日期范围，直到结束日期
        //  var i=0
        while (!calendar.time.after(end)) {

            val currentDate = calendar.time
            val formattedDate = dateFormat.format(currentDate)

            // 查找数据集合中是否存在当前日期的数据

            var matchingData = dataList.find { getZeroTimeStamp(it.time) == calendar.time.time }

            // 如果存在匹配的数据，则添加到补全后的列表中
            if (matchingData != null) {
                matchingData.time = dateFormat.format(Date(matchingData.time.toLong() * 1000))
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(Model(Float.NaN, formattedDate))
            }

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

        return filledDataList
    }

    /**
     * 获取当前时间戳在当天0点的时间戳
     */
    private fun getZeroTimeStamp(timeMillis: String): Long {
        if (timeMillis.isEmpty()) {
            LogUtils.w("getZeroTimeStamp,timeMillis is empty")
            return 0
        }
        if (!timeMillis.isDigitsOnly()) {
            LogUtils.w("getZeroTimeStamp,timeMillis is not digits")
            return 0
        }
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timeMillis.toLong() * 1000

        // 设置时间部分为零
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)

        return calendar.timeInMillis
    }

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

        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

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

        // 如果是时间是今天，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.MONTH) == now.get(Calendar.MONTH)
        ) {
            maxDay = now.get(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
                filledDataList.add(matchingData)
            } else {
                // 不存在匹配的数据，则添加一个值为0的数据
                filledDataList.add(Model(Float.NaN, formattedDate))
            }
        }

        return filledDataList
    }

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

        // 初始化日期范围
        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(Model(Float.NaN, formattedMonth))
            }
        }

        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)
    }
}