//
//  AppDelegate+JUPH.swift
//  SYMobilePortal
//
//  Created by xiejiangbo on 2018/5/15.
//  Copyright © 2018年 yin chen. All rights reserved.
//

import UIKit

extension AppDelegate: JPUSHRegisterDelegate {
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]!) {
        
    }
    
    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 as JPUSHRegisterDelegate))
        } 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
        // 体验版 c0eb5d604f19e9d58af5f8de
//        188502 106785
        if AccountInfo.sharedInstance().isTest == "1" {
            JPUSHService.setup(withOption: launchOptions, appKey: "444b4a4c86a09bd2e27367fe", channel:"App Store" , apsForProduction: true);
//            JPUSHService.setup(withOption: launchOptions, appKey: "f5294632ffc8affe034ba5f9", channel:"App Store" , apsForProduction: true);
        } else if AccountInfo.sharedInstance().isTest == "2"{
            JPUSHService.setup(withOption: launchOptions, appKey: "c0eb5d604f19e9d58af5f8de", channel:"App Store" , apsForProduction: true);
        } else {
            JPUSHService.setup(withOption: launchOptions, appKey: "cd8c71ebd290a618efaa72cd", channel:"App Store" , apsForProduction: true);
        }
        
        JPUSHService.crashLogON()
        JPUSHService.registrationIDCompletionHandler {[weak self] (code, registrationID) in
            print("极光")
//            print(registrationID!)
            AccountInfo.sharedInstance().juph_registrationID = self?.judgmentStrNil(str: registrationID)
//            SMToastView.showMessage(registrationID)
        }
//        var voipregistry: = 
        
        
        // 获取推送消息
//        let remote:NSMutableDictionary = launchOptions![UIApplicationLaunchOptionsKey.remoteNotification] as! NSMutableDictionary
//        if remote != nil {
//            if remote.allKeys.count != 0 {
//                receiveNotification(userInfo: remote as [NSObject : AnyObject])
//            }
//        }
//        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)
        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!], completion: { (iResCode, iTags, seq) in
            print("jiguang",iResCode,iTags!,seq)
            } as JPUSHTagsOperationCompletion, seq: 0)
        JPUSHService.setAlias(AccountInfo.sharedInstance().UserId, completion: { (iResCode, iTags, seq) in
            print("jiguang",iResCode,iTags!,seq)
        }, seq: 1)
        SinglePointWeChatHttp.sharedInstance().juphRegistrationIDActionHttp { [weak self] (value:Any) in
        } errorBlock: { (value:Any) in
        }
    }
    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 receiveNotification(userInfo: [NSObject : AnyObject]){
        let dic:NSDictionary = userInfo as NSDictionary
        print("收到通知2222：",dic)
        AccountInfo.sharedInstance().UMS_messageJSON = dicValueString(dic as! [String : Any])
        let keyArray:NSArray = dic.allKeys as NSArray
        
        //let alert2:String = dic .object(forKey: "content") as! String
        guard let aps:NSDictionary = try? dic .object(forKey: "aps") as! NSDictionary else {
            return
        }
        
        var alert = ""
        let alertsss:AnyObject = aps .object(forKey: "alert") as! AnyObject
        if alertsss is String {
            alert = aps .object(forKey: "alert") as! String
        } else if alertsss is NSDictionary {
            let alertDic:NSDictionary = aps .object(forKey: "alert") as! NSDictionary
            if alertDic .object(forKey: "body") != nil {
                alert = (alertDic .object(forKey: "body") as? String)!
            }
        }
        if dic .object(forKey: "id") != nil { 
            AccountInfo.sharedInstance().messageId = dic .object(forKey: "id") as? String
        } else {
            AccountInfo.sharedInstance().messageId = ""
        }
        
        if dic .object(forKey: "messageSource") != nil {
            AccountInfo.sharedInstance().UMS_messageType = "1"
        } else {
            AccountInfo.sharedInstance().UMS_messageType = "0"
        }
        if dic .object(forKey: "messageDetaUrl") != nil {
            AccountInfo.sharedInstance().UMS_messageDetaUrl = dic .object(forKey: "messageDetaUrl") as? String
        } else {
            AccountInfo.sharedInstance().UMS_messageDetaUrl = ""
        }
        
        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")
        }
        SinglePointWeChatHttp.sharedInstance().juphMessageJsonActionHttp { [weak self] (value:Any) in
        } errorBlock: { (value:Any) in
        }
        //print("-----",alert["body"] ?? NSDictionary())
        //let badge = aps["badge"] as! int //推送显示内容
        
    }
    //MARK: - 自定义消息回调
    @objc func networkDidReceiveMessage(notification:NSNotification){
        print("收到通知------：",notification)
        let userInfo = notification.userInfo
        receiveNotification(userInfo: userInfo! as [NSObject : AnyObject])
        //        NSLog("content :%@", content)
    }
}
