import SwiftUI

struct BarChartView: View {
    let compassManager: CompassManager
    @State private var altitudeData: [String: Double] = [:] // 日期和海拔值的字典
    @State private var maxChartHeight: CGFloat = 200
    @State private var currentDate: String = ""
    @State private var maxAltitudeToday: Double = 0.0
    private let minBarHeight: CGFloat = 5 // 非零值的最小条形高度
    private let maxAltitude: Double = 500 // 最大海拔（例如）
    private let spacew: CGFloat = 10

    var body: some View {
        GeometryReader { geometry in
            let barWidth = geometry.size.width / CGFloat(7) - spacew // 动态计算条形宽度
            
            HStack(alignment: .bottom, spacing: spacew) {
                ForEach(getLastSevenDays(), id: \.self) { date in
                    VStack {
                        let altitude = altitudeData[date, default: 0.0]
                        Text("\(Int(altitude))")
                            .font(.caption)
                        Rectangle()
                            .fill(Color.customblue)
                            .frame(width: barWidth, height: barHeight(for: altitude))
                            .animation(.easeOut(duration: 0.5), value: altitude)
                        Text(date)
                            .font(.caption)
                            .fixedSize(horizontal: true, vertical: false)
                    }
                }
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
            .onAppear {
                compassManager.loadaltimeterandhealth()
                maxChartHeight = geometry.size.height
                loadAltitudeData()
                currentDate = Date().todayDateString()
                updateTodayAltitude() // 确保更新当天的海拔数据
                updatePastDates()
            }
            .onChange(of: compassManager.altitude) { newAltitude in
                updateMaxAltitude(newAltitude)
            }
        }
        .onChange(of: altitudeData) { _ in
            saveAltitudeData(altitudeData)
        }
    }

    private func barHeight(for altitude: Double) -> CGFloat {
        guard altitude > 0 else { return minBarHeight }
        let scaledHeight = CGFloat(altitude) / CGFloat(maxAltitude) * maxChartHeight
        return max(scaledHeight, minBarHeight)
    }

    // 获取过去 7 天的日期
    private func getLastSevenDays() -> [String] {
        var dates: [String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM.dd"
        let today = Date()
        for offset in 0..<7 {
            let date = Calendar.current.date(byAdding: .day, value: -offset, to: today)!
            let dateString = dateFormatter.string(from: date)
            dates.append(dateString)
        }
        return dates.reversed() // 最近的日期在前面
    }

    // 从 UserDefaults 加载数据
    private func loadAltitudeData() {
        if let savedData = UserDefaults.standard.dictionary(forKey: "altitudeData") as? [String: Double] {
            altitudeData = savedData
            let today = Date().todayDateString()
                maxAltitudeToday = altitudeData[today] ?? 0.0
                currentDate = today // 初始化当前日期
            
        }
    }

    // 保存数据到 UserDefaults
    private func saveAltitudeData(_ newAltitudeData: [String: Double]) {
        UserDefaults.standard.set(newAltitudeData, forKey: "altitudeData")
    }

    // 更新今天的海拔数据
    private func updateTodayAltitude() {
        let today = Date().todayDateString()
        let currentAltitude = compassManager.altitude
        if let existingAltitude = altitudeData[today] {
            altitudeData[today] = max(existingAltitude, currentAltitude)
        } else {
            altitudeData[today] = currentAltitude
        }
        // 更新 maxAltitudeToday
        maxAltitudeToday = altitudeData[today] ?? 0.0
    }

    // 更新过去 7 天的海拔数据
    private func updatePastDates() {
        let pastDates = getLastSevenDays()
        for date in pastDates {
            if altitudeData[date] == nil {
                altitudeData[date] = 0.0 // 初始化未记录的日期的海拔值
            }
        }
    }

    // 更新今天的最大海拔值
    private func updateMaxAltitude(_ newAltitude: Double) {
        if Date().todayDateString() == currentDate {
            // 更新今天的最大海拔值
            maxAltitudeToday = max(maxAltitudeToday, newAltitude)
            altitudeData[currentDate] = maxAltitudeToday
        } else {
            // 日期改变，保存昨天的数据并更新当前日期
            currentDate = Date().todayDateString()
            maxAltitudeToday = newAltitude // 重置为新海拔值
            altitudeData[currentDate] = maxAltitudeToday
        }
        // 更新当前条形图的最大值
        altitudeData[currentDate] = maxAltitudeToday
        saveAltitudeData(altitudeData)
    }
}


struct BarChartView_Previews: PreviewProvider {
    static var previews: some View {
        BarChartView(compassManager: CompassManager())
    }
}
