//
//  ICPurchaseManager
//  ICPurchaseManager
//
//  Created by Mazy on 2020/6/10.
//  Copyright © 2020 Mazy. All rights reserved.
//

import UIKit
import SwiftyStoreKit

class ICPurchaseManager: NSObject {
    
    @objc class func purchaseWithProductId(productId: String, inView: UIView, success: @escaping(()->Void) ,faliure: @escaping(()->Void)) {
        
        let productIdentifier = productId
        
        print(productIdentifier)
        
        let hud = MBProgressHUD.showAdded(to: inView, animated: true)
        SwiftyStoreKit.purchaseProduct(productId, quantity: 1, atomically: true) { result in
            hud.hide(animated: true)
            switch result {
            case .success(let product):
                print("Purchase Success: \(product.productId)")
                
                let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ed0f68aca7964038a5cdf2a68c8c35c4")
                let hud = MBProgressHUD.showAdded(to: inView, animated: true)
                SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
                    hud.hide(animated: true)
                    if case .success(let receipt) = result {
                        let purchaseResult = SwiftyStoreKit.verifySubscription(
                            ofType: .autoRenewable,
                            productId: productId,
                            inReceipt: receipt)
                        
                        switch purchaseResult {
                        case .purchased(let expiryDate, _):
                            print("Product is valid until \(expiryDate)")
                            let dateFormatter = DateFormatter()
                            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                            let dateStr = dateFormatter.string(from: expiryDate)
                            UserDefaults.standard.set(dateStr, forKey: "expiryDate")
                            if product.needsFinishTransaction {
                                SwiftyStoreKit.finishTransaction(product.transaction)
                            }
//                            success()
                        case .expired(let expiryDate, _):
                            
                            MBProgressHUD.showError(NSLocalizedString("ProductIsExpired", comment: "Product is expired"), to: inView)
                            print("Product is expired since \(expiryDate)")
                        case .notPurchased:
                            print("This product has never been purchased")
                        }
                        
                    } else {
                        // receipt verification error
                    }
                }
                
                let receiptData = SwiftyStoreKit.localReceiptData
                let receiptString = receiptData?.base64EncodedString(options: []) ?? ""
                print("receiptString: \(receiptString)")
                
                /*
                 receipt_data：不传的话 服务器根本没法校验
                 product_id：这个也不用解释 内购产品编号 你不传的话 服务器不知道你买的哪个订单
                 transaction_id：这个是交易编号
                 */
                // 需要验证
                let dict = ["productId": product.productId, "transactionId" : (product.transaction.transactionIdentifier ?? ""), "receiptData" : receiptString]
                print("productId transactionId receiptData: \(dict)")
                print("localizedPrice: \(product.product.localizedPrice ?? ""), price: \(product.product.price), priceLocale: \(product.product.priceLocale.currencyCode)")
                // TODO: 服务器验证
                let innerHud = MBProgressHUD.showAdded(to: inView, animated: true)
                ZTNetworkTools.shared().post(withBodyAction: iosIPAVerifyReceipt,
                                             parameters: [
                                                          "price" : product.product.price,
                                                          "priceLocale" : product.product.priceLocale.currencyCode ?? ""],
                                             body: dict, success: { (data) in
                    innerHud.hide(animated: true)

                    print("success----iosIPAVerifyReceipt-----------------\(data)------")
                    if let dict = data as? [String:Any] {
                        if let result = dict["result"] as? [String:Any] {
                            if let data = result["data"] as? [String:Any] {
                                print("SwiftyStoreKit---1-\(data)")
                                if let status = data["status"] as? Bool {
                                    print("SwiftyStoreKit--2--\(status)")
                                    if status {
                                        print("SwiftyStoreKit--3--\(status)")
                                        if product.needsFinishTransaction {
                                            SwiftyStoreKit.finishTransaction(product.transaction)
                                        }
                                        print("Purchase Success: \(product.productId)")
                                        success()
                                    } else {
                                        
                                        MBProgressHUD.showError(NSLocalizedString("UnknownError", comment: "Unknown Error"))
                                    }
                                }else {
                                    MBProgressHUD.showError(NSLocalizedString("UnknownError", comment: "Unknown Error"))
                                }
                            }else {
                                MBProgressHUD.showError(NSLocalizedString("UnknownError", comment: "Unknown Error"))
                            }
                        }else {
                            MBProgressHUD.showError(NSLocalizedString("UnknownError", comment: "Unknown Error"))
                        }
                    }else {
                        MBProgressHUD.showError(NSLocalizedString("UnknownError", comment: "Unknown Error"))
                    }
                }) { (error) in
                    innerHud.hide(animated: true)
                    faliure();
                }

            case .error(let error):
                faliure();
                hud.hide(animated: true);
                switch error.code {
                case .unknown:
                    print("Unknown error. Please contact support")
                    MBProgressHUD.showError(NSLocalizedString("ConnectToiTunesStoreFail", comment: "Connect To iTunes Store Fail")) //"无法连接到 iTunes Store, 请稍后再试")ConnectToiTunesStoreFail
                case .paymentCancelled:
                    MBProgressHUD.showError(NSLocalizedString("CancelledThePurchase", comment: "Cancelled The Purchase")) // "您已取消购买")CancelledThePurchase
                case .paymentInvalid:
                    MBProgressHUD.showError(NSLocalizedString("TryAgainLater", comment: "Try Again Later"))//"无法购买, 请稍后重试")
                    print("The purchase identifier was invalid")
                case .clientInvalid: print("Not allowed to make the payment")
                case .paymentNotAllowed: print("The device is not allowed to make the payment")
                case .storeProductNotAvailable: print("The product is not available in the current storefront")
                case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
                case .cloudServiceNetworkConnectionFailed:
                    MBProgressHUD.showError(NSLocalizedString("UnableConnectNetwork", comment: "Unable Connect Network")) //"无法连接到网络")//UnableConnectNetwork
                    print("Could not connect to the network")
                case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
                default: print((error as NSError).localizedDescription)
                }
            }
        }
    }
    
    /// 静态初始化
    @objc class func launchWithSwiftyStoreKit(success: @escaping(()->Void)) {
        
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    // Deliver content from server, then:
                    let receiptData = SwiftyStoreKit.localReceiptData
                    let receiptString = receiptData?.base64EncodedString(options: []) ?? ""
                    
                    print("Purchase Success: \(purchase.productId.description) receiptString: \(receiptString)")
                    
                    // TODO: 服务器验证
//                    if purchase.needsFinishTransaction {
                        //                        let receiptData = SwiftyStoreKit.localReceiptData
                        //                        let receiptString = receiptData?.base64EncodedString(options: []) ?? ""
                        let dict = ["productId": purchase.productId, "transactionId" : (purchase.transaction.transactionIdentifier ?? ""), "receiptData" : receiptString]
                        print("productId transactionId receiptData: \(dict)")
                        // TODO: 服务器验证
                        ZTNetworkTools.shared().post(withBodyAction: iosIPAVerifyReceipt, parameters: [:], body: dict, success: { (data) in
                            print("success----iosIPAVerifyReceipt-----------------\(data)------")
                            if let dict = data as? [String:Any] {
                                if let result = dict["result"] as? [String:Any] {
                                    if let data = result["data"] as? [String:Any] {
                                        print("SwiftyStoreKit---1-\(data)")
                                        if let status = data["status"] as? Bool {
                                            print("SwiftyStoreKit--2--\(status)")
                                            if status {
                                                print("SwiftyStoreKit--3--\(status)")
                                                if purchase.needsFinishTransaction {
                                                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                                                }
                                                success()
                                                print("Purchase Success: \(purchase.productId)")
                                            }
                                        }
                                    }
                                }
                            }
                        }) { (error) in
                            print("\(error)")
                        }
//                    }
                // Unlock content
                case .failed, .purchasing, .deferred:
                break // do nothing
                @unknown default:
                    break
                }
            }
        }
    }
    
    class func forceFetchReceipt(product: PurchaseDetails) {
        SwiftyStoreKit.fetchReceipt(forceRefresh: true) { result in
            switch result {
            case .success(let receiptData):
                let encryptedReceipt = receiptData.base64EncodedString(options: [])
                print("Fetch receipt success:\n\(encryptedReceipt)")
                // fetch content from your server, then:
                if product.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(product.transaction)
                }
            case .error(let error):
                print("Fetch receipt failed: \(error)")
            }
        }
    }
    
    // 恢复购买
    @objc class func restorePurchases(success: @escaping(()->Void), toView: UIView) {
        let hud = MBProgressHUD.showAdded(to: UIApplication.shared.delegate!.window!!, animated: true)
        SwiftyStoreKit.restorePurchases(atomically: true) { results in
            hud.hide(animated: true);
            if results.restoreFailedPurchases.count > 0 {
                print("Restore Failed: \(results.restoreFailedPurchases)")
            } else if results.restoredPurchases.count > 0 {
                
                let sortedResults = results.restoredPurchases.sorted { (purchase1, purchase2) -> Bool in
                    if let date1 = purchase1.transaction.transactionDate, let data2 = purchase2.transaction.transactionDate {
                        return date1.compare(data2) == .orderedAscending
                    }
                    return false
                }
                print("Restore sortedResults: \(sortedResults)")
                
                if let purchase = sortedResults.last {
                    let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ed0f68aca7964038a5cdf2a68c8c35c4")
                    let hud = MBProgressHUD.showAdded(to: UIApplication.shared.delegate!.window!!, animated: true)
                    SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
                        hud.hide(animated: true)
                        if case .success(let receipt) = result {
                            let purchaseResult = SwiftyStoreKit.verifySubscription(
                                ofType: .autoRenewable,
                                productId: purchase.productId,
                                inReceipt: receipt)
                            
                            switch purchaseResult {
                            case .purchased(let expiryDate, _):
                                print("Product is valid until \(expiryDate)")
                                let dateFormatter = DateFormatter()
                                dateFormatter.locale = Locale(identifier: "en_CN")
                                dateFormatter.timeZone = TimeZone.current
                                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
                                let dateStr = dateFormatter.string(from: expiryDate)
                                UserDefaults.standard.set(dateStr, forKey: "expiryDate")
                                //RestoreSuccess
                                MBProgressHUD.showSuccess(NSLocalizedString("RestoreSuccess", comment: "Restore Success"), to: toView)
                                if purchase.needsFinishTransaction {
                                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                                }
                                success()
                            case .expired(let expiryDate, _):
                                print("Product is expired since \(expiryDate)")
//                                MBProgressHUD.showError("订阅已过期，请重新获取", to: toView)
                                MBProgressHUD.showError(NSLocalizedString("ProductIsExpired", comment: "Product is expired"), to: toView)
                            case .notPurchased:
                                print("This product has never been purchased")
                            }
                        } else {
                            // receipt verification error
                        }
                    }
                    
                    print("Restore Success: \(results.restoredPurchases)")
        
                }
                
            } else {
                //NoProductToRestore
                MBProgressHUD.showError(NSLocalizedString("NoProductToRestore", comment: "No Product To Restore"))
                print("Nothing to Restore")
            }
        }
    }
}
