//
//  ApplePayManager.swift
//  Pods
//
//  Created by Mac 3 on 2025/1/20.
//

import StoreKit

class ApplePayManager: NSObject {
    
    static let shared = ApplePayManager()
    
    private var completion: ((Bool, String?) -> Void)?
    
    var appleGoodId = ""
    
    var appleAccountToken = ""

    var isCheck: Bool = false
    // 是否正在恢复
    var isPaying: Bool = false
    // 是否正在恢复
    var isRestoring: Bool = false
    
    override init() {
        super.init()
        SKPaymentQueue.default().add(self)
    }
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
}

extension ApplePayManager {

    @available(iOS 15.0.0, *)
    func check(appleId: String) async -> Bool {
        print("检查自动续费订单及是否存在试用资格")
        SKPaymentQueue.default().add(self)
        self.isCheck = true

        do {
            // 获取产品信息
            let productIds = [appleId]
            let products = try await Product.products(for: Set(productIds))

            // 检查第一个产品的试用资格
            if let product = products.first {
                return await product.subscription?.isEligibleForIntroOffer ?? false
            }
            return false
        } catch {
            print("Error checking trial eligibility: \(error)")
            return false
        }
    }
    
    // 开始支付
    func startPay(appleId: String, token: String, complete: ((Bool, String?) -> Void)?) {
        
        self.isPaying = true
        self.isCheck = false
        
        // 支付前查询自动续费的订单，将订单置为支付状态
        let transactions = SKPaymentQueue.default().transactions
        if transactions.count > 0 {
            for tran in transactions {
                if tran.transactionState == .purchased {
                    SKPaymentQueue.default().finishTransaction(tran)
                }
            }
        }
        
        appleGoodId = appleId
        appleAccountToken = token
        completion = complete
        
        self.submitIAP()
    }
    
    func restoreAction(complete: ((Bool, String?) -> Void)?) {
        
        // 支付前查询自动续费的订单，将订单置为支付状态
        let transactions = SKPaymentQueue.default().transactions
        if transactions.count > 0 {
            for tran in transactions {
                if tran.transactionState == .purchased {
                    SKPaymentQueue.default().finishTransaction(tran)
                }
            }
        }
        
        self.isPaying = false
        self.isCheck = false
        self.isRestoring = false
        self.completion = complete
        
        print("开始恢复订阅")
        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

extension ApplePayManager: SKPaymentTransactionObserver {
    
    // 提交内购
    func submitIAP() {
        
        if SKPaymentQueue.canMakePayments() {
            
            let payment = SKMutablePayment()
            payment.productIdentifier = self.appleGoodId
            payment.applicationUsername = self.appleAccountToken
            payment.quantity = 1
            SKPaymentQueue.default().add(payment)
        }
    }
    
    // 恢复订阅
    func restoreOrder(transaction: SKPaymentTransaction) {
        
        if isRestoring { return }
        
        if let receiptUrl = Bundle.main.appStoreReceiptURL {
            let receiptData = try? Data(contentsOf: receiptUrl)
            if let receiptString = receiptData?.base64EncodedString(options: .endLineWithLineFeed) {
                debugPrint("receiptString = \(String(describing: receiptString))")
                
                if let completion = self.completion {
                    isRestoring = true
                    completion(true, receiptString)
                }
            }
        }
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
            
        print("监听AppStore支付状态 updatedTransactions")
        
//        if !self.isPaying { return }
        
        DispatchQueue.main.async {
            for tran in transactions {
                switch tran.transactionState {
                    
                case .purchased:
                    print("商品已苹果支付成功")
                    
                    if self.isPaying {
                        if let receiptUrl = Bundle.main.appStoreReceiptURL {
                            let receiptData = try? Data(contentsOf: receiptUrl)
                            if let receiptString = receiptData?.base64EncodedString(options: .endLineWithLineFeed), let completion = self.completion {
                                completion(true, receiptString)
                            }
                        }
                    } else {
                        if let completion = self.completion {
                            completion(false, "")
                        }
                    }
                    
                    SKPaymentQueue.default().finishTransaction(tran)
                case .purchasing:
                    print("正在购买中，商品已添加进列表")
                case .restored:
                    print("恢复订阅")
                    self.restoreOrder(transaction: tran)
                    SKPaymentQueue.default().finishTransaction(tran)
                case .failed:
                    print("商品支付失败")
                    SKPaymentQueue.default().finishTransaction(tran)
                    if let completion = self.completion {
                        completion(false, "")
                    }
                case .deferred:
                    print("未确定")
                    if let completion = self.completion {
                        completion(false, "")
                    }
                default:
                    if let completion = self.completion {
                        completion(false, "")
                    }
                    break
                }
            }
        }
    }
        
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        print("恢复购买失败\(error.localizedDescription)")
    }
}
