//
//  AppDelegate.swift
//  VattiCSS
//
//  Created by fishxiaou on 2023/8/15.
//

import UIKit
import CoreLocation
import UserNotifications
import IQKeyboardManagerSwift
import Bugly

let jgAk = "7aeea60528a1b8ae182c82bd"

@main
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
    var Token: String = ""
    var window: UIWindow?
    var isForceLandscape: Bool = false
    var isForcePortrait: Bool = false
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AMapServices.shared().enableHTTPS = true
//        AMapServices.shared().apiKey = "ed2bc95b4b245521bc7b228e2d2d1d31"
        AMapServices.shared().apiKey = "f1ab9f52d5296d102e08d5addfddb394"
        
        
        Bugly.start(withAppId: "f604dfcaa8")
       
        makeTopBar()
        configReachabilityManager()
        configIQKeyboard()
        configSVProgressHUD()
        configJPUSH(launchOptions: launchOptions)
        registerForRemoteNotifications()
        makeRootViewController()
        configNetWork()
        
        configLoginTokenPostError()
    
//        AMapPrivacyUtility.handlePrivacyAgreeStatus()
        AMapLocationManager.updatePrivacyAgree(.didAgree)
        return true
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
          if (isForceLandscape) {
              //这里设置允许横屏的类型
              return .landscapeRight;
          }else if (isForcePortrait){
              return .portrait;
          }
          return .portrait;
      }
    
    func makeTopBar() {
        MyDimeScale.setUITemplateSize(CGSize(width: 375, height: 667))
        CD_TopBar.Model.color_bg = Config.color.hex("f")
        CD_TopBar.Model.color_line = Config.color.line_1
        CD_TopBar.Model.color_title = Config.color.txt_1
        CD_TopBar.Model.color_subTitle = Config.color.txt_1
        CD_TopBar.Model.color_prompt = Config.color.txt_1
        CD_TopBar.Model.color_normal = Config.color.txt_1
        CD_TopBar.Model.color_selected = Config.color.txt_3
        CD_TopBar.Model.color_highlighted = Config.color.txt_3
        let icon = CD_IconFont.tback_light(22)
        CD_TopBar.Model.back = .title([(icon.text, icon.font, Config.color.txt_1, .normal), (icon.text, icon.font, Config.color.txt_1.cd_alpha(0.6), .highlighted), (icon.text, icon.font, Config.color.txt_1.cd_alpha(0.6), .selected)])
        
        CD.iOSAdjustmentBehavior()
        UITextView.appearance().tintColor = Config.color.main_1
        UITextField.appearance().tintColor = Config.color.main_1
        UITableViewCell.appearance().selectionStyle = .none
        UITableView.appearance().backgroundColor = Config.color.bg
        UICollectionView.appearance().backgroundColor = Config.color.bg
        UINavigationBar.appearance().tintColor = Config.color.txt_1//UIColor.white
        //UINavigationBar.appearance().backgroundColor = Config.color.navigation0
        UINavigationBar.appearance().backIndicatorImage = UIImage.cd_iconfont(CD_IconFont.tback_light(22), color: Config.color.txt_1)
        UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage.cd_iconfont(CD_IconFont.tback_light(22), color: Config.color.txt_1)
    }

    func makeRootViewController(){
        window = UIWindow(frame: UIScreen.main.bounds)
        window!.makeKeyAndVisible()
        
        let loginVC = UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController()
        self.window!.rootViewController = loginVC
    }
    
    func configNetWork() {
        TWOCNetwork.shareNetManager().isJsonContentType = true
        TWOCNetwork.shareNetManager().baseParameters = ["mobileType":"2"] // 设备类型:1安卓、2IOS
    }
    
    func configIQKeyboard() {
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
    }
    
    func configSVProgressHUD() {
        SVProgressHUD.setDefaultStyle(.dark)
        SVProgressHUD.setDefaultMaskType(.clear)
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        SVProgressHUD.setMaximumDismissTimeInterval(3)
    }
    
    func configLoginTokenPostError(){
        NotificationCenter.default.addObserver(self, selector: #selector(backPost(_:)), name: NSNotification.Name(rawValue: "LoginTokenPostError"), object: nil)
    }
    
    @objc func backPost(_ notification: Notification){
        let msg = (notification.userInfo!["message"] as! String).stringValue
        
        let alertController = UIAlertController.init(title: msg, message: "", preferredStyle: .alert)
        alertController.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in
            //被踢返回登录
            self.makeRootViewController()
        }))
        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
    }
    
    func configReachabilityManager()
    {
        AFNetworkReachabilityManager.shared().startMonitoring()
    // 检测网络连接的单例,网络变化时的回调方法
        AFNetworkReachabilityManager.shared().setReachabilityStatusChange { (status:AFNetworkReachabilityStatus) -> Void in
            if status == AFNetworkReachabilityStatus.reachableViaWiFi {

            }else if (status == AFNetworkReachabilityStatus.reachableViaWWAN){

            }else{
                hud_error("网络无连接~")
            }
        }
    }
    
    func registerForRemoteNotifications(){
        // 推送
        if #available(iOS 10.0, *) {
            let notifiCenter = UNUserNotificationCenter.current()
            notifiCenter.delegate = self
            let types = UNAuthorizationOptions(arrayLiteral: [.alert, .badge, .sound])
            notifiCenter.requestAuthorization(options: types) { (flag, error) in
                if flag {
                    debugPrint("注册成功")
                }else{
                    debugPrint("注册失败")
                }
            }
            UIApplication.shared.registerForRemoteNotifications()
        } else { //iOS8,iOS9注册通知
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [UIUserNotificationType.sound , UIUserNotificationType.badge , UIUserNotificationType.alert] , categories: nil))
        }
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //把deviceToken发送到我们的推送服务器
        let subStr = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
        Token = subStr
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        //  接收到通知
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "LoginTokenPostError"), object: nil)
    }

}


extension AppDelegate: JPUSHRegisterDelegate {
     // 极光
     func configJPUSH(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
         let entity = JPUSHRegisterEntity()
         entity.types = 1 << 0 | 1 << 1 | 1 << 2
         JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
         JPUSHService.setup(withOption: launchOptions, appKey: jgAk, channel: "App Store", apsForProduction: true, advertisingIdentifier: nil)
     }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        guard let trigger = notification.request.trigger else { return }
        if trigger.isKind(of: UNPushNotificationTrigger.self) {
            // 从通知界面直接进入应用
            
        }else{
            //从通知设置界面进入应用
            
        }
    }
    
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
        guard let theNo = notification, let trigger = theNo.request.trigger else { return }
        if trigger.isKind(of: UNPushNotificationTrigger.self) {
            // 从通知界面直接进入应用
            
        }else{
            //从通知设置界面进入应用
            
        }
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        if let theNo = notification, let trigger = theNo.request.trigger, trigger.isKind(of: UNPushNotificationTrigger.self) {
            let nUserInfo = notification.request.content.userInfo
            JPUSHService.handleRemoteNotification(nUserInfo)
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let theNo = response.notification
        if let trigger = theNo.request.trigger, trigger.isKind(of: UNPushNotificationTrigger.self) {
            let nUserInfo = response.notification.request.content.userInfo
            JPUSHService.handleRemoteNotification(nUserInfo)
            if UIApplication.shared.applicationState == .inactive {
                self.jPushNotificationJumpAction(notiDict: nUserInfo)
            }
        }
        completionHandler()
    }
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    // 推送处理
    func jPushNotificationJumpAction(notiDict:[AnyHashable:Any]) {
        print_cd(notiDict)
    }
    
}
 
 


