//
//  WeChatBindingViewController+http.swift
//  MobilePortal
//
//  Created by caiyang on 2020/8/10.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit

extension WeChatBindingViewController {
    /// 微信绑定
    func getWeChatBindingHttpPostCmd(){
//        showHintView()
        let cmd:HttpCommand = WeChatBindingHttpPostCmd.init(version: PHttpVersion_v1)
        let block:httpBlock = {[weak self] (result:RequestResult!,useInfo:Any!)->() in
            if result != nil {
                self?.httpWeChatBindingHttpResultResponse(result: result)
            }else{
                print("空的")
            }
        }
        let dic:NSMutableDictionary = NSMutableDictionary()
        dic[kHttpWeChatBindingHttpPostCmd_userid] = AccountInfo.sharedInstance().UserId
        dic[kHttpWeChatBindingHttpPostCmd_wechatid] = AccountInfo.sharedInstance().weChat_unionid
        dic[kHttpWeChatBindingHttpPostCmd_state] = "1"
        dic[kHttpWeChatBindingHttpPostCmd_wechatname] = AccountInfo.sharedInstance().weChatInfo_nickname
        let completeDelegate = SMBaseHttpComplete.init(block: block , withUserInfo: nil)
        cmd.requestInfo = dic as? [AnyHashable : Any]
        cmd.completeDelegate=completeDelegate
        print("url==%@",cmd.getUrl())
        cmd.execute()
        
    }
    func httpWeChatBindingHttpResultResponse(result:RequestResult){
        let r:WeChatBindingHttpResult = result as! WeChatBindingHttpResult
        if r.isOk() {
            let array:NSMutableArray = r.getWeChatBindingHttpResult()
//            actionHttpGCD()
            if (array.count == 0) {
                SMToastView.showMessage("绑定成功！")
                getLoginDeviceInformationHttpCmd()
            } else {
                SMToastView.showMessage((array[0] as! String))
                self.hidenHintView()
                AccountInfo.sharedInstance().clearAccount()
                self.arrowResponse()
            }
        }else{
            SMToastView.showMessage("请查看当前网络状态！")
            AccountInfo.sharedInstance().clearAccount()
            self.arrowResponse()
            self.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 {
                    /// 自带登录
                    self.loginType = .OldLoginType
                    getLoginHttpPostCmdCmd()
                }
                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_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("您当前的密码为初始密码，请修改密码！")
                    self.loginView.passTextView.text = ""
                    self.hidenHintView()
                    self.logingotoChangePassWordViewController(changePassWordType: .LoginChangePassWordType)
                }else{
//                    AccountInfo.sharedInstance().passWord = self.loginView.passTextView.text
//                    getLoginDeviceInformationHttpCmd()
                    getWeChatBindingHttpPostCmd()
                }
            }
        }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()
        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 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: .LoginChangePassWordType)
            })
            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()
    }
}
