import Foundation
internal import CoreData
import SwiftUI
import Combine

class HomeViewModel: ObservableObject {
    // 发布统计数据
    @Published var totalSpent: Float = 0
    @Published var totalProfit: Float = 0
    @Published var totalTickets: Int = 0
    @Published var winningTickets: Int = 0
    @Published var pendingTickets: Int = 0
    @Published var lostTickets: Int = 0
    @Published var groupedTickets: [Date: [LotteryTicket]] = [:]
    
    private var viewContext: NSManagedObjectContext
    
    init(context: NSManagedObjectContext) {
        self.viewContext = context
        refreshData()
    }
    
    // 刷新所有统计数据
    func refreshData() {
        let request = LotteryTicket.fetchRequest()
        
        do {
            let tickets = try viewContext.fetch(request)
            
            // 计算统计数据
            totalTickets = tickets.count
            totalSpent = tickets.reduce(0) { $0 + $1.amount }
            
            let totalPrize = tickets.reduce(0) { $0 + $1.prizeAmount }
            totalProfit = totalPrize - totalSpent
            
            winningTickets = tickets.filter { $0.ticketStatus == .won }.count
            pendingTickets = tickets.filter { $0.ticketStatus == .pending }.count
            lostTickets = tickets.filter { $0.ticketStatus == .lost }.count
            
            // 按日期分组
            let calendar = Calendar.current
            groupedTickets = Dictionary(grouping: tickets) { ticket in
                calendar.startOfDay(for: ticket.date ?? Date())
            }
            
        } catch {
            print("❌ 获取数据失败: \(error)")
        }
    }
    
    // 获取日期分组后的排序键（按日期倒序）
    var sortedDates: [Date] {
        groupedTickets.keys.sorted(by: >)
    }
    
    // 获取特定日期的记录
    func ticketsForDate(_ date: Date) -> [LotteryTicket] {
        groupedTickets[date] ?? []
    }
    
    // 修改：将 formattedDate 改为一个返回闭包的计算属性
    var formattedDate: (Date) -> String {
        return { date in
            let formatter = DateFormatter()
            
            if Calendar.current.isDateInToday(date) {
                return "今天"
            } else if Calendar.current.isDateInYesterday(date) {
                return "昨天"
            } else {
                let formateYear = Calendar.current.component(.year, from: Date())
                let currentYear = Calendar.current.component(.year, from: date)
                
                formatter.dateFormat = (currentYear == formateYear) ? "MM月dd日" : "yyyy年MM月dd日"
                return formatter.string(from: date)
            }
        }
    }
}
