//
//  SKUPay.swift
//  SwiftProject
//
//  Created by aaa on 2024/4/1.
//

import Foundation
import StoreKit
import SVProgressHUD
import Firebase
//MARK: - 将货币信息格式化为本地信息
extension SKProduct {
    var regularPrice: String? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = self.priceLocale
        return formatter.string(from: self.price)
    }
}


class SKUPay:NSObject, SKRequestDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver {
    static let sharedInstance:SKUPay = SKUPay()
    var productRequest:SKProductsRequest?
    var productsArr:[SKProduct] = []//存放请求到的商品条目,有效的商品
    var invalidProductIdentifiers:[String] = [] //存放已经无效(过期、被删除等)的商品
    
    
    func setTransactionDic(transactions:[SKPaymentTransaction]?) {
        guard let transactions else {
            UserDefaults.standard.setValue(nil, forKey: "kHistoryTransaction")
            UserDefaults.standard.synchronize()
            return
        }
        
        var arr:[Any] = []
        transactions.forEach { nv in
            var dic:[String:Any] = [:]
            dic["productIdentifier"] = nv.payment.productIdentifier
            dic["transactionState"] = nv.transactionState.rawValue
            arr.append(dic)
        }
        
        UserDefaults.standard.setValue(arr, forKey: "kHistoryTransaction")
        UserDefaults.standard.synchronize()
        setUpUserInfo()
    }
    
    //此处初始化用户信息
    func setUpUserInfo()  {
        //test ----
//        UserDefaults.standard.setValue(nil, forKey: "kHistoryTransaction")
//        UserDefaults.standard.synchronize()
        //test+++++
        let arr:[Any]? = UserDefaults.standard.value(forKey: "kHistoryTransaction") as? [Any] ?? nil
        guard let arr else {
            return
        }
        
        arr.forEach { item in
            let it = item as! [String:Any]
            let productIdentifier = it["productIdentifier"] as? String
            let stateRawValue = it["transactionState"] as? Int
            let state =  SKPaymentTransactionState(rawValue:stateRawValue ?? 2)
            if (state == .purchased || state == .restored) {//检查到用户有购买
                UserInfo.sharedInstance.paymentState = true
                UserInfo.sharedInstance.paymentProductIdentifier = productIdentifier
            }
        }
    }
    
    override init() {
        super.init()
        print("初始化内购管理对象....")
        SKPaymentQueue.default().add(self)
    }
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
    
    //MARK: - 拉取商品信息
    func requestProducts(productsIdentifiers:[String]) {
        let pitSet = Set(productsIdentifiers)
        productRequest = SKProductsRequest(productIdentifiers: pitSet)
        productRequest?.delegate = self
        productRequest?.start()
        
    }
    
    //MARK: - 支付
    func pay(productIdentifier:String) {
        if !self.productsArr.isEmpty {
            let product = self.productsArr.filter {
                $0.productIdentifier == productIdentifier
            }.first
            if let pd = product {
                let payment = SKPayment(product: pd)
                SKPaymentQueue.default().add(payment)
                showToast(value: true)
            }
        }
    }
    
    //MARK: - 恢复购买
    func restoreProducts() {
        SKPaymentQueue.default().restoreCompletedTransactions()
        showToast(value: true)
    }
    
    //是否显示加载信息...
    func showToast(value:Bool) {
        DispatchQueue.main.async {
            if value {
                SVProgressHUD.show(withStatus: NSLocalizedString("支付中...", comment: ""))
            }
            else {
                SVProgressHUD.dismiss()
            }
        }
        
    }
    
    
    //MARK: - 验单
    func checkPay() {
        //.....
    }
    
    ////////////////////////////////////////Delegate///////////////////////////////////////////////////
    
    //MARK: - SKProductsRequestDelegate 商品信息拉取回调
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse){
        self.productsArr.removeAll()
        if !response.products.isEmpty {
            print("恭喜,获取到了有效商品信息.....iap")
            self.productsArr.append(contentsOf: response.products)
        }
        
        self.invalidProductIdentifiers.removeAll()
        if !response.invalidProductIdentifiers.isEmpty {
            print("很遗憾,商品信息还未生效:\n\(response.invalidProductIdentifiers)")
            self.invalidProductIdentifiers.append(contentsOf: response.invalidProductIdentifiers)
        }
    }
    
    
    //MARK: - SKPaymentTransactionObserver 交易信息回调
    
    // Sent when the transaction array has changed (additions or state changes).  Client should check state of transactions and finish as appropriate.
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){
        if !transactions.isEmpty {
//            self.historyPaymentTransactions = transactions
            self.setTransactionDic(transactions: transactions)
            
            transactions.forEach { spt in
                if spt.transactionState == .purchased || spt.transactionState == .restored {
                    queue.finishTransaction(spt)
                }
                print("updatedTransactions ..\(spt)")
            }
        }
        showToast(value: false)
        print("updatedTransactions ..")
    }

    
    // Sent when transactions are removed from the queue (via finishTransaction:).
//    func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]){
//        
//    }

    
    // Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error){
        print("restoreCompletedTransactionsFailedWithError...")
        showToast(value: false)
        Analytics.logEvent("Payment_fail", parameters: nil)
    }

    
    // Sent when all transactions from the user's purchase history have successfully been added back to the queue.
    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue){
//        queue.transactions
        print("paymentQueueRestoreCompletedTransactionsFinished...")
        showToast(value: false)
        Analytics.logEvent("Payment_success", parameters: nil)
    }
    
    // Sent when a user initiates an IAP buy from the App Store
//    func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool{
//        return true
//    }

    
    func paymentQueueDidChangeStorefront(_ queue: SKPaymentQueue){
        print("paymentQueueDidChangeStorefront..")
    }

    
    // Sent when entitlements for a user have changed and access to the specified IAPs has been revoked.

    func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]){
        print("didRevokeEntitlementsForProductIdentifiers..")
    }
    
}
