//
//  TSPUrChaseTool.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/6/10.
//

private let kFreeNumKey = "kFreeNumKey"
private let kTotalUseNumKey = "kTotalUseNumKey"

public enum VipFreeNumType: String, CaseIterable {
    case none = "kNone"
    case general = "kGeneralAI" //通用的 vip
}

let kPurchaseBusiness = TSPurchaseBusiness.shared
class TSPurchaseBusiness {
    static let shared = TSPurchaseBusiness()
    public var totalUsedTimes: Int = 0
    // 免费使用会员的次数
    var freeDict:[String:Int] = [:]
    
    
    init() {
        initializeForFree()
    }
    
    var isVip:Bool{
        return PurchaseManager.default.isVip
    }
    
    var vipType:PremiumPeriod{
        return PurchaseManager.default.vipType
    }
    
    public var isOverTotalTimes: Bool {
        if isVip {
            loadTotalUse()
            #if DEBUG
                    return false
            #endif
            return totalUsedTimes >= vipType.freeNumber
        }
        return false
    }
    
    /// 使用一次免费次数
    func useOnceForFree(type:VipFreeNumType){
        var freeNum = freeDict[type.rawValue] ?? 0
        if freeNum > 0 {
            freeNum-=1
        }
        
        if freeNum < 0 {
            freeNum = 0
        }
        
        freeDict[type.rawValue] = freeNum
        saveForFree()
        
        NotificationCenter.default.post(name: .kVipFreeNumChanged, object: nil, userInfo: ["VipFreeNumType": type])
    }
    
    func freeNum(type:VipFreeNumType) -> Int{
        let freeNum = freeDict[type.rawValue] ?? 0
        return freeNum
    }
    
    func saveForFree(){
        UserDefaults.standard.set(freeDict, forKey: kFreeNumKey)
        UserDefaults.standard.synchronize()
    }
    
    func loadTotalUse() {
        // 当天没记录，设置默认次数
        guard let dict = UserDefaults.standard.dictionary(forKey: kTotalUseNumKey),
              dict.safeString(forKey: "date") == Date().dateDayString else {
            totalUsedTimes = 0
            return
        }
        // 有记录，设置已经使用次数
        totalUsedTimes = dict.safeInt(forKey: "times")
    }
    
    func initializeForFree(){
        if let dict = UserDefaults.standard.dictionary(forKey: kFreeNumKey) as? [String:Int]{
            freeDict = dict
        }else{
            freeDict = [
                VipFreeNumType.general.rawValue:1
            ]
            saveForFree()
        }
    }
    
    /// 免费次数是否可用
    func freeNumAvailable(type:VipFreeNumType) -> Bool{
        if isVip == true {
            return true
        }else{
            if let freeNum = freeDict[type.rawValue],freeNum > 0 {
                return true
            }
        }
        return false
    }
    
    /// 是否展示生成类的会员图标
    func generateVipShow(type:VipFreeNumType) -> Bool{
        if isVip == false, freeNum(type: type) > 0 {
            return false
        }
        return true
    }
}
extension TSPurchaseBusiness{
    
    
    func launchPrchase() {
        PurchaseManager.default.password = "4a0575c1dde64878b81b5642f82104ea"
        PurchaseManager.default.purchaseProducts = [
            PurchaseProduct(productId: "801", period:.week),
            PurchaseProduct(productId: "802", period:.month)
        ]
        
        PurchaseManager.default.requestProducts()
        
    }
    
}

extension TSPurchaseBusiness{
    func kJudgeVipFreeType(vipFreeNumType:VipFreeNumType,
                   vc:UIViewController? = nil,
                   closePageBlock:(()->Void)? = nil) -> Bool {
        //判断 vip
        return kJudgeVip(externalBool: kPurchaseBusiness.freeNumAvailable(type: vipFreeNumType) == false, vc: vc,closePageBlock: closePageBlock)
    }
    
    func kJudgeVip(externalBool:Bool,//(externalBool)功能是否需要vip
                   vc:UIViewController? = nil,
                   closePageBlock:(()->Void)? = nil) -> Bool {
        //判断 vip
        if externalBool,
           self.isVip == false
        {
            if let vc = vc {
                TSPurchaseVC.show(target: vc,closePageBlock: nil)
            }else if let rootVC = WindowHelper.getRootViewController() {
                TSPurchaseVC.show(target: rootVC,closePageBlock: nil)
            }
            
            return true
        }
        return false
    }
}
