//
//  HomeViewController.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit
import AppTrackingTransparency
import SVProgressHUD

class HomeViewController:BaseViewController {
    
    private var isShowPay:Bool = false
    
    private var isShowCharge:Bool = false
    
    private var canShowIAP:Bool = false
    
    var homeView:HomeView?
    
    var isAdCallBack = false

    fileprivate func junmToModule(_ cIndex: String, _ self: HomeViewController) {
       
        switch cIndex {

        case HomeTabbarItemState.Charging.rawValue:
            
            DispatchQueue.main.async {[weak self] in
                
                guard let self else {return}
                
                let vc:ChargeViewController = ChargeViewController()
                
                self.navigationController?.pushViewController(vc, animated: true)
            }
            break
        case HomeTabbarItemState.SecretSpace.rawValue:
            DispatchQueue.main.async { [weak self] in
                guard let self else {return}
                // 这里需要看下是否需要PIN验证
                let pass =  SettingConfiguration.share.config.secret ?? ""//UserDefaults.standard.object(forKey: SecretViewController.psKey) as? String ?? ""
                if pass.count > 2{
                    let set = SecretSetViewController()
                    set.secretType = .verify
                    set.modalPresentationStyle = .fullScreen
                    self.present(set, animated: true)
                    set.Callback = {[weak self] su in
                        guard let self else {return}
                        set.dismiss(animated: true)
                        let vc:SecretViewController = SecretViewController()
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }else {
                    let vc:SecretViewController = SecretViewController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        case HomeTabbarItemState.Contacts.rawValue :
            DispatchQueue.main.async {[weak self] in
                guard let self else {return}
                let vc:ContactViewController = ContactViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            break
        case HomeTabbarItemState.EmailCleaner.rawValue :
            DispatchQueue.main.async {[weak self] in
                guard let self else {return}
                if PMEmailManager.shareManager.loginUser != nil {
                    let vc:EmailCleanController = EmailCleanController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    let vc:EmailLoginController = EmailLoginController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            break
        case HomeTabbarItemState.Compress.rawValue :
            DispatchQueue.main.async {[weak self] in
                guard let self else {return}
                let vc:CompressController = CompressController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            break
        default:
            break
        }
    }
    
    
    
    
    lazy var imageView : UIImageView =  {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "img_bj_home")
        imageView.backgroundColor = .clear
        return imageView
    }()
    
    
    func setupUI(){
        // 第一个背景
        self.view.addSubview(self.imageView)
        self.imageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(450 * RScreenH())
        }
        self.view.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        loadLaunchView()
        self.setupUI()
        
        // 调用下追踪权限
        checkTrackingAuthorization()
        
        homeView = HomeView(frame: view.bounds)
        homeView?.y = cWindow?.safeAreaInsets.top ?? 20
        homeView?.height = view.height - (cWindow?.safeAreaInsets.top ?? 20)
        
        homeView?.titleCallBack = {[weak self] model,type in
            guard let self else {return}
            guard let model = model else{ return }
            DispatchQueue.main.async {
                let vc:HomeInfoViewController = HomeInfoViewController(ids: model.assets , type: type,titleText: model.folderName)
                if model.folderName == HomeUIEnum.Dublicates.title{
                    APIReportManager.shared.startReport(type: .Duplicates_show)
                }else{
                    APIReportManager.shared.startReport(type: .Similar_show)
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
        homeView?.otherItemCallBack = {[weak self] model,otherItemRow in
            guard let self else {return}
            if otherItemRow == 0 {
                DispatchQueue.main.async {
                    let vc:HomeVideoDetailController = HomeVideoDetailController()
                    APIReportManager.shared.startReport(type: .Videos_show)
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            
            if otherItemRow == 1 {
                DispatchQueue.main.async {
                    let vc:HomeInfoViewController = HomeInfoViewController(ids: model.assets , type: .similarScreenshots ,titleText: model.folderName)
                    APIReportManager.shared.startReport(type: .SimilarScreenshots_show)
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            if otherItemRow == 3 {
                DispatchQueue.main.async {
                    let vc:HomeInfoViewController = HomeInfoViewController(ids: model.assets , type: .SimilarVideos ,titleText: model.folderName)
                    APIReportManager.shared.startReport(type: .SimilarVideos_show)
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            
            if otherItemRow == 2 ||  otherItemRow == 4{
                DispatchQueue.main.async {
                    let  vc = HomePhotosDetailViewController(mediaType: otherItemRow == 2 ? .screenshots : .Other)
                    if otherItemRow == 2{
                        APIReportManager.shared.startReport(type: .Screenshots_show)
                    }else{
                        APIReportManager.shared.startReport(type: .Other_show)
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }
        
        
        homeView?.indexCallBack = {[weak self] index in
            
            guard let self else {return}
                
            if let cIndex = index as? String {
                //self.junmToModule(cIndex, self)
                // 先走广告策略
                if IAPManager.share.isSubscribed == false {
//                    self.adManager.finisedCallBack = {
//                        Print("执行成功",cIndex)
//                        if self.adManager.adFromVC == cIndex,self.adManager.isFromHome{
//                            self.isAdCallBack = true
//                            self.junmToModule(cIndex, self)
//                        }
//                    }
//                    self.adManager.failueFinishedCallBack = {
//                        // 首页特殊要求广告没准备好也需要跳转
//                        Print("执行失败",cIndex)
//                        if self.adManager.adFromVC == cIndex,self.adManager.isFromHome{
//                            self.junmToModule(cIndex, self)
//                        }
//                    }
                  //  self.adManager.showInterstitialAd(vc: self,from: cIndex,isHome: true)
                   // self.junmToModule(cIndex, self)

                    ADManager.shared.showInterstitialAd(from:cIndex) {
                        self.junmToModule(cIndex, self)
                    } showFailBlock: { error in
                        self.junmToModule(cIndex, self)
                    }

                }else{
                    self.isAdCallBack = true
                    self.junmToModule(cIndex, self)
                }
               
             
            }
        }
        view.addSubview(homeView!)
    }

    
    func loadLaunchView(){
        let luanch = HomeLaunchView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: ScreenH))
        luanch.show()
        luanch.disMissBlock = {[weak self] in
            guard let weakSelf = self else { return }
            guard UserDef.shard.isShowLanding else{
                return
            }
           
            weakSelf.showIAPVC()
            
        }
        
        if !UserDef.shard.isShowLanding{
            let Ssoryboard = UIStoryboard(name: "PermissionVC", bundle: nil)
            if  let current = Ssoryboard.instantiateViewController(identifier: "PermissionVCID") as? PermissionVC {
                self.navigationController?.pushViewController(current, animated: false)
            }
        }
        
        NotificationCenter.default.addObserver(forName: .guidePageClose, object: nil, queue: nil) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.showIAPVC()
        }
    }
  
    func showIAPVC(){
        IAPManager.share.isHotLaunch = true
        IAPManager.share.checkSubscriptionState {[weak self] isSubscribed,type,expiresDate in
            guard let self = self else { return }
            Print("是否内购---",isSubscribed)
            DispatchQueue.main.async {
                if IAPManager.share.showYearPage{
                    //按钮启动
                    switch type {
                    case .none,.week:
                        let vc = PayDistanceViewController()
                        let nav:BaseNavViewController = BaseNavViewController(rootViewController: vc)
                        nav.modalPresentationStyle = .fullScreen
                        self.present(nav, animated: true)
                        
                        break
                    case .lifetime,.year:
                        let vc : PayCompletedViewController =  PayCompletedViewController()
                        vc.modalPresentationStyle = .fullScreen
                        self.present(vc, animated: true)
                    }
                }else{
                    // 正常启动
                    if !isSubscribed{
                        DispatchQueue.main.async {
                            if !IAPManager.share.showYearPage{
                                HomePayViewController.show {
                                    NotificationManager().configNotifications()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !isShowCharge {
            if BatteryMonitorManager.shared.getBatteryIsCharging() {
                // 从字典里面取 如果有
                var tempModel : ChargeDataModel?
                if UserDefaults.standard.object(forKey: "chargePicInfo") != nil {
                    let flag : String = UserDefaults.standard.object(forKey: "chargePicInfo") as! String
                    tempModel = loadVideoItems()[Int(flag)!]
                    let vc:ChargeInfoViewController = ChargeInfoViewController(model:tempModel, type: ChargeInfoViewController.ChargeInfoType.charge)
                    self.navigationController?.pushViewController(vc, animated: false)
                }
            }
            isShowCharge = true
        }
        homeView?.viewModel.reloadTrashAndKeep()
        homeView?.collectionView.reloadData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        self.barHidden = false
        if !isShowCharge {
            NotificationManager().configNotifications()
            return
        }

    }
    
}

extension HomeViewController {
    
    // 检查跟踪授权状态
    func checkTrackingAuthorization() {
        if #available(iOS 14, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            switch status {
            case .authorized:
                // 用户已授权跟踪
                print("用户已授权应用进行跟踪")
                Print("idfa",ADManager.shared.getIDFA())
            case .denied:
                // 用户拒绝了跟踪请求
                print("用户拒绝了应用的跟踪请求")
            case .restricted:
                // 由于系统限制，无法跟踪用户
                print("由于系统限制，无法跟踪用户")
            case .notDetermined:
                // 用户尚未对跟踪请求做出决定
                print("用户尚未对跟踪请求做出决定，再次请求授权")
                requestTrackingAuthorization()
            @unknown default:
                break
            }
        } else {
            // iOS 14 以下系统不支持 ATT 框架
            // 可以执行其他操作
        }
    }
    func requestTrackingAuthorization() {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                switch status {
                case .authorized:
                    // 用户已授权跟踪
                    print("用户已授权应用进行跟踪")
                    Print("idfa",ADManager.shared.getIDFA())
                case .denied:
                    // 用户拒绝了跟踪请求
                    print("用户拒绝了应用的跟踪请求")
                case .restricted:
                    // 由于系统限制，无法跟踪用户
                    print("由于系统限制，无法跟踪用户")
                case .notDetermined:
                    // 用户尚未对跟踪请求做出决定
                    print("用户尚未对跟踪请求做出决定")
                @unknown default:
                    break
                }
            })
        } else {
            // iOS 14 以下系统不支持 ATT 框架
            // 可以执行其他操作
        }
    }
}

