//
//  AppDelegate+JPUSH.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/6/27.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

extension AppDelegate:JPUSHRegisterDelegate {
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        
    }

    // 注册推送
    func setupJpush(launchOptions: [UIApplicationLaunchOptionsKey: 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)
        }
        // 注册极光推送
        //正式  cd8c71ebd290a618efaa72cd
        //测试  444b4a4c86a09bd2e27367fe
        JPUSHService.setup(withOption: launchOptions, appKey: "444b4a4c86a09bd2e27367fe", channel:"App Store" , apsForProduction: true);
        
        JPUSHService.crashLogON()
        //NotificationCenter.default.addObserver(self, selector: #selector(networkDidReceiveMessage(notification:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
        
    }
    // MARK: -JPUSHRegisterDelegate
    // iOS 10.x 需要
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        let userInfo = notification.request.content.userInfo;
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
            
        }
        print("1213",userInfo)
        receiveNotification(userInfo: userInfo as [NSObject : AnyObject])
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue)|Int(UNNotificationPresentationOptions.sound.rawValue))
    }
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        let userInfo = response.notification.request.content.userInfo;
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        completionHandler();
        receivePush(userInfo as! Dictionary<String, Any>)
        // 应用打开的时候收到推送消息
        //NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName_ReceivePush), object: NotificationObject_Sueecess, userInfo: userInfo)
        
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("444444",userInfo)
        receiveNotification(userInfo: userInfo as [NSObject : AnyObject])
        JPUSHService.handleRemoteNotification(userInfo);
        completionHandler(UIBackgroundFetchResult.newData);
    }
    // 接收到推送实现的方法
    func receivePush(_ userInfo : Dictionary<String,Any>) {
        // 角标变0
        JPUSHService.setBadge(0)
        UIApplication.shared.applicationIconBadgeNumber = 0;
        receiveNotification(userInfo: userInfo as [NSObject : AnyObject])
        // 剩下的根据需要自定义
        //self.tabBarVC?.selectedIndex = 0;
        //NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName_ReceivePush), object: NotificationObject_Sueecess, userInfo: userInfo)
    }
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("deviceToken==",deviceToken)
        JPUSHService.registerDeviceToken(deviceToken)
        if AccountInfo.sharedInstance().UserId == nil {
            UIApplication.shared.unregisterForRemoteNotifications()
            return
        }
//        JPUSHService.setTags([AccountInfo.sharedInstance().appUUID!], alias: AccountInfo.sharedInstance().UserId) { (code, tags, alias) in
//            print("code:",code,tags!,alias ?? String())
//        }
        JPUSHService.setTags([AccountInfo.sharedInstance().appUUID!], completion: { (iResCode, iTags, seq) in
            print(iResCode,iTags!,seq)
            } as JPUSHTagsOperationCompletion, seq: 0)
        
        JPUSHService.setAlias(AccountInfo.sharedInstance().UserId, completion: { (iResCode, iTags, seq) in
            print(iResCode,iTags!,seq)
        }, seq: 1)
    }
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        //NotificationCenter.default.post(name: NSNotification.Name(rawValue: "AuthorizedResult"), object: nil, userInfo: nil)
        print("收到通知1111：",userInfo)
        JPUSHService.handleRemoteNotification(userInfo)
        self.receiveNotification(userInfo: userInfo as [NSObject : AnyObject])
        
    }
//    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
//        JPUSHService.showLocalNotification(atFront: notification, identifierKey: nil)
//        [UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:]方法中调用completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert)
//    }
    
    func receiveNotification(userInfo: [NSObject : AnyObject]){
        let dic:NSDictionary = userInfo as NSDictionary
        print("收到通知2222：",dic)
        let keyArray:NSArray = dic.allKeys as NSArray
        
        //let alert2:String = dic .object(forKey: "content") as! String
        let aps:NSDictionary = dic .object(forKey: "aps") as! NSDictionary
        let alert:String = aps .object(forKey: "alert") as! String
        if dic .object(forKey: "id") != nil {
            AccountInfo.sharedInstance().messageId = dic .object(forKey: "id") as? String
        }
        var isDel = String()
        var isEnable = String()
        var deviceStatus = String()
        if keyArray.contains("isDel") {
            isDel = dic .object(forKey: "isDel") as! String
            if isDel == "Y"{
                logoutUserInfo(str: alert)
                return
            }
        }
        //
        if keyArray.contains("isEnable") {
            isEnable = dic .object(forKey: "isEnable") as! String
            if isEnable == "Y"{
                logoutUserInfo(str: alert)
                return
            }
        }
        if keyArray.contains("deviceStatus") {
            deviceStatus = dic .object(forKey: "deviceStatus") as! String
            if deviceStatus == "Y" {
                logoutUserInfo(str: alert)
                return
            }
        }
        
        print(alert)
        showAlert(title: "您有一条新消息", message: alert, titleCancelBtn: "取消", titleSecondBtn: "查看") {
            NotificationCenter.default.post(name: Notification.Name(rawValue: "gotoMessageWeb"), object: "0")
        }
        //print("-----",alert["body"] ?? NSDictionary())
        //let badge = aps["badge"] as! int //推送显示内容
        
    }
    //MARK: - 自定义消息回调
    func networkDidReceiveMessage(notification:NSNotification){
        print("收到通知------：",notification)
        let userInfo = notification.userInfo
        receiveNotification(userInfo: userInfo! as [NSObject : AnyObject])
        //        NSLog("content :%@", content)
    }
    func dropOutAPP()  {
        let app:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let window:UIWindow = app.window!
        UIView.animate(withDuration: 1.0, animations: {
            window.alpha = 0
            window.frame = CGRect(x:0, y: window.bounds.size.width, width:0 , height:0 )
        }) { (finished:Bool) in
            exit(0)
        }
    }
    //注销用户
    func logoutUserInfo(str:String){
        deAllSelecCompanyDepartment()
        AccountInfo.sharedInstance().clearAccount()
        showOneAlert(title: "提示", message: str, titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
            self?.dropOutAPP()
        })
    }
    
    func judgmentStrNil(str:String?) -> String{
        if str == nil {
            return ""
        }
        return str!
    }
}
