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

import UIKit
import SnapKit
enum OpenUrlType: Int{
    case OpenAppType = 1
    case DownloadType = 2
}

class BaseViewController: UIViewController,UIGestureRecognizerDelegate {

    var queue = DispatchQueue.init(label: "com.custom.thread", qos: .default, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil)
    var group = DispatchGroup()
    
    var createArgs:AnyObject!
    // 当前statusBar使用的样式
    var style: UIStatusBarStyle = .default
    // 重现statusBar相关方法
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return self.style
    }
    deinit {
        print("------------------------------")
        print(NSStringFromClass(self.classForCoder)+"释放")
        print("------------------------------")
    }
    
    lazy var positionView : PositionView = {
        let positionView = PositionView.init(frame: CGRect(x:0, y: 0, width:64 , height:44))
        return positionView;
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        addNotificationCenter()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    }
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }
    /// 添加响应事件
    func addNotificationCenter(){
        NotificationCenter.default.addObserver(self, selector: #selector(actionCustomerServiceVC), name: NSNotification.Name(rawValue: "gotoCustomerServiceVC"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(gotoMessageVC), name: NSNotification.Name(rawValue: "gotoMessageWeb"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(gotoVoiceDialogueVC), name: NSNotification.Name(rawValue: "gotoVoiceDialogueVC"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(gotoIntelligentCustomerService), name: NSNotification.Name(rawValue: "gotoIntelligentCustomerService"), object: nil)
    }
    /// 删除响应事件
    func addRemoveObserver(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoCustomerServiceVC"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoMessageWeb"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoVoiceDialogueVC"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoIntelligentCustomerService"), object: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    // 视图即将消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoCustomerServiceVC"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoMessageWeb"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoVoiceDialogueVC"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "gotoIntelligentCustomerService"), object: nil)
//        self.wr_setNavBarShadowImageHidden(false)
    }
    // 视图已经消失
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // 导航栏不遮挡
    func isNavigationBarObstructed(){
        //        self.edgesForExtendedLayout = UIRectEdge.bottom
    }
    func pushViewController(viewController:UIViewController,animated:Bool){
        self.navigationController?.pushViewController(viewController, animated: true)
    }
    // 设置导航栏
    func initTitleBar(){
//        self.view.backgroundColor = loginBg_Color
        self.view.backgroundColor = UIColorFromRGB(rgbValue: 0xF4F9FD)
        //        self.defaultBackButtonItem()
        //        self.initTitleBarColor()
        self.initReturnBtn()
    }
    //跳转智能客服
    @objc func gotoIntelligentCustomerService(){
        
    }
    func addPositionView(){
        let leftN:UIBarButtonItem = UIBarButtonItem.init(customView: positionView)
        self.navigationItem.leftBarButtonItem = leftN
    }
    func initReturnBtn(){
        let leftN:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "return_image")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(arrowResponse))
        self.navigationItem.leftBarButtonItem = leftN
    }
    private func defaultBackButtonItem(){
        let barButtonItem :UIBarButtonItem=UIBarButtonItem.init(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
        self.navigationItem.backBarButtonItem=barButtonItem
        self.navigationController!.navigationBar.tintColor=UIColor.white
        self.navigationController?.navigationBar.barTintColor=statusBarColor
        self.navigationController?.navigationBar.subviews[0].backgroundColor=statusBarColor
        self.navigationController?.navigationBar.isTranslucent = false
    }
    private func initTitleBarColor(){
        let dict:[NSAttributedStringKey:AnyObject]=[NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue):UIColor.white, NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):UIFont.systemFont(ofSize: 17.0)]
        self.navigationController!.navigationBar.titleTextAttributes = dict
    }
    @objc func arrowResponse(){
        self.navigationController?.popViewController(animated: true)
    }
    func setStatusBarBackgroundColor(){
        let h = STATUBAR_HEIGHT()
        let stateView:UIView = UIView.init(frame: CGRect(x:0, y: 0, width:SCREEN_WHIDTH() , height:h ))
        stateView.backgroundColor = statusBarColor
        self.view.addSubview(stateView)
    }
    /// 导航栏透明
    func hideNavigationBar(){
//        self.wr_setNavBarBackgroundAlpha(0)
//        self.wr_setNavBarShadowImageHidden(true)
    }
    /// 将导航栏 上移动
    func mobileNavigationBar(progress:CGFloat){
        self.navigationController?.navigationBar.wr_setTranslationY(-(NAV_HEIGHT()) * progress)
        self.navigationController?.navigationBar.wr_setBarButtonItemsAlpha(1-progress, hasSystemBackIndicator: true)
    }
   
    
    //跳转客服
    @objc func actionCustomerServiceVC() {
//        let vc:WebSwiftViewController = WebSwiftViewController()
//        vc.newType = .OrdinaryNewsType
//        vc.isHomePushType = .YesIsHomePushType
//        vc.isShowTitleType = .NoShowTitleType
//        vc.webViewUrl = AccountInfo.sharedInstance().getCustomerServiceUrl()+judgmentStrNil(str: AccountInfo.sharedInstance().UserId)+"&userCompany="+judgmentStrNil(str: AccountInfo.sharedInstance().infoCompanyName)+"&userDepartment="+judgmentStrNil(str: AccountInfo.sharedInstance().infoDeptName)+"&userName="+judgmentStrNil(str: AccountInfo.sharedInstance().userName)+"&isOutUser="+judgmentStrNil(str: AccountInfo.sharedInstance().externalUser)
        let vc = CustomerServiceRootVC()
//        let vc = DialogueViewController()
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    
    //跳转 修改密码
    func gotoChangePassWordViewController(changePassWordType:ChangePassWordType){
        let vc:ChangePassWordViewController=ChangePassWordViewController()
        vc.changePassWordType = changePassWordType
        //        vc.signOutBlock = signOutBlock
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    func getHtitleType(htitle:String?) -> IsShowTitleType {
        if htitle == "2" {
            return .NoShowTitleType
        }
        return .YesShowTitleType
    }
    /// 获取拼接的参数
    public func getWebCookie(urlStr:String?) -> String {
        if (urlStr?.contains("?"))! {
            let string = urlStr! as NSString
            let startRange = string.range(of: "?")
            let range = NSMakeRange(startRange.location+startRange.length, urlStr!.count-startRange.location-1)
            let result = string.substring(with: range)
            return result
        }
        return urlStr!
    }
    /// 获取问号前的链接
    public func getWebCookieUrl(urlStr:String?) -> String {
        if (urlStr?.contains("?"))! {
            let string = urlStr! as NSString
            let startRange = string.range(of: "?")
            let range = NSMakeRange(0, startRange.location)
            let result = string.substring(with: range)
            return result
        }
        return urlStr!
    }
    func getisShowTitleType(urlStr:String?) -> IsShowTitleType {
        if (urlStr?.contains(","))! {
            let string = urlStr! as NSString
            let startRange = string.range(of: ",")
            let range = NSMakeRange(startRange.location+startRange.length, 1)
            let result = string.substring(with: range)
            if result == "0"{
                return .NoShowTitleType
            }else{
                return .YesShowTitleType
            }
        }
        return .YesShowTitleType
    }
    func setisShowTitleType(urlStr:String?,isShowTitleType:IsShowTitleType) -> String? {
        if AccountInfo.sharedInstance().oldType == "1" {
            return urlStr
        }
        if isShowTitleType == .NoShowTitleType && (urlStr?.contains(",0"))! {
            let string = urlStr! as NSString
            let startRange = string.range(of: ",")
            let range = NSMakeRange(startRange.location+startRange.length, 1)
            let result = string.substring(with: range)
            if result == "0"{
                return urlStr?.replacingOccurrences(of:",0", with: "")
            }else{
                return urlStr?.replacingOccurrences(of:",1", with: "")
            }
        }
        return urlStr
    }
    ///跳转到消息页面
    @objc func gotoMessageVC(){
        
    }
    ///唤醒进入
    @objc func gotoVoiceDialogueVC(){
        let vc = VoiceDialogueVC()
        vc.gotoVoiceDialogueType = .VoiceDialogueWeakUp
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    ///正常跳转
    @objc func gotoNomVoiceDialogueVC(){
        let vc = VoiceDialogueVC()
        vc.gotoVoiceDialogueType = .NomVoiceDialogue
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    
    //跳转ScanCodeViewController 扫码
    public func gotoQRCodeSwiftViewController(isHomePushType:IsHomePushType){
        let vc:QRCodeSwiftViewController=QRCodeSwiftViewController()
        vc.isHomePushType = isHomePushType
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    //跳转ScanCodeViewController 扫码,并返回扫描结果
    public func gotoQRCodeCallBackViewController(isHomePushType:IsHomePushType,callBackBlock:@escaping passParameterBlock){
        let vc:QRCodeCallBackViewController=QRCodeCallBackViewController()
        vc.isHomePushType = isHomePushType
        vc.callBackBlock = callBackBlock
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    ///加载中。。。
    public func showHintView(){
        MBProgressHUDFunc.sharedInstance().showHintView()
//        CBToast.showIndicatorToastAction(message: "加载中...")
    }
    public func hidenHintView(){
        MBProgressHUDFunc.sharedInstance().hidenHintView()
//        CBToast.hiddenIndicatorToastAction()
    }
    ///版本更新 下载APP
    public func downloadUrl(urlString:String){
        let url = URL(string: urlString)
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                                        (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
        dropOutAPP()
    }
    public func getSignInAction(model:ApplicationHttpListModel)->String{
        if AccountInfo.sharedInstance().oldType == "0" {
            return model.comments! + "?userId="+AccountInfo.sharedInstance().UserId!
        }
        if model.appid == "ZPeuHeJgPWNRhyQs" {
//            model.hurl = "https://mobileportal.shaphar.com:8443/SYERP/SYOrderLife/#/information"
            //            httpDetailModel.hurl = "http://192.168.1.149:8080/#/upcoming"
        }
//        model.hurl = "http://192.168.0.21:8081/#/login"
//        model.hurl = "https://mobiletms.plovehj.com/#/entrustTransList"
        var str = model.hurl
        if model.applicationPlatformsType == .AndroidiOSType {
            let value = "userId="+AccountInfo.sharedInstance().UserId!+"&loginType="+judgmentStrNil(str: AccountInfo.sharedInstance().loginType)+"&IDMToken="+judgmentStrNil(str: AccountInfo.sharedInstance().singlePoint_access_token)
            str = model.iosopenurl!
            str = str! + (WebActionOC.share()?.encryptAES(value, key: judgmentStrNil(str: model.appid)))!
            return str!
        }
        if model.pointstate == "1" {
            if (str?.contains("?"))! && model.scope == "9" {
                str = str! + "&userId="
            } else {
                str = str! + "?userId="
            }
            str = str!+AccountInfo.sharedInstance().UserId!+"&loginType="+judgmentStrNil(str: AccountInfo.sharedInstance().loginType)+"&IDMToken="+judgmentStrNil(str: AccountInfo.sharedInstance().singlePoint_access_token)
        } else{
            return str!
        }
        if model.companystate == "1" {
            str = str! + "&companyName="+AccountInfo.sharedInstance().infoCompanyName!
        }
        if model.passstate == "1" {
            str = str! + "&passWord="+judgmentStrNil(str: AccountInfo.sharedInstance().passWord!)
        }
        
        if model.partstate == "1" {
            str = str! + "&department="+AccountInfo.sharedInstance().infoDeptName!
        }
        return str!
    }
    //下载APP
    public func downloadOpenApp(urlString:String?,openUrlType:OpenUrlType){
//        var str = urlString
//        if openUrlType == .OpenAppType {
//            str = str! + getOpurlJson()
//        }
//        if openUrlType == .OpenAppType {
//            if AccountInfo.sharedInstance().singlePoint_access_token != nil && AccountInfo.sharedInstance().singlePoint_access_token != "" && AccountInfo.sharedInstance().loginType == "1" && !isSingOutAction() {
//                AccountInfo.sharedInstance().clearAccount()
//                deAllSelecCompanyDepartment()
//                showOneAlert(title: "温馨提示", message: "登录已失效，请重新登录！", titleSecondBtn: "确定") {
//                    NotificationCenter.default.post(name: Notification.Name(rawValue: "setLoginWindow"), object: "0")
//                }
//                return
//            }
//        }
//        let openUrl = "itms-apps://itunes.apple.com/app/id1236176492"
        
        let url = URL(string: (WebActionOC.share()?.getUrl(urlString)!)!)
        if url == nil {
            SMToastView.showMessage("下载地址有误，请联系管理员！")
            return
        }
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {(success) in
                                        print(success)
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    public func getOpurlJson()->String{
        return "userId="+AccountInfo.sharedInstance().UserId!+"&token=temptoken20181221"
    }
    //是否安装APP
    public func isInstallation(urlString:String?)->Bool{
        if urlString?.count == 0 || urlString == nil {
            return true
        }
        let url = URL(string: urlString!)
        if url == nil {
            return true
        }
        if UIApplication.shared.canOpenURL(url!) {
            return false
        }
        return true
    }
    //存储选中的公司部门
    public func setSelecCompanyDepartment(info:SelecCompanyDepartmentInfo,block:@escaping selectBlock){
        FGDBHelper.sharedInstance().save(info) { (arg0) in
            let (isSuccess) = arg0
            if isSuccess {
                block()
                print("存储成功！")
            }else{
                SMToastView.showMessage("存储失败！")
                print("存储失败！")
            }
        }
    }
    //获取早已选中过的 某个类别 公司部门
    public func getSelecCompanyDepartment(tags:String)->SelecCompanyDepartmentInfo{
        let infoArray:NSMutableArray = FGDBHelper.sharedInstance().queryCompanyDepartmentInfo(tags, andUserId: AccountInfo.sharedInstance().UserId)
        for index in 0..<infoArray.count {
            let info:SelecCompanyDepartmentInfo = infoArray[index] as! SelecCompanyDepartmentInfo
            return info
        }
        return SelecCompanyDepartmentInfo()
    }
    //获取早已选中过的所有公司部门
    public func getAllSelecCompanyDepartment()->NSMutableArray{
        let infoArray:NSMutableArray = FGDBHelper.sharedInstance().allCompanyDepartmentInfo(AccountInfo.sharedInstance().UserId)
        if infoArray.count != 0 {
            return infoArray
        }
        return NSMutableArray()
    }
    //注销用户
    public func logoutUserInfo(str:String){
        deAllSelecCompanyDepartment()
        AccountInfo.sharedInstance().clearAccount()
        showOneAlert(title: "提示", message: str, titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
            self?.dropOutAPP()
        })
    }
    func addd(){
        showOneAlert(title: "提示", message: "单点未开启,请联系管理员！", titleSecondBtn: "确定", blockOtherBtn: {
            
        })
    }
    // 退出APP
    public func dropOutAPP()  {
        let app:AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let window:UIWindow = app.window!
        UIView.animate(withDuration: 2.0, animations: {
            window.alpha = 0
            window.frame = CGRect(x:0, y: window.bounds.size.width, width:0 , height:0 )
        }) { (finished:Bool) in
            exit(0)
        }
    }
    public func deAllSelecCompanyDepartment(){
        FGDBHelper.sharedInstance().deleteAllCompanyDepartmentInfo(AccountInfo.sharedInstance().UserId) { (bool) in
            print(bool)
        }
    }
    // 用手机浏览器
    public func openSafari(urlString:String?){
        if urlString == nil {
            SMToastView.showMessage("链接地址有误，请联系管理员！")
            return
        }
        let url = URL(string: (WebActionOC.share()?.getUrl(urlString)!)!)
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                                        (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    
}
