//
//  SinglePointWeChatVC+Http.swift
//  MobilePortal
//
//  Created by caiyang on 2020/8/24.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit

extension SinglePointWeChatVC {
    // MARK: 判断APP是否被停用
    func judgmentDeactivateEnable(){
        SinglePointWeChatHttp.sharedInstance().judgmentDeactivateEnable(userid: judgmentStrNil(str: self.loginView.userTextView.text!), resultBlock: { [weak self] (value:Any) in
            self?.juDeactivateEnableSinglePointData(array: value as! NSMutableArray)
        }) { (value:Any) in
        }
    }
    func juDeactivateEnableSinglePointData(array:NSMutableArray) {
        if (array.count == 0) {
            self.getLoginTypeHttpAction()
        } else {
            showOneAlert(title: "提示", message: array.firstObject as! String, titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
                self?.dropOutAPP()
            })
//            deAllSelecCompanyDepartment()
//            AccountInfo.sharedInstance().clearAccount()
        }
    }
    // MARK:根据公司获取登录方式
    func getLoginTypeHttpAction(){
        SinglePointWeChatHttp.sharedInstance().getLoginTypeHttpGetCmd(userid: self.loginView.userTextView.text!, resultBlock: {[weak self] (value:Any) in
            self?.loginTypeHttpGetCmdTypeAction(array: value as! NSMutableArray)
        }) { (value:Any) in
            
        }
    }
    func loginTypeHttpGetCmdTypeAction(array:NSMutableArray) {
        if array.count != 0 {
            let item:String = array.firstObject as! String
            if (item == "3") {
                ///集团单点
                self.loginType = .SinglePointLoginType
//                loginView.weixinQQView.isHidden = true
                if self.loginInitType == .LoginActionType {
                    self.getVerifyTokenHttpPostCmdAction()
//                    self.loginGetAccess_token()
                }
            } else {
                /// 自带登录
                if self.loginInitType == .LoginActionType {
                    self.getLoginHttpPostCmdCmd()
//                    self.getVerifyTokenHttpPostCmdAction()
//                        self.getVerifyTokenHttpPostCmdAction()
                }
                self.loginType = .OldLoginType
//                loginView.weixinQQView.isHidden = false
            }
            AccountInfo.sharedInstance().loginType = self.loginType.rawValue
        }
    }
    // MARK:获取登录方式
    func getScopeListHttpCmd(){
        SinglePointWeChatHttp.sharedInstance().getScopeListHttpCmd(resultBlock: {[weak self] (value:Any) in
            self?.selectSinglePointTypeAction(array: value as! NSMutableArray)
        }) { (value:Any) in
        }
    }
    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") {
                    ///集团单点
                    self.loginType = .SinglePointLoginType
                    loginView.weixinQQView.isHidden = true
                } else {
                    /// 自带登录
                    if self.loginInitType == .LoginActionType {
                        self.getLoginHttpPostCmdCmd()
                    }
                    self.loginType = .OldLoginType
                    loginView.weixinQQView.isHidden = false
                }
                AccountInfo.sharedInstance().loginType = self.loginType.rawValue
            }
        }
    }
    
    // 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_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()
                    AccountInfo.sharedInstance().UserId = ""
                    SMToastView.showMessage("您当前的密码为初始密码，请修改密码！")
                    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()
        }
    }
    
    // MARK:设备是否可用绑定
    func getDeviceDisabledHttpPostCmd(){
        SinglePointWeChatHttp.sharedInstance().getDeviceDisabledHttpPostCmd(resultBlock: {[weak self] (value:Any) in
            self!.getLoginDeviceInformationHttpCmd()
        }) { [weak self](value:Any) in
            self?.hidenHintView()
        }
    }
    
    //版本更新
    func getNewVersionUpdateHttpCmd(){
        showHintView()
        SinglePointWeChatHttp.sharedInstance().getNewVersionUpdateHttpCmd(resultBlock: { (value:Any) in
            self.httpNewVersionUpdateHttpResultResponse(result: value as! RequestResult)
        }) { (value:Any) in
        }
    }
    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!)
                })
                hidenHintView()
            } else {
                getUntuedCellPhoneHttpPostCmd()
            }
        }else{
            hidenHintView()
            getUntuedCellPhoneHttpPostCmd()
            SMToastView.showMessage("请查看当前网络状态！")
        }
    }
    
    // MARK:手机是否禁用
    func getUntuedCellPhoneHttpPostCmd(){
        SinglePointWeChatHttp.sharedInstance().getUntuedCellPhoneHttpPostCmd(resultBlock: {[weak self] (value:Any) in
            self?.judgmentPhone(httpArray: value as! NSMutableArray)
            self?.hidenHintView()
        }) {[weak self] (value:Any) in
            self?.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
            }
        }
    }
    
    /// 上传手机信息
    func getLoginDeviceInformationHttpCmd(){
        self.showHintView()
        SinglePointWeChatHttp.sharedInstance().getLoginDeviceInformationHttpCmd(resultBlock: {[weak self] (value:Any) in
            /// 获取个人信息
            self?.getMyInformationHttpGetCmd()
        }) {[weak self] (value:Any) in
            self?.hidenHintView()
        }
    }
    // MARK:获取个人信息接口
    func getMyInformationHttpGetCmd(){
        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: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()
        }
    }
    
    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
        }
        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
        }
    }
    /// 跳转修改密码
    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()
    }
}
