//
//  SinglePointViewController+http.swift
//  MobilePortal
//
//  Created by caiyang on 2020/7/29.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit

extension SinglePointViewController {
    // MARK:设备是否可用绑定
    func getDeviceDisabledHttpPostCmd(){
        let cmd:HttpCommand = DeviceDisabledHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpDeviceDisabledHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpDeviceDisabledHttpPostCmd_userid] = AccountInfo.sharedInstance().UserId
        dic[kHttpDeviceDisabledHttpPostCmd_id] = AccountInfo.sharedInstance().appUUID
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpDeviceDisabledHttpResultResponse(result:RequestResult){
        let r:DeviceDisabledHttpResult = result as! DeviceDisabledHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getDeviceDisabledHttpResult()
            if (array.count == 0) {
                /// 上传手机信息
                getLoginDeviceInformationHttpCmd()
//                getUntuedCellPhoneHttpPostCmd()
//                getDeviceDisabledHttpPostCmd()
            } else {
                SMToastView.showMessage((array[0] as! String))
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        hidenHintView()
    }
    /// 获取登录方式
    func getScopeListHttpCmd(){
        let cmd:HttpCommand = ScopeListHttpCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpScopeListHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpSNHttpBasePostCmd_system] = "logintype"
        if AccountInfo.sharedInstance().UserId == nil || AccountInfo.sharedInstance().UserId == "" {
            dic[kHttpSNHttpBasePostCmd_companyname] = "上药控股有限公司"
        } else {
            dic[kHttpSNHttpBasePostCmd_companyname] = judgmentStrNil(str: AccountInfo.sharedInstance().infoCompanyName)
        }
        cmd.requestInfo = dic as [NSObject:AnyObject]
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpScopeListHttpResultResponse(result:RequestResult){
        let r:ScopeListHttpResult = result as! ScopeListHttpResult
        if r.isOk() {
            let httpArray = r.getScopeListHttpResult() as NSMutableArray
            self.selectSinglePointTypeAction(array: httpArray)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    func selectSinglePointTypeAction(array:NSMutableArray) {
        for index in 0..<array.count {
            let item:ScopeListHttpModel = array[index] as! ScopeListHttpModel
            /// 1.自带登录；2.老单点；3.集团单点
            if (index == 0) {
                if (item.name == "3" && item.state == "1") {
                    ///集团单点
                    //                    loginGetAccess_token()
                    self.loginType = .SinglePointLoginType
                    
                } else {
                    /// 自带登录
                    if self.loginInitType == .LoginActionType {
                        self.getLoginHttpPostCmdCmd()
                    }
                    self.loginType = .OldLoginType
                }
                AccountInfo.sharedInstance().loginType = self.loginType.rawValue
            }
        }
    }
    //版本更新
    func getNewVersionUpdateHttpCmd(){
        showHintView()
        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!)
                })
                //                SMAlertView.showAlert("版本更新", cancelTitle: ("请更新到"+model.versionNumber!), delegate: self)
                hidenHintView()
            } else {
                getUntuedCellPhoneHttpPostCmd()
            }
        }else{
            hidenHintView()
            getUntuedCellPhoneHttpPostCmd()
            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("请查看当前网络状态！")
        }
        hidenHintView()
    }
    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
            } else {
//                autoLogin()
//                if self.loginInitType == .LoginActionType {
//                    getLoginDeviceInformationHttpCmd()
//                }
            }
        }
    }
    // MARK:登录接口
    func getLoginHttpPostCmdCmd(){
        showHintView()
        let cmd:HttpCommand = LoginHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpLoginHttpPostResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpLoginHttpPostCmd_userid] = self.loginView.userTextView.text
        dic[kHttpLoginHttpPostCmd_password] = self.loginView.passTextView.text
        //dic[kHttpLoginHttpPostCmd_password] = ""
        dic[kHttpLoginHttpPostCmd_ticket] = AccountInfo.sharedInstance().appUUID
        dic[kHttpLoginHttpPostCmd_type] = ""
        
        let attrDic:NSMutableDictionary = NSMutableDictionary()
        attrDic[kHttpLoginHttpPostCmd_attr] = dic
        
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = attrDic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpLoginHttpPostResultResponse(result:RequestResult){
        let r:LoginHttpPostResult = result as! LoginHttpPostResult
        if r.isOk() {
            let array:NSMutableArray = r.getLoginHttpPostList()
            if array.count != 0{
                SMToastView.showMessage(array[0] as? String )
                AccountInfo.sharedInstance().clearAccount()
                self.hidenHintView()
            }else{
                if loginView.passTextView.text == "123456" && self.loginType == .OldLoginType{
                    
                    //                    AccountInfo.sharedInstance().clearAccount()
                    SMToastView.showMessage("您当前的密码为初始密码，请修改密码！")
                    AccountInfo.sharedInstance().UserId = ""
                    self.loginView.passTextView.text = ""
                    self.hidenHintView()
                    self.logingotoChangePassWordViewController(changePassWordType: .LoginChangePassWordType)
                }else{
//                    AccountInfo.sharedInstance().passWord = self.loginView.passTextView.text
                    getLoginDeviceInformationHttpCmd()
                }
            }
        }else{
            AccountInfo.sharedInstance().clearAccount()
            SMToastView.showMessage("请查看当前网络状态！")
            self.hidenHintView()
        }
        
    }
    
    /// 上传手机信息
    func getLoginDeviceInformationHttpCmd(){
        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()
        
    }
    // MARK:上传手机信息成功后 刷新页面
    override 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) )
                self.hidenHintView()
            }else{
                /// 获取个人信息
                getMyInformationHttpGetCmd()
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
            self.hidenHintView()
        }
        
    }
    // MARK:获取个人信息接口
    func getMyInformationHttpGetCmd(){
//        let cmd:HttpCommand = MyInformationHttpGetCmd.init(version: PHttpVersion_v1)
//        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
//            if result != nil {
//                self?.httpMyInformationHttpGetResultResponse(result: result)
//            }else{
//                print("空的")
//            }
//        }
//        let dic:NSMutableDictionary = NSMutableDictionary()
//        dic[kHttpMyInformationHttpGetCmd_userid] = AccountInfo.sharedInstance().UserId
//        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
//        cmd.requestInfo = (dic as! [AnyHashable : Any])
//        cmd.completeDelegate=completeDelegate
//        print("url==%@",cmd.getUrl())
//        cmd.execute()
        let cmd:HttpCommand = UserInfoHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpMyInformationHttpGetResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        let arrtDic:NSMutableDictionary = NSMutableDictionary()
        arrtDic[kHttpUserInfoHttpPostCmd_name] = AccountInfo.sharedInstance().UserId
        dic[kHttpUserInfoHttpPostCmd_attr] = arrtDic
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = (dic as! [AnyHashable : Any])
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
    }
    func httpMyInformationHttpGetResultResponse(result:RequestResult){
//        let r:MyInformationHttpGetResult = result as! MyInformationHttpGetResult
//        if r.isOk() {
//            let array:NSMutableArray = r.getMyInformationAllData()
//            var inforHttpModel = MyInformationHttpModel()
//            inforHttpModel = array[0] as! MyInformationHttpModel
//            self.addHeadImageModel(httpInfoModel: inforHttpModel)
//        }else{
//            SMToastView.showMessage("请查看当前网络状态！")
//        }
        let r:UserInfoHttpPostResult = result as! UserInfoHttpPostResult
        if r.isOk() {
            let array:NSMutableArray = r.getUserInfoHttpPostResult()
            var inforHttpModel = MyInformationHttpModel()
            inforHttpModel = array[0] as! MyInformationHttpModel
            self.addHeadImageModel(httpInfoModel: inforHttpModel)
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
        }
        self.hidenHintView()
        if self.loginInitType == .LoginWeiChatType {
            self.getWeChatBindingHttpPostCmd()
        }
        NotificationCenter.default.post(name: Notification.Name(rawValue: "addTabBarWindow"), object: "0")
        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)
        SinglePointWeChatHttp.sharedInstance().juphRegistrationIDActionHttp { [weak self] (value:Any) in
        } errorBlock: { (value:Any) in
        }
        //        group.leave()
    }
    
    func addHeadImageModel(httpInfoModel:MyInformationHttpModel) {
        AccountInfo.sharedInstance().userName = judgmentStrNil(str: httpInfoModel.cnname)
        AccountInfo.sharedInstance().infoCompanyName = judgmentStrNil(str: httpInfoModel.companyname)
        AccountInfo.sharedInstance().infoDeptName = judgmentStrNil(str: httpInfoModel.deptnames)
        AccountInfo.sharedInstance().externalUser = judgmentStrNil(str: httpInfoModel.type)
        if judgmentStrNil(str: httpInfoModel.password) == md5(strs: "123456") && self.loginType == .OldLoginType {
            showOneAlert(title: "温馨提示", message: "您当前密码为初始密码，需要修改密码", titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
                self?.gotoChangePassWordViewController(changePassWordType: .OrdinaryChangePassWordType)
            })
            return
        }
        if judgmentStrNil(str: httpInfoModel.status) == "0" {
            self.logoutUserInfo(str: "您的账户已被禁用，请联系管理员！")
            return
        }
        if judgmentStrNil(str: httpInfoModel.is_deleted) == "Y" {
            self.logoutUserInfo(str: "您的账户已被删除，请联系管理员！")
            return
        }
    }
    /// 跳转修改密码
    func logingotoChangePassWordViewController(changePassWordType:ChangePassWordType){
        let vc:ChangePassWordViewController=ChangePassWordViewController()
        vc.changePassWordType = changePassWordType
        //        vc.signOutBlock = signOutBlock
        vc.hidesBottomBarWhenPushed = true
        self.pushViewController(viewController: vc, animated: true)
    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        print("1234")
    }
    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()
    }
}
