//
//  AppDelegate.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/9/3.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,WXApiDelegate  {
    
    var loginType:LoginType = .OldLoginType
    
    var window: UIWindow?
    lazy var windows:UIWindow = {
        let windows = UIApplication.shared.keyWindow
        return windows!
    }()
//    var queue = DispatchQueue.init(label: "com.AppDelegate", qos: .default, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil)
//    var group = DispatchGroup()
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        AccountInfo.sharedInstance().weChat_appid = "wx3d3b2a6669b28feb"
        AccountInfo.sharedInstance().singlePoint_appId = "K2"
        AccountInfo.sharedInstance().singlePoint_remoteIp = "10.11.180.80"
        let bool = WXApi.registerApp(AccountInfo.sharedInstance().weChat_appid!, universalLink: "https://yzsreport.shaphar.com/shaphar/")
        if bool {print("成功！")} else {print("失败！")}
        /// 键盘
        IQKeyboardManager.shared.enable = true
//        2体验版 1 测试版 0正式 106785
        AccountInfo.sharedInstance().isTest = "1"
        AccountInfo.sharedInstance().messageNumber = "0"
//        1新接口 0老接口
        if AccountInfo.sharedInstance().oldType == nil {
            deAllSelecCompanyDepartment()
            AccountInfo.sharedInstance().clearAccount()
        }
        
        // 199476 1234@qwer
        AccountInfo.sharedInstance().oldType = "1"
        AccountInfo.sharedInstance().UMS_messageJSON = ""
        AccountInfo.sharedInstance().messageId = ""
        AccountInfo.sharedInstance().UMS_messageType = ""
        
        if (AccountInfo.sharedInstance().webViewUrl == nil) {
            AccountInfo.sharedInstance().webViewUrl = ""
        }
        AccountInfo.sharedInstance().CustomerServicePower = ""
//        AccountInfo.sharedInstance().UMS_messageDetaUrl = "https://employeedev.shaphar.com/mobile-portal/messagedetail/1174"
//        AccountInfo.sharedInstance().UserId = "199476"
//        网络框架
        ProjectConfigGroup.initHttpConfig()
        HTHttpConfig.sharedInstance().isout = false
        if AccountInfo.sharedInstance().appUUID == nil {
//            AccountInfo.sharedInstance().appUUID = AppIdentUUID.share().getAllDeviceUUID()
            AccountInfo.sharedInstance().appUUID = self.getAppid()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(addTabBar), name: NSNotification.Name(rawValue: "addTabBarWindow"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(setLoginWindow), name: NSNotification.Name(rawValue: "setLoginWindow"), object: nil)
//        print(AccountInfo.sharedInstance().loginType!)
        if AccountInfo.sharedInstance().loginType == nil {
            AccountInfo.sharedInstance().clearAccount()
            AccountInfo.sharedInstance().loginType = "2"
        }
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId == "" {
            setLoginWindow()
        } else {
            addTabBar()
//         版本更新
            getNewVersionUpdateHttpCmd()
//         设备是否被禁用
            getUntuedCellPhoneHttpPostCmd()
        }
//        if AccountInfo.sharedInstance().loginType == nil && AccountInfo.sharedInstance().UserId != nil {
//            setLoginTypeToWindow()
//        }
//        setWindow()
        
        SNHttpBaseCmd.networkTestingActionTRUEBlock {
        }
        
        
//        https://www.shaphar.com/shaphar/apple-app-site-association
        WebActionOC.share().clearCache()
        addBugly()
//        极光推送
        setupJpush(launchOptions: launchOptions)
        JPUSHService.setBadge(0)
        UIApplication.shared.applicationIconBadgeNumber = 0
//        AddressConfig.sharedInstance().initLacationManager()
//        AddressConfig.sharedInstance().startUpdatingLocation()

//      访问量
        getAccessHttpCmd()
        deAllSelecCompanyDepartment()
        
        return true
    }
    /// 根据用户登录方式
//    func setLoginTypeToWindow(){
//        queue.async(group: group, execute: {[weak self] in
//            self?.group.enter()
//            self?.getLoginTypeHttpAction()
//        })
//        group.notify(queue: DispatchQueue.main) {[weak self] in
//            self?.setWindow()
//        }
//    }
    func setWindow(){
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId == "" {
            self.setLoginWindow()
        } else {
            self.addTabBar()
            //         版本更新
            self.getNewVersionUpdateHttpCmd()
            //         设备是否被禁用
            self.getUntuedCellPhoneHttpPostCmd()
        }
    }
    
    func addBugly(){
        if AccountInfo.sharedInstance().isTest == "1" {
            // 测试版
        } else if AccountInfo.sharedInstance().isTest == "2" {
            // 体验版
            Bugly.start(withAppId: "24a6f9c175")
        } else {
            // 正式版
            Bugly.start(withAppId: "67a82c474b")
        }
    }
    /// 获取设备id
    func getAppid()->String{
        if AccountInfo.sharedInstance().isTest == "1" {
            // 测试版
            return AppIdentUUID.share().getAllDeviceUUID()
        } else if AccountInfo.sharedInstance().isTest == "2" {
            // 体验版
            return AppIdentUUID.share().getAllDeviceUUID() + "NEW"
        } else {
            // 正式版
            return AppIdentUUID.share().getAllDeviceUUID()
        }
    }
    @objc func addTabBar(){
        
        self.window?.removeFromSuperview()
        let nav = RootTabBarViewController.init()
        self.window?.rootViewController = nav
        self.window?.backgroundColor = UIColor.white
        self.window?.makeKeyAndVisible()
        setNavBarAppearence()
        if AccountInfo.sharedInstance().UserId != nil {
//            setVoiceWindow()
        }
        getMessageTemplateHttpPostCmd()
        initIFly()
    }
    @objc func setLoginWindow()  {
//        微信授权登录 已测试
//        let nav = UINavigationController.init(rootViewController: SinglePointViewController())
//        IDM单点登录 加微信授权登录
        let nav = UINavigationController.init(rootViewController: SinglePointWeChatVC())
//        旧的登录方式
//        let nav = UINavigationController.init(rootViewController: LoginViewController())
        SuspensionView.share().getsuspensionBtn()?.isHidden = false
        self.window?.rootViewController = nav
        setNavBarAppearence()
        self.window?.makeKeyAndVisible()
    }
    //设置导航栏
    func setNavBarAppearence()  {
        WRNavigationBar.wr_widely()
//        WRNavigationBar.wr_setBlacklist(["MineViewController","HomeViewController"])
        WRNavigationBar.wr_setDefaultNavBarBarTintColor(UIColor.white)
//        WRNavigationBar.wr_setDefaultNavBarTintColor(UIColorFromRGB(rgbValue: 0x747782))
        WRNavigationBar.wr_setDefaultNavBarTitleColor(UIColorFromRGB(rgbValue: 0x23262A))
        WRNavigationBar.wr_setDefaultNavBarTintColor(UIColor.white)
        WRNavigationBar.wr_setDefaultStatusBarStyle(.default)
        WRNavigationBar.wr_setDefaultNavBarShadowImageHidden(false)
        
    }
    //删除用户 公司数据库
    func deAllSelecCompanyDepartment(){
        FGDBHelper.sharedInstance().deleteAllCompanyDepartmentInfo(AccountInfo.sharedInstance().UserId) { (bool) in
            print(bool)
        }
        AccountInfo.sharedInstance().selecCompanyName = nil
        AccountInfo.sharedInstance().sysUserId = nil
        AccountInfo.sharedInstance().selecDepartmentName = nil
        AccountInfo.sharedInstance().sysOrg = nil
        AccountInfo.sharedInstance().sysOrgService = nil
        AccountInfo.sharedInstance().sysType = nil
        AccountInfo.sharedInstance().docId = nil
        AccountInfo.sharedInstance().db_source = nil
        AccountInfo.sharedInstance().sysUserId = nil
        AccountInfo.sharedInstance().partyOpcode = nil
        AccountInfo.sharedInstance().cmsRealDb = nil
        AccountInfo.sharedInstance().cmsTestDb = nil
        AccountInfo.sharedInstance().omsRealDb = nil
        AccountInfo.sharedInstance().omsTestDb = nil
        AccountInfo.sharedInstance().tmsRealDb = nil
        AccountInfo.sharedInstance().tmsTestDb = nil
        AccountInfo.sharedInstance().appRealDb = nil
        AccountInfo.sharedInstance().appTestDb = nil
        AccountInfo.sharedInstance().myApplicationCellNum = "0"
    }
    func initIFly(){
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId?.count == 0 {
            return
        }
        IFLYSpeechTwo.share().initIfly()
        BDVoiceWakeUp.share().initwakeupEventManager()
        BDVoiceWakeUp.share().startWakeup()
//        IFlySpeech.share().initIfly()
//        VoiceWaveView.share().initView()
//        VoiceWaveView.share().getBagView().frame = CGRect(x:0, y: SCREEN_HEIGHT()-HEIGHT_TAB_BAR()-HEIGHT_BOTTOM_MARGIN()-50, width:SCREEN_WHIDTH() , height:50 )
//        window?.addSubview(VoiceWaveView.share().getBagView())
    }
    
    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.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
        UIApplication.shared.cancelAllLocalNotifications()
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId?.count == 0 {
            return
        }
        BDVoiceWakeUp.share().stopWakeup()
        // 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 applicationWillEnterForeground(_ application: UIApplication) {
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId?.count == 0 {
            return
        }
        BDVoiceWakeUp.share().startWakeup()
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    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.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return WXApi.handleOpen(url, delegate: WXApiManager.shared())
    }
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return WXApi.handleOpen(url, delegate: WXApiManager.shared())
    }
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: WXApiManager.shared())
    }
}

