//
//  AppDelegate+http.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/7/1.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

extension AppDelegate {
    // MARK:根据公司获取登录方式
    func getLoginTypeHttpAction(){
        SinglePointWeChatHttp.sharedInstance().getLoginTypeHttpGetCmd(userid: judgmentStrNil(str: AccountInfo.sharedInstance().UserId), resultBlock: {[weak self] (value:Any) in
            self?.loginTypeHttpGetCmdTypeAction(array: value as! NSMutableArray)
        }) {(value:Any) in
            AccountInfo.sharedInstance().loginType = "2"
//            self?.group.leave()
        }
    }
    func loginTypeHttpGetCmdTypeAction(array:NSMutableArray) {
        if array.count != 0 {
            let item:String = array.firstObject as! String
            if (item == "3") {
                ///集团单点
                self.loginType = .SinglePointLoginType
                AccountInfo.sharedInstance().clearAccount()
            } else {
                /// 自带登录
                self.loginType = .OldLoginType
            }
            AccountInfo.sharedInstance().loginType = self.loginType.rawValue
        } else {
            AccountInfo.sharedInstance().loginType = "2"
        }
//        group.leave()
    }
    
    
    
    
    //访问量接口
    func getAccessHttpCmd(){
        let cmd:HttpCommand = AccessHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result  != nil {
                self?.httpAccessHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpAccessHttpCmd_devicenumber] = AccountInfo.sharedInstance().appUUID
        dic[kHttpAccessHttpCmd_companyname] = judgmentStrNil(str: AccountInfo.sharedInstance().infoCompanyName)
        dic[kHttpAccessHttpCmd_userid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpAccessHttpCmd_intertype] = SNHttpBaseCmd.getNetconnType()
        dic[kHttpAccessHttpCmd_devidetype] = ModelJudgeFunc.deviceModelName()
        dic[kHttpAccessHttpCmd_systemversion] = UIDevice.current.systemVersion
        dic[kHttpAccessHttpCmd_operator] = DeviceInformation.share().getcarrierName()
        dic[kHttpAccessHttpCmd_latutide] = judgmentStrNil(str:AccountInfo.sharedInstance().latutide)
        dic[kHttpAccessHttpCmd_address] = judgmentStrNil(str:AccountInfo.sharedInstance().address)
        dic[kHttpAccessHttpCmd_phonenumber] = ""
        dic[kHttpAccessHttpCmd_platform] = "iOS"
        dic[kHttpAccessHttpCmd_storage] = DeviceInformation.share().getDivceSize()
        dic[kHttpAccessHttpCmd_remainstorage] = DeviceInformation.share().getDivceSizetoTalCapacity()
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpAccessHttpResultResponse(result:RequestResult){
        let r:AccessHttpResult = result as! AccessHttpResult
        if r.isOk() {
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    //版本更新
    func getNewVersionUpdateHttpCmd(){
        let cmd:HttpCommand = NewVersionUpdateHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpNewVersionUpdateHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpAdvisoryHttpCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        dic[kHttpAdvisoryHttpCmd_attr] = attrDic
        dic[kHttpAdvisoryHttpCmd_orderby] = "createon"
        dic[kHttpAdvisoryHttpCmd_pageNum] = "0"
        dic[kHttpAdvisoryHttpCmd_pageSize] = "20"
        dic[kHttpAdvisoryHttpCmd_sort] = "desc"
        let filtersDic:NSMutableDictionary = NSMutableDictionary()
        if AccountInfo.sharedInstance().isTest == "1" {
//           测试版 正式版
            filtersDic[kHttpAdvisoryHttpCmd_value] = "41"
        } else if AccountInfo.sharedInstance().isTest == "2" {
            // 体验版
            filtersDic[kHttpAdvisoryHttpCmd_value] = "42"
        }
        let filtersArray = NSMutableArray()
        filtersArray.add(filtersDic)
        dic[kHttpAdvisoryHttpCmd_filters] = filtersArray
        
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpNewVersionUpdateHttpResultResponse(result:RequestResult){
        let r:NewVersionUpdateHttpResult = result as! NewVersionUpdateHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getNewVersionUpdateHttpResult()
            if array.count != 0{
                let model:NewVersionUpdateModel = array[0] as! NewVersionUpdateModel
                showOneAlert(title: "版本更新", message: ("请更新到"+model.versionNumber!), titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
                    self?.openUrl(urlString: model.downloadLink!)
                })
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    func openUrl(urlString:String){
        deAllSelecCompanyDepartment()
        let url = URL(string: urlString)
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {
                                        (success) in
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
        dropOutAPP()
    }
    // MARK:上传手机信息
    func getDeviceInformationHttpCmd(){
        let cmd:HttpCommand = DeviceInformationHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpDeviceInformationHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        cmd.requestInfo = DeviceInformation.share().getDeviceInformation(dic) as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = (dic as! [AnyHashable : Any])
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpDeviceInformationHttpResultResponse(result:RequestResult){
        let r:DeviceInformationHttpResult = result as! DeviceInformationHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getDeviceInformationHttpResult()
            if array.count != 0{
                SMToastView.showMessage((array[0] as! String) )
            }else{
                
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    // MARK:手机是否禁用
    func getUntuedCellPhoneHttpPostCmd(){
        let cmd:HttpCommand = UntuedCellPhoneHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpUntuedCellPhoneHttpPostResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let filtersDic:NSMutableDictionary = NSMutableDictionary()
        filtersDic[kHttpUntuedCellPhoneHttpPostCmd_key] = "ID"
        filtersDic[kHttpUntuedCellPhoneHttpPostCmd_opt] = "EQ"
        filtersDic[kHttpUntuedCellPhoneHttpPostCmd_type] = "S"
        filtersDic[kHttpUntuedCellPhoneHttpPostCmd_value] = AccountInfo.sharedInstance().appUUID
        let filtersArray = NSMutableArray()
        filtersArray.add(filtersDic)
        dic[kHttpUntuedCellPhoneHttpPostCmd_filters] = filtersArray
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    func httpUntuedCellPhoneHttpPostResultResponse(result:RequestResult){
        let r:UntuedCellPhoneHttpPostResult = result as! UntuedCellPhoneHttpPostResult
        if r.isOk() {
            let array:NSMutableArray = r.getUntuedCellPhoneHttpPostResult()
            self.judgmentPhone(httpArray: array)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    func judgmentPhone(httpArray:NSMutableArray){
        for index in 0..<httpArray.count {
            let httpModel:UntuedCellPhoneHttpPostListModel = httpArray[index] as! UntuedCellPhoneHttpPostListModel
            if httpModel.id == AccountInfo.sharedInstance().appUUID && httpModel.status == "N"{
                showOneAlert(title: "提示", message: "您的设备已被禁用，请联系管理员！", titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
                    self?.dropOutAPP()
                })
                deAllSelecCompanyDepartment()
                AccountInfo.sharedInstance().clearAccount()
                return
            }
        }
        if AccountInfo.sharedInstance().UserId != nil {
            //上传手机信息
            getDeviceInformationHttpCmd()
        }
    }
    
    // MARK:y应用公告
    func getMessageTemplateHttpPostCmd(){
        let cmd:HttpCommand = MessageTemplateHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMessageTemplateHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpMessageTemplateHttpPostCmd_companyname] = judgmentStrNil(str: AccountInfo.sharedInstance().infoCompanyName)
        attrDic[kHttpMessageTemplateHttpPostCmd_empid] = judgmentStrNil(str: AccountInfo.sharedInstance().UserId)
        let filtersArray = NSMutableArray()
        dic[kHttpMessageTemplateHttpPostCmd_filters] = filtersArray
        dic[kHttpMessageTemplateHttpPostCmd_attr] = attrDic
        dic[kHttpMessageTemplateHttpPostCmd_logic] = "or"
        dic[kHttpMessageTemplateHttpPostCmd_pageNum] = "1"
        dic[kHttpMessageTemplateHttpPostCmd_pageSize] = "10"
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpMessageTemplateHttpResultResponse(result:RequestResult){
        let r:MessageTemplateHttpResult = result as! MessageTemplateHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getMessageTemplateHttpResult()
            if array.count != 0{
                self.showLXFPopUpToolView(model: array[0] as! MessageTemplateModel)
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    /// 应用公告通知
    func showLXFPopUpToolView(model:MessageTemplateModel) {
        LXFPopUpToolView.sharedInstance().show(title: model.title!, content: model.content!)
    }
    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)
        }
    }
    ///注销用户
    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!
    }
}
