//
//  AppDelegate.swift
//  galaxy
//
//  Created by davidhuangA on 2023/12/19.
//

import UIKit
import ESTabBarController_swift
import IQKeyboardManagerSwift
import SmartCodable
import GKNavigationBarSwift
import DeviceKit
import AVFoundation

@main
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        setupAudionConfig()
        
        //初始化 神策sdk
        YHAnalytics.analyticsStart(launchOptions: launchOptions)
        
        // JPush服务注册
        registerJPushService(launchOptions)
        
        //全局导航栏、返回事件/手势
        setupNavBar()
        
        //2.通用UI设置
        setupWholeUI()
        
        //3.其他第三方sdk设置
        thirdSetting()
        
        //4.本地用户信息加载
        YHLoginManager.shared.loadLocalUserInfoData()
        
        YHConfigManager.shared.loadConfigData()
        
        //5.预加载
        preloadOP()
        
        //微信注册app
        WXApi.registerApp(YhConstant.Wechat.appKey, universalLink: YhConstant.Wechat.universalLink)
        WXApi.startLog(by: .detail) { string in
            printLog(string)
        }
        
        // 一键登录
        YHOneKeyLoginManager.shared.configOneKeyLogin()
        
        YHOSSManager.share.getOSSID()
        
        //1.设置主窗口
        setupRootVC()
        return true
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        if YHAnalytics.handleSchemeUrl(url) ?? false {
            return true
        }
        return true
    }
    
    
    func setupNavBar() {
        GKConfigure.setupDefault()
    }
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func onResp(_ resp: BaseResp) {
        if resp.isKind(of: SendAuthResp.self) {
            let res = resp as? SendAuthResp
            if res?.state == "wechat_sdk_demo_test", let code = res?.code {
                YHShareManager.shared.getWechatAccessToken(code: code)
            }
        }
    }
}


extension AppDelegate {
    private func thirdSetting() -> Void {
        //1.数据解析
#if DEBUG
        SmartConfig.debugMode = .none
#elseif TESTNEV
        SmartConfig.debugMode = .none
#else
        SmartConfig.debugMode = .none
#endif
        
        //2.bugly参数设置
#if DEBUG
        Bugly.start(withAppId: YhConstant.Bugly.appidForTest)
#elseif TESTNEV
        Bugly.start(withAppId: YhConstant.Bugly.appidForTest)
#else
        Bugly.start(withAppId: YhConstant.Bugly.appidForRelease)
#endif
    }
    
    //2.通用全局UI设置相关
    private func setupWholeUI() -> Void {
        
        DispatchQueue.global().async {
            //异步延迟设置
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.25) { [] in
                //1、系统控件属性设置
                UITextField.appearance().tintColor = .brandMainColor
                UITextView.appearance().tintColor = .brandMainColor
                
                IQKeyboardManager.shared.enable = true
                IQKeyboardManager.shared.enableAutoToolbar = false
                IQKeyboardManager.shared.resignOnTouchOutside = true  //控制点击背景是否收起键盘
            }
        }
        
        YHNetworkStatusManager.shared.listenNetWorkStatus()
    }
    
    //1.设置闪主窗口
    private func setupRootVC() {
        
        let dateString = Date().dateString(ofStyle: .short)
        let oldString = UserDefaults.standard.value(forKey: "todayShowStartPageViewFlag")
        
        if  let tempStr =  oldString as? String, tempStr == dateString {
            setupRootVCWithTabBar()
        } else {
            let nav = YHNavigationController(rootVC:YHStartPageViewController())
            window = UIWindow(frame: UIScreen.main.bounds)
            window?.rootViewController = nav
            window?.makeKeyAndVisible()
        }
        
    }
    
    //1.设置HomePageView为主窗口
    func setupRootVCWithTabBar() {
//        gk_navigationBar.isHidden = false
        let tabBarController = YHTabBarViewController()
        let homeVC = YHHomePageViewController()
        tabBarController.delegate = homeVC
        let v0 = YHNavigationController(rootVC:homeVC)
        let v1 = YHNavigationController(rootVC:YHServiceCenterMainViewController())
        let v2 = YHNavigationController(rootVC:YHMessageListVC())
        let v3 = YHNavigationController(rootVC:YHMyViewController())
        
        v0.tabBarItem = ESTabBarItem.init(YHBasicContentView(),title: "首页", image: UIImage(named: "home"), selectedImage: UIImage(named: "home_1"))
        
        v1.tabBarItem = ESTabBarItem.init(YHBasicContentView(),title: "服务", image: UIImage(named: "service"), selectedImage: UIImage(named: "service_1"))
        
        v2.tabBarItem = ESTabBarItem.init(YHBasicContentView(),title: "消息", image: UIImage(named: "msg"), selectedImage: UIImage(named: "msg_1"))
        
        v3.tabBarItem = ESTabBarItem.init(YHBasicContentView(),title: "我的", image: UIImage(named: "me"), selectedImage: UIImage(named: "me_1"))
        
        tabBarController.viewControllers = [v0,v1,v2,v3]
        tabBarController.tabBar.backgroundColor = .white
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarController
        window?.makeKeyAndVisible()
        
        if YHLoginManager.shared.needJumpToMsgTabFlag {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
                goTabBarBy(tabType: .message)
            })
        }
    }
    
    
    
    private func preloadOP() {
        DispatchQueue.global().async {
            guard let videoURL = Bundle.main.url(forResource: "loginBkg", withExtension: "mov") else { return }
            
            let player: AVPlayer? = AVPlayer(url: videoURL)
            player?.actionAtItemEnd = .none
            let playerLayer: AVPlayerLayer? = AVPlayerLayer(player: player)
            playerLayer?.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight)
            playerLayer?.videoGravity = .resizeAspectFill
            player?.play()
            player?.pause()
        }
    }
    
    private func setupAudionConfig() {
        
        // 确保 AVAudioSession 被正确配置,以便在静音模式下也能正常播放音频
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try AVAudioSession.sharedInstance().setActive(true)
                    
        } catch let error as NSError {
            print("error: \(error.localizedDescription)")
        }
    }
}
