//
//  AddTicketViewModel.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import Foundation
import Combine
internal import CoreData

class AddTicketViewModel: ObservableObject {
    // 输入字段
    @Published var selectedType: LotteryType = .doubleColorBall
    @Published var numbers: String = ""
    @Published var betCount: Int = 1
    @Published var amountPerBet: String = "2"
    
    // 修改：改为购买日期（默认今天）
    @Published var purchaseDate: Date = Date()
    
    // 修改：开奖日期根据彩票类型自动计算
    var drawDate: Date {
        calculateDrawDate()
    }
    
    // 验证状态
    @Published var isValid: Bool = false
    @Published var errorMessage: String = ""
    
    // 计算属性
    var totalAmount: Float {
        let amount = Int(amountPerBet) ?? 0
        return Float(amount * betCount)
    }
    
    var formattedPurchaseDate: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        return formatter.string(from: purchaseDate)
    }
    
    var formattedDrawDate: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        return formatter.string(from: drawDate)
    }
    
    private var cancellables = Set<AnyCancellable>()
    
    init() {
        setupValidation()
    }
    
    // 计算开奖日期（根据彩票类型）
    private func calculateDrawDate() -> Date {
        let calendar = Calendar.current
        
        switch selectedType {
        case .doubleColorBall:
            // 双色球：每周二、四、日开奖
            return nextDrawDate(for: [2, 4, 7], from: purchaseDate)
            
        case .superLotto:
            // 大乐透：每周一、三、六开奖
            return nextDrawDate(for: [1, 3, 6], from: purchaseDate)
            
        case .welfare3D:
            // 福彩3D：每天开奖
            return calendar.date(byAdding: .day, value: 1, to: purchaseDate) ?? purchaseDate
            
        case .sevenStar:
            // 七星彩：每周二、五、日开奖
            return nextDrawDate(for: [2, 5, 7], from: purchaseDate)
            
        case .other:
            // 其他：默认3天后
            return calendar.date(byAdding: .day, value: 3, to: purchaseDate) ?? purchaseDate
        }
    }
    
    // 计算下一个开奖日期
    private func nextDrawDate(for weekdays: [Int], from date: Date) -> Date {
        let calendar = Calendar.current
        let currentWeekday = calendar.component(.weekday, from: date)
        
        // 查找下一个开奖日
        for weekday in weekdays.sorted() {
            if weekday >= currentWeekday {
                let daysToAdd = weekday - currentWeekday
                return calendar.date(byAdding: .day, value: daysToAdd, to: date) ?? date
            }
        }
        
        // 如果本周没有，取下一周的第一个开奖日
        let daysToAdd = (7 - currentWeekday) + weekdays.min()!
        return calendar.date(byAdding: .day, value: daysToAdd, to: date) ?? date
    }
    
    // 设置表单验证
    private func setupValidation() {
        Publishers.CombineLatest($amountPerBet, $numbers)
            .map { amount, numbers in
                // 金额验证
                guard let amountValue = Double(amount), amountValue > 0 else {
                    return false
                }
                
                // 注数验证
                guard self.betCount > 0 && self.betCount <= 100 else {
                    return false
                }
                
                return true
            }
            .assign(to: \.isValid, on: self)
            .store(in: &cancellables)
    }
    
    // 重置表单
    func resetForm() {
        selectedType = .doubleColorBall
        numbers = ""
        betCount = 1
        amountPerBet = "2.00"
        purchaseDate = Date()
        errorMessage = ""
    }
    
    // 保存彩票记录
    func saveTicket(context: NSManagedObjectContext) -> Bool {
        guard isValid else {
            errorMessage = "请填写完整信息"
            return false
        }
        
        guard let amountValue = Double(amountPerBet), amountValue > 0 else {
            errorMessage = "金额无效"
            return false
        }
        
        let ticket = LotteryTicket(context: context)
        ticket.id = UUID()
        ticket.lotteryType = selectedType
        ticket.numbers = numbers.isEmpty ? "随机" : numbers
        ticket.betCount = Int16(betCount)
        ticket.amount = totalAmount
        ticket.date = purchaseDate  // 使用用户选择的购买日期
        ticket.drawDate = drawDate  // 自动计算的开奖日期
        ticket.ticketStatus = .pending
        ticket.prizeAmount = 0
        
        do {
            try context.save()
            print("✅ 彩票记录保存成功")
            print("   类型: \(selectedType.rawValue)")
            print("   注数: \(betCount)")
            print("   金额: " + Formatters.formatCurrency(totalAmount))
            print("   购买: \(formattedPurchaseDate)")
            print("   开奖: \(formattedDrawDate)")
            return true
        } catch {
            errorMessage = "保存失败: \(error.localizedDescription)"
            print("❌ 保存失败: \(error)")
            context.delete(ticket)
            return false
        }
    }
    
    // 快速填充测试数据
    func fillSampleData() {
        selectedType = LotteryType.allCases.randomElement() ?? .doubleColorBall
        numbers = generateSampleNumbers(for: selectedType)
        betCount = Int.random(in: 1...5)
        amountPerBet = String(format: "%.2f", Double.random(in: 2.0...10.0))
        purchaseDate = Date().addingTimeInterval(Double.random(in: -30...0) * 24 * 3600)
    }
    
    // 生成示例号码
    private func generateSampleNumbers(for type: LotteryType) -> String {
        switch type {
        case .doubleColorBall:
            return "01 05 12 23 28 33 + 09"
        case .superLotto:
            return "03 07 15 20 28 + 02 09"
        case .welfare3D:
            return "1 2 3"
        case .sevenStar:
            return "1 3 5 7 9 2 4"
        case .other:
            return "随机号码"
        }
    }
}
