//
//  SHStoreManager.swift
//  CleanMaster
//
//  Created by Mazy on 2020/8/20.
//  Copyright © 2020 CleanMaster. All rights reserved.
//

import UIKit
import SwiftyStoreKit

class SHStoreManager: NSObject {
    
 @objc class func purchaseWithProductId(productId: String, inView: UIView, success: @escaping(()->Void) ,faliure: @escaping((String)->Void)) {
        
        MBProgressHUD.showMessage("请稍等...", delayTime: 90, mode: .indeterminate, to: inView)
        SwiftyStoreKit.purchaseProduct(productId, quantity: 1, atomically: true) { result in
            MBProgressHUD.hide(for: inView)
            switch result {
            case .success(let product):
                log("Purchase Success: \(product.productId)")
                
                let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "fea7fab4406346e783c9f7d966ea8041")
                MBProgressHUD.showMessage("校验中...", delayTime: 90, mode: .indeterminate, to: inView)
                SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
                    MBProgressHUD.hide(for: inView)
                    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)
                            CRUserDefaults.expireInTime = dateStr
                            if product.needsFinishTransaction {
                                SwiftyStoreKit.finishTransaction(product.transaction)
                            }
                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                                success()
                            }
                        case .expired(let expiryDate, _):
                            MBProgressHUD.showError("订阅已过期，请重新获取", 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)")
                // TODO: 服务器验证
                CMNetworkManager.shared.postRequestWithBody(withPath: .iosIPAVerifyReceipt, body: dict) { (json, error) in
                    MBProgressHUD.hide(for: inView)
                    print("success----iosIPAVerifyReceipt-----------------\(json)------")
                    
                    let result: Bool = json["result"]["data"]["status"].boolValue
                    if result {
                        if product.needsFinishTransaction {
                            SwiftyStoreKit.finishTransaction(product.transaction)
                        }
                        print("Purchase Success: \(product.productId)")
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                            success()
                        }
                    } else {
                        faliure(error?.localizedDescription ?? "未知错误,请联系客服")
                        MBProgressHUD.showError("未知错误,请联系客服")
                    }
                }
    
            case .error(let error):
                faliure(error.localizedDescription)
                switch error.code {
                case .unknown:
                    print("Unknown error. Please contact support")
                    MBProgressHUD.showError("无法连接到 iTunes Store, 请稍后再试")
                case .paymentCancelled:
                    MBProgressHUD.showError("操作取消")
                case .paymentInvalid:
                    MBProgressHUD.showError("无法购买, 请试试其他的")
                    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("无法连接到网络")
                    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)
                    MBProgressHUD.showError((error as NSError).localizedDescription)
                }
            }
        }
    }
    
    /// 静态初始化
    @objc class func launchWithSwiftyStoreKit() {
        
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            
            let sortedResults = purchases.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 {
                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: 服务器验证
                    CMNetworkManager.shared.postRequestWithBody(withPath: .iosIPAVerifyReceipt, body: dict) { (json, error) in
                        print("success----iosIPAVerifyReceipt-----------------\(json)------")
                        
                        let result: Bool = json["result"]["data"]["status"].boolValue
                        if result {
                            if purchase.needsFinishTransaction {
                                SwiftyStoreKit.finishTransaction(purchase.transaction)
                            }
                            print("Purchase Success: \(purchase.productId)")
                        } else {
//                            MBProgressHUD.showError("未知错误,请联系客服")
                        }
                    }
                    //                    }
                // 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: toView, 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: "fea7fab4406346e783c9f7d966ea8041")
                    let hud1 = MBProgressHUD.show(with: toView)
                    SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
                        hud1?.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)
                                CRUserDefaults.expireInTime = dateStr
                                MBProgressHUD.showSuccess("恢复成功", to: toView)
                                if purchase.needsFinishTransaction {
                                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                                }
                                success()
                            case .expired(let expiryDate, _):
                                print("Product is expired since \(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)
                                CRUserDefaults.expireInTime = dateStr
                                MBProgressHUD.showError("订阅已过期，请重新获取", to: toView)
                            case .notPurchased:
                                print("This product has never been purchased")
                            }
                        } else {
                            // receipt verification error
                        }
                    }
                    print("Restore Success: \(results.restoredPurchases)")
                }
            } else {
                MBProgressHUD.showError("没有商品可恢复")
                print("Nothing to Restore")
            }
        }
    }
}
