//
//  LoginViewController.swift
//  SocketChat
//
//  Created by Justine on 16/5/20.
//  Copyright © 2016年 AppCoda. All rights reserved.
//

import UIKit
import Alamofire
import MBProgressHUD
import SocketIOClientSwift
class LoginViewController: UIViewController{
    @IBOutlet weak var userName: UITextField!
    @IBOutlet weak var passWord: UITextField!
    var hud:MBProgressHUD = MBProgressHUD()
    var Response:ServerModel = ServerModel.init()
    @IBAction func LoginBtn(sender: UIButton) {
        //使用全局方法 去除空格
        var username = (userName.text!)
        var password = (passWord.text!)
        username = trimstring(username, trimchar: " ")
        password = trimstring(password, trimchar: " ")
        //将用户转换为登陆对象传递
        hud.labelText = "连接中..."
        hud.show(true)
        self.checkUser(username,password: password)
    }
    
    
    func checkUser(username:String,password:String)->Void{
        defer{
            //该方法执行完成后 自动隐藏
            hud.hide(true, afterDelay: 1.0)
        }
        //网络请求用户名
        let url = CENTER_SERVER+username
        //validate默认statecode 200~299 为正常
        Alamofire.Manager.sharedInstance.request(.GET, url).responseJSON{ R in
            switch R.result {
            case .Failure(let error):
                print("---------error start----------")
                print(error)
                print("---------error end------------")
                return
            case .Success:
                
                guard let bigDic:NSMutableDictionary = R.result.value as? NSMutableDictionary else{
                    print("//转字典后再取值给servermodel")
                    return}
                let ret = bigDic["ret"] as! Int
                let msg = bigDic["msg"] as! String
                let dataDic:NSDictionary = bigDic["data"] as! NSDictionary
                //强转为ServerModel
                self.Response.ret = ret
                self.Response.msg = msg
                self.Response.data = ServerData.init(fromDictionary: dataDic)
                //self.Response = (R.result.value! as? ServerModel)
                print(self.Response)
                guard (self.Response.ret! == 1) else{
                    //弹窗口显示 msg
                    print("###############################")
                    print(self.Response.msg)
                    return
                }
                //返回各服务 字典对象data{appserver chatserver fileserver downserver等}
                let data = self.Response.data.toDictionary()
                //清空老数据
                ManagerUserDefault().DelServers()
                //储存各项服务器
                ManagerUserDefault().SetServers(data)
                
                let serverID = ManagerUserDefault().SelectUserDefault(SERVER_ID) as! String
                let tmpmsg:[String] = [username,password,serverID]
                let LoginMSG:LoginMsg = LoginMsg(fromStringarr: tmpmsg)
                //sendArr[1] = LoginMSG.toDictionary()
                let parm = LoginMSG.toDictionary()as! [String : AnyObject!]
                let url = (USER_SOCKET_SERVER as! String) + "/v1/user/login"
                print("################ parm ###############")
                
                
                let head = ["Content-Type":"application/json",
                            "accept":"application/json",
                            "accept-ecoding":"gzip, deflate",
                            "accpet-language":"en-US,en;q=0.8"
                            ]
                Alamofire.Manager.sharedInstance.request(Method.POST, url, parameters: parm , encoding: ParameterEncoding.JSON, headers: head).responseJSON(completionHandler: { (R) in
                    guard R.result.error == nil else {
                        print("###############  error #############")
                        print("operation: %@" ,R.response.debugDescription)
                        print(R.result.error)
                        return
                    }
                    print(R.result.value!)
                    //结果转模型储存
                    guard let bigDic1:NSMutableDictionary = R.result.value as? NSMutableDictionary else{
                        print("Failed return //转字典后再取值给model")
                        print("### My Define alamofire httprequest error ######")
                        return
                    }
                    let issuccess = (bigDic1["success"] as! Int)
                    if (issuccess != 1){
                    //hud Alert
                        print("登陆失败，服务端返回错误为\(bigDic1["message"])")
                    }
                    else{
                    //根据返回值大字典bigDic1里的小字典data["isLocked"]判断是否登陆
                        guard let dataDic1:NSDictionary = bigDic1["data"] as? NSDictionary else{
                            print("大字典bigDic1转字典dataDic1转换失败")
                            return
                        }
                        //未锁定
                        guard (dataDic1["isLocked"]as! Bool) == false else{
                            print("账号已锁定请联系管理员")
                            self.hud.labelText = "账号已锁定请联系管理员"
                            return
                        }
                        //未验证
                        if (dataDic1["needSMS"]as! Bool) {
                            //showBindbySMScontroller
                            print("设备需要绑定,即将进入短信绑定界面")
                            self.showSMSVC()
                        }
                        //进入主界面 更新设备token
                        else{
                            //showRootViewController
                            print("即将进入主界面")
                            
                        }
                    }
                    
                    
                    
                    
                    
                    //let r:LoginRet = R.result.value! as! NSDictionary
                    
                    //TCPClient.shareInstance.connect(USER_APP_SERVER! as! String )
                    
                })
                
                
                
                
                
                
                
                
            }
            
        }
        
    }
    func showSMSVC(){
        let story = UIStoryboard(name: "Main", bundle: nil)
        let SMSVC = story.instantiateViewControllerWithIdentifier("SMSVC")
        self.presentViewController(SMSVC, animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(hud)
        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
    
}
