/*
 shareSDK账号&密码
 17322010717
 gelifood81338860
  
 融云账号&融云密码
 18924107259
 81338860geLI
 
 苹果账号&密码
 notice@gelifood.com
 81338860^geLi
 
 极光密码
 GeliFood
 81338860geLI
 
 高德地图
 18924107259
 81338860geli
 
 微信开发平台
 GELIFOOD123@126.com
 81338860geli
 
 微信分享 id & secret
 wx26b371b279064098
 55343eb2b2c2329860ad8545715ae9f3
 
 测试账号&密码
 Liangyuepf
 zxcvbnm
 */

import UIKit
import ESTabBarController_swift

@available(iOS 10.0, *)

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate,loginDelegate,UITabBarControllerDelegate, JPUSHRegisterDelegate{
    var blueToothVC:BtViewController!
    var window:UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        //        启动图,调整展示时间为3秒
        Thread .sleep(forTimeInterval: 2.0)
        blueToothVC = BtViewController()
        let UserToken = UserDefaults.standard.value(forKey: "user_token")
        
        if UserToken == nil {
            addLoginVc(isAgain: false)
        }else{
            addTabBarVcs(isAgain: false)
        }
        setting_Jpush(application: application, launchOptions: launchOptions)
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        setting_ShareSDK()
        
        
        return true
    }
    
    
    func setting_ShareSDK(){
        ShareSDK.registPlatforms {
            register in
            register?.setupWeChat(withAppId: "wx26b371b279064098", appSecret: "55343eb2b2c2329860ad8545715ae9f3",universalLink: "https://GeliBusinessPlatform.GeliBusinessPlatform/")
        }
    }
    
    func setting_Jpush(application:UIApplication,launchOptions:[UIApplication.LaunchOptionsKey: Any]?) {
        
        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                                    UNAuthorizationOptions.badge.rawValue |
                                    UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
        } else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }else {
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        
        // 根据环境的不同,设置不同的apsForProduction值,具体看下面参数说明
        JPUSHService.setup(withOption: launchOptions,
                           appKey: "3ecbdeacab51eb48e1219a96",
                           channel: "App Store",
                           apsForProduction: true)
        
        //注册别名
        
        
    }
    // 注册deviceToken
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
        
    }
    //IOS 12
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification!) {
        
        
        if notification != nil && (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            //从通知界面直接进入应用
            let userInfo = notification?.request.content.userInfo
            print("1--",userInfo as Any)
        }else{
            //从通知设置界面进入应用
            let userInfo = notification?.request.content.userInfo
            print("1-11-",userInfo as Any)
        }
        
    }
    //IOS 10
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
            //前台内容先到这
            print("2--",userInfo as Any)
        }
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))// 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
    }
    
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
            //点击都走这
            print("3--",userInfo as Any)
            let dict = userInfo as NSDictionary
            let num = dict["type"] as! NSString
            if num.integerValue == 1 {
                tabBarC.selectedIndex = 0
            }else{
                switch tabBarC.selectedIndex {
                case 0:
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "jpushServiceNotification0"), object: nil, userInfo: userInfo)
                    break
                case 1:
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "jpushServiceNotification1"), object: nil, userInfo: userInfo)
                    break
                case 2:
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "jpushServiceNotification2"), object: nil, userInfo: userInfo)
                    break
                case 3:
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "jpushServiceNotification3"), object: nil, userInfo: userInfo)
                    break
                case 4:
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "jpushServiceNotification4"), object: nil, userInfo: userInfo)
                    break
                default:
                    break
                }
            }
        }
        completionHandler()
    }
    
    //监测通知授权状态返回的结果
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    
    //MARK:--成功登录并反馈
    func successLogin() {
        addTabBarVcs(isAgain: true)
    }
    //MARK:--退出登录并反馈
    @objc func popLogout() {
        addLoginVc(isAgain: true)
    }
    //MARK:--loginVC
    func addLoginVc (isAgain:Bool){
        
        let vc = LoginViewController()
        vc.delegate = self
        let contentView = vc
        
        if isAgain {
            let transtition = CATransition()
            transtition.duration = 0.5
            transtition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
            UIApplication.shared.keyWindow?.layer.add(transtition, forKey: "animation")
            let rootV = NavViewController(rootViewController: contentView)
            UIApplication.shared.keyWindow?.rootViewController = rootV
        }else{
            let window = UIWindow.init(frame: UIScreen.main.bounds)
            self.window = window
            let rootV = NavViewController(rootViewController: contentView)
            self.window!.rootViewController = rootV;
            
            self.window!.makeKeyAndVisible()
        }
    }
    
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        
        return true
        
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        return true
    }
    
    
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //可选
        NSLog("did Fail To Register For Remote Notifications With Error: \(error)")
    }
    // 接受数据
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("444--",userInfo as Any)
        completionHandler(.newData)
    }
    
    // 接受数据
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print("555--",userInfo as Any)
    }
    
    // 进入前台的时候,清空角标
    func applicationWillEnterForeground(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        UIApplication.shared.applicationIconBadgeNumber = 0
        
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
    }
    
    //MARK:--tabbarVCs
    weak var tabBarC:ESTabBarController!
    func addTabBarVcs (isAgain:Bool) {
        let tabBarController = ESTabBarController()
        tabBarController.delegate = self
        tabBarController.tabBar.backgroundColor = UIColor.white
        tabBarController.tabBar.shadowImage = UIImage(named: "transparent")
        let img = imageWithColor(UIColor.white)
        tabBarController.tabBar.backgroundImage = img
        NotificationCenter.default.addObserver(self, selector: #selector(popLogout), name: NSNotification.Name(rawValue: "logout"), object: nil)
        
        tabBarC = tabBarController
        
        let v1 = OrderListViewController()
        
        let v2 = GoodsManageListVC()
        
        let v3 = WorkCViewController()
        
        let v4 = WarehoseMangementListVC()
        
        let v5 = PersonCenterViewController()
        
        v1.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "订单管理", image: UIImage(named: "tab_btn_dingdao_nor"), selectedImage: UIImage(named: "tab_btn_dingdan_hig"))
        v2.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "商品管理", image: UIImage(named: "tab_btn_shangpin_nor"), selectedImage: UIImage(named: "tab_btn_shangpin_hig"))
        v3.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "工作中心", image: UIImage(named: "tab_btn_gongzuo_nor"), selectedImage: UIImage(named: "tab_btn_gongzuo_hig"))
        v4.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "仓库管理", image: UIImage(named: "tab_btn_cangku_nor"), selectedImage: UIImage(named: "tab_btn_cangku_hig"))
        v5.tabBarItem = ESTabBarItem.init(ExampleBouncesContentView(), title: "个人中心", image: UIImage(named: "tab_btn_geren_nor"), selectedImage: UIImage(named: "tab_btn_geren_hig"))
        
        tabBarController.viewControllers = [v1, v2, v3, v4, v5]
        
        tabBarController.selectedIndex = 2
        
        let contentView = tabBarController
        
        if isAgain {
            let transtition = CATransition()
            transtition.duration = 0.5
            transtition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
            UIApplication.shared.keyWindow?.layer.add(transtition, forKey: "animation")
            let rootV = NavViewController(rootViewController: contentView)
            UIApplication.shared.keyWindow?.rootViewController = rootV
        }else{
            let window = UIWindow.init(frame: UIScreen.main.bounds)
            let rootV = NavViewController(rootViewController: contentView)
            window.rootViewController = rootV;
            self.window = window
            window.makeKeyAndVisible()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(changgeTabItem(notion:)), name: NSNotification.Name(rawValue: "changgeTabItem"), object: nil)
        
    }
    //MARK:--切换tab
    @objc func changgeTabItem(notion:Notification) {
        let dic = notion.userInfo
        tabBarC.selectedIndex = dic!["tag"] as Any as! Int
    }
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        //添加通知,才加载数据
        print(viewController)
    }
}