//
//  AdvManager.swift
//  PhoneManager
//
//  Created by edy on 2025/4/17.
//

import Foundation
import GoogleMobileAds
import UserMessagingPlatform
import AppTrackingTransparency
import AdSupport
import AppLovinSDK
import FBAudienceNetwork
import SVProgressHUD

enum AdvertisementType {
    case rewardedInterstitialType
    case interstitialType
}


class AdvManager : NSObject, FullScreenContentDelegate {
    
    // fixme:上线前更改
//        private static let REWARDED_INTERSTITIALAD_KEY : String = "ca-app-pub-3480207748580737/4276457203"
//        private static let INTERSTITIALAD_KEY : String = "ca-app-pub-3480207748580737/5836950888"
    //    info.plist:  ca-app-pub-3480207748580737~4236262472
    
    private static let REWARDED_INTERSTITIALAD_KEY : String = "ca-app-pub-3940256099942544/6978759866"
    private static let INTERSTITIALAD_KEY : String = "ca-app-pub-3940256099942544/4411468910"

    static let shared : AdvManager = AdvManager()
    
    var adFromName:String = ""
    
    var adFromVC:String = ""
    
    // 看完广告的回调
    var finisedCallBack:()->Void = {}
    
    var serctCallBack:()->Void = {}
    
    // 广告都没播放成功回调
    var failueFinishedCallBack : ()->Void = {}
    
    // 激励插页广告
    var rewardedInterstitialAd: RewardedInterstitialAd?
    
    // 插页广告
    var interstitial: InterstitialAd?
    
    
    var currentTimes : Int = 3
    
    /// 记录激励上次展示广告的时间
    private var rewardlastAdShowTime: Date?
    /// 记录插屏上次展示广告的时间
    private var interstitiallastAdShowTime: Date?
    
    var isFromHome = false
    
    /// 默认每日免费删除次数
    var defaultFreeTimes : Int {
        get {
            // 获取存储的时间
            let saveTime = UserDefaults.standard.object(forKey: "saveTime")
            if saveTime == nil {
                UserDefaults.standard.set(Date(), forKey: "saveTime")
                UserDefaults.standard.set(AdvManager.shared.currentTimes, forKey: "saveAdvTimes")
                return AdvManager.shared.currentTimes
            }else {
                // 判断时间是不是同一天
                let calendar = Calendar.current
                let isSameDay = calendar.isDate(saveTime as! Date, inSameDayAs: Date())
                if isSameDay {
                    // 如果是同一天
                    let times =  UserDefaults.standard.object(forKey: "saveAdvTimes") as! Int
                    // 如果等于0 那啥也不做
                    return times
                }else{
                    // 如果不是同一天，重置次数
                    UserDefaults.standard.set(Date(), forKey: "saveTime")
                    UserDefaults.standard.set(AdvManager.shared.currentTimes, forKey: "saveAdvTimes")
                    return AdvManager.shared.currentTimes
                }
            }
        }
    }
    
    /// 广告策略  第一次可删除5张，第二次可删除5张，第三次可删除4张
    let advDeleteResouceDic : [Int:Int] = [3:5,2:5,1:4,0:0]
    
    var interstitialOnceAgin = false
    var rewardOnceAgin = false
    
    /// 能请求广告
    var canRequestAds: Bool {
        return ConsentInformation.shared.canRequestAds
    }
    
    // 是否有权限
    var isPrivacyOptionsRequired: Bool {
        return ConsentInformation.shared.privacyOptionsRequirementStatus == .required
    }
    
    /// 初始化SDK
    func initAdertisementSDK() {
        ALPrivacySettings.setDoNotSell(true)
        FBAdSettings.setAdvertiserTrackingEnabled(true)
        MobileAds.shared.start { status in
            let adapterStatuses = status.adapterStatusesByClassName
            for adapter in adapterStatuses {
              let adapterStatus = adapter.value
              NSLog("Adapter Name: %@, Description: %@, Latency: %f", adapter.key,
              adapterStatus.description, adapterStatus.latency)
            }
            
            Task {
                // 同时load两个广告内容
                await self.loadInterstitial()
                await self.loadRewardedInterstitialAd()
            }
            // 隐私设置
            ALPrivacySettings.setHasUserConsent(true)
        }


    }
    
    ///  获取激励插页广告
    ///
    func loadRewardedInterstitialAd() async {
        APIReportManager.shared.startReport(type: .ad_pull_start, ext: ["ad_type":"rewardAd"])
        do {
            rewardedInterstitialAd = try await RewardedInterstitialAd.load(
                with: AdvManager.REWARDED_INTERSTITIALAD_KEY, request: Request())
            rewardedInterstitialAd?.fullScreenContentDelegate = self

            rewardedInterstitialAd?.paidEventHandler = {[weak self] value in
                guard let weakSelf = self else { return }
                print("激励广告价值回调",value)
                let valueMicros = value.value
                let currencyCode = value.currencyCode
                let precision = value.precision
                
                // 获取基础广告信息
                var pram = weakSelf.loadedAdNetworkResponseInfo(ad: weakSelf.rewardedInterstitialAd)
//                // 添加价值相关信息到 pram 字典中
                pram["valueMicros"] = "\(valueMicros)"
                pram["currencyCode"] = currencyCode
                pram["precision"] = "\(precision.rawValue)"
              
                print("广告价值和来源", pram)
                // 使用 APIReportManager 上报广告价值
                APIReportManager().startReport(type: .ad_price, ext: pram)
             
            }
            APIReportManager.shared.startReport(
                type: .ad_pull,
                ext: ["ad_type":"rewardAd",
                      "status":"1",
                      "from":"",
                     ]
            )
        } catch {
            if rewardOnceAgin == false{
                rewardOnceAgin = true
                Task{
                    await loadRewardedInterstitialAd()
                }
            }
            print("Failed to load rewarded interstitial ad with error: \(error.localizedDescription)")
            APIReportManager.shared.startReport(
                type: .ad_pull,
                ext: ["ad_type":"rewardAd",
                      "status":"2",
                      "from":"",
                      "errMsg":error.localizedDescription]
            )
        }
    }
    
    
    
    /// 获取单纯的插页广告
    fileprivate func loadInterstitial() async {
        APIReportManager.shared.startReport(type: .ad_pull_start, ext: ["ad_type":"interAd"])
        do {
            interstitial = try await InterstitialAd.load(
                with: AdvManager.INTERSTITIALAD_KEY, request: Request())
            interstitial?.fullScreenContentDelegate = self
            interstitial?.paidEventHandler = {[weak self] value in
                guard let weakSelf = self else { return }
                print("插屏广告价值回调",value)
                let valueMicros = value.value
                let currencyCode = value.currencyCode
                let precision = value.precision
                
                // 获取基础广告信息
                var pram = weakSelf.loadedAdNetworkResponseInfo(ad: weakSelf.interstitial)
//                // 添加价值相关信息到 pram 字典中
                pram["valueMicros"] = "\(valueMicros)"
                pram["currencyCode"] = currencyCode
                pram["precision"] = "\(precision.rawValue)"
              
                print("广告价值和来源", pram)
                // 使用 APIReportManager 上报广告价值
                APIReportManager().startReport(type: .ad_price, ext: pram)
             
            }
            
            APIReportManager.shared.startReport(
                type: .ad_pull,
                ext: ["ad_type":"interAd",
                      "status":"1",
                      "from":"",
                     ]
            )
        } catch {
            if interstitialOnceAgin == false{
                interstitialOnceAgin = true
                Task{
                    await loadInterstitial()
                }
            }
            print("Failed to load interstitial ad with error: \(error.localizedDescription)")
            APIReportManager.shared.startReport(
                type: .ad_pull,
                ext: ["ad_type":"interAd",
                      "status":"2",
                      "from":"",
                      "errMsg":error.localizedDescription]
            )
        }
    }
    
    
    /// 开始显示
    /// - Parameter completed: 准备完成后回调
    func showRewardedInterstitialAd(vc:UIViewController,from:String = "",isByInter:Bool = false) {
        isFromHome = false
        // 检查是否在上次广告展示后的 30 秒内
        if let lastAdShowTime = rewardlastAdShowTime {
            let timeSinceLastAd = Date().timeIntervalSince(lastAdShowTime)
            if timeSinceLastAd < 30 {
                showErrMessage(vc: vc)
                return
            }
        }
        guard let ad = self.rewardedInterstitialAd else {
            Task {
                await self.loadRewardedInterstitialAd()
            }
            if !isByInter{
                if let inter = self.interstitial{
                    showInterstitialAd(vc: vc,isByReward: true)
                }else{
                    showErrMessage(vc: vc)
                }
            }
            return
        }
        self.adFromName = from
        APIReportManager.shared.startReport(
            type: .ad_prepare_show,
            ext: ["ad_type": "rewardAd","from":self.adFromName])
        ad.present(from: nil) {}
    }
    
    /// 开始显示
    /// - Parameter completed: 准备完成后回调
    func showInterstitialAd(vc:UIViewController,from:String = "",isByReward:Bool = false,needAlert:Bool = false,isHome:Bool = false) {
        isFromHome = isHome
        adFromVC = from
        if let lastAdShowTime = interstitiallastAdShowTime {
            let timeSinceLastAd = Date().timeIntervalSince(lastAdShowTime)
            if timeSinceLastAd < 30 {
                if needAlert{
                    showErrMessage(vc: vc)
                }else{
                    failueFinishedCallBack()
                }
                return
            }
        }
        guard let ad = self.interstitial else {
            Task{
                await loadInterstitial()
            }
            if !isByReward{
                showRewardedInterstitialAd(vc: vc,from: from,isByInter: true)
            }
            return
        }

        self.adFromName = from
        APIReportManager.shared.startReport(
            type: .ad_prepare_show,
            ext: ["ad_type": "interAd","from":adFromName])
        ad.present(from: nil)
    }
    
    
    // MARK: - GADFullScreenContentDelegate
    func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
        print("Ad did present full screen content.")
        var ad_type = "interAd"
        if let _ = ad as? RewardedInterstitialAd{
            ad_type = "rewardAd"
            rewardlastAdShowTime = Date()
        }else{
            interstitiallastAdShowTime = Date()
        }
    
        APIReportManager.shared.startReport(
            type: .ad_show,
            ext: ["ad_type": ad_type,"from":adFromName])
    }
    
    
    func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("Ad failed to present full screen content with error \(error.localizedDescription).")
        
        var ad_type = "interAd"
        if let _ = ad as? RewardedInterstitialAd{
            ad_type = "rewardAd"
        }
        APIReportManager.shared.startReport(
            type: .ad_show_error,
            ext: ["ad_type": ad_type,"from":adFromName,"reason":error.localizedDescription])
        interstitiallastAdShowTime = nil
        rewardlastAdShowTime = nil
        self.rewardedInterstitialAd = nil
        self.interstitial = nil
        
    }
    
    func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        print("Ad did dismiss full screen content.")
        if let _ = ad as? RewardedInterstitialAd{
            self.rewardedInterstitialAd = nil
            Task {
                await self.loadRewardedInterstitialAd()
            }
        }else{
            self.interstitial = nil
            Task {
                await self.loadInterstitial()
            }
        }

        finisedCallBack()
    }
    
    
    
    func adDidRecordClick(_ ad: any FullScreenPresentingAd) {
        print("点击广告")
        
        let pram = loadedAdNetworkResponseInfo(ad: ad)
        
        APIReportManager.shared.startReport(
            type:.ad_click,
            ext:pram)
    }
    
    
    func showErrMessage(vc:UIViewController){
        // 这里如果还没有，则弹出框
        let alert = UIAlertController(title: nil, message: "Ad wasn't ready", preferredStyle: .alert)
        GETCURRENTNAV()?.present(alert, animated: true, completion: nil)
        // 1 秒后关闭弹窗
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            alert.dismiss(animated: true) {
                self.failueFinishedCallBack()
            }
        }
       // SVProgressHUD.showInfo(withStatus: "Ad wasn't ready")
    }

}
    


extension AdvManager{
    
    
    func loadedAdNetworkResponseInfo(ad: FullScreenPresentingAd?) ->[String:String]{

        var adNetworkName = ""
        var adSourceName = ""
        var adSourceID = ""
        var adSourceInstanceName = ""
        var adNetworkClassName = ""
        var adSourceInstanceID = ""
        
        if let rewardedAd = ad as? RewardedInterstitialAd {
            adNetworkName = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adNetworkClassName ?? "unknown"
            adSourceName = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceName ?? "unknown"
            adSourceID = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceID ?? "unknown"
            adSourceInstanceName = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceInstanceName ?? "unknown"
            adNetworkClassName = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adNetworkClassName ?? "unknown"
            adSourceInstanceID = rewardedAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceInstanceID ?? "unknown"
            
        } else if let interstitialAd = ad as? InterstitialAd {
           
            adNetworkName = interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adNetworkClassName ?? "unknown"
            adSourceName =  interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceName ?? "unknown"
            adSourceID = interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceID ?? "unknown"
            adSourceInstanceName = interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceInstanceName ?? "unknown"
            adNetworkClassName = interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adNetworkClassName ?? "unknown"
            adSourceInstanceID = interstitialAd.responseInfo.loadedAdNetworkResponseInfo?.adSourceInstanceID ?? "unknown"
        }
        
        var pram = [
            "from":adFromName,
            "networkname":adNetworkName,
            "adSourceName":adSourceName,
            "adSourceInstanceName":adSourceInstanceName,
            "adSourceId":adSourceID,
            "adNetworkClassName":adNetworkClassName,
            "adSourceInstanceId":adSourceInstanceID,
        ]
        
        if let rewardAd = ad as? RewardedInterstitialAd{
            pram["ad_type"] = "rewardAd"
            pram["adUnitId"] = rewardAd.adUnitID
        }else if let interstitial = ad as? InterstitialAd{
            pram["ad_type"] = "interAd"
            pram["adUnitId"] = interstitial.adUnitID
        }
        
        return pram
    }
}



extension AdvManager {
    /// 获取IDFA
    func getIDFA() -> String {
        if #available(iOS 14, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            switch status {
            case .authorized:
                return ASIdentifierManager.shared().advertisingIdentifier.uuidString
            case .denied, .restricted, .notDetermined:
                requestIDFAPermission { staus in
                    
                }
                return ""
            @unknown default:
                return ""
            }
        } else {
            // iOS 14以下版本
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                return ASIdentifierManager.shared().advertisingIdentifier.uuidString
            }
            return ""
        }
    }
    
    /// 请求IDFA权限
    func requestIDFAPermission(completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void) {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                DispatchQueue.main.async {
                    completion(status)
                }
            }
        } else {
            completion(.authorized)
        }
    }
}

