NewLoginViewController.swift 6.67 KB
//
//  NewLoginViewController.swift
//  youer
//
//  Created by sinceredeveloper on 15/11/9.
//  Copyright (c) 2015年 kagami. All rights reserved.
//

import UIKit

class NewLoginViewController: UIViewController,UITextFieldDelegate {
    @IBOutlet weak var viewContent: UIView!
    @IBOutlet weak var constraintContentOffset: NSLayoutConstraint!
    @IBOutlet weak var fieldAccount: UITextField!
    @IBOutlet weak var fieldPassword: UITextField!
    @IBOutlet weak var buttonLogin: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        constraintContentOffset.constant=20
        view.backgroundColor=UIColorFromRGB(0xf7f7f7)
        Theme.configButton(buttonLogin)
        NotificationCenter.default.addObserver(self, selector: #selector(NewLoginViewController.refreshUser), name: NSNotification.Name(rawValue: "refreshLoginUser"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(NewLoginViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(NewLoginViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        fieldAccount.tintColor=Theme.topBarColor()
        fieldPassword.tintColor=Theme.topBarColor()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //注册完了后自动填充账号
    func refreshUser(noti:Notification){
        fieldAccount.text = "\(noti.object!)"
    }
    @IBAction func onLoginClicked(_ sender: UIButton) {
        self.view.endEditing(true)
        let account=fieldAccount.text
        let pw=fieldPassword.text
        
        if (account?.characters.count)!<1 || pw!.characters.count<1 {
            self.view.makeToast("账号或密码不能为空")
            return
        }
        login(phone: account!, pw:pw!)

    }
    func login(phone:String, pw:String){
        if phone.isMobilePhoneNumber() {
            SVProgressHUD.show(withStatus: "登录...")
            SVProgressHUD.setDefaultMaskType(.black)
            let parameters:Dictionary<String,AnyObject>=["grant_type":"password" as AnyObject,"username":phone as AnyObject,"password":pw as AnyObject]
            AppDelegate.instance().httpServer.login(parameters: parameters) { (str, error) in
                let json=JSON.fromString(jsonString: str)
                if let ret=json{
                    let er=ret["error"].string
                    if let errorStr=er{
                        SVProgressHUD.dismiss()
                        let Strings=errorStr.components(separatedBy:":")
                        if Strings.count >= 2 {
                            switch Strings[1] {
                            //用户关联多个身份,请使用学事号登录:100
                            case "101"://用户认证身份不存在:101
                                AppDelegate.instance().window?.makeToast("用户认证身份不存在,请进行账号激活。")
                                break
                            //用户帐号或密码错误:102
                            case "103":// 用户不存在:103
                                AppDelegate.instance().window?.makeToast("该号码不存在,请联系客服400-826-2468")
                                break
                            default:
                                AppDelegate.instance().window?.makeToast("\(errorStr)")
                                break
                            }
                        }else{
                            AppDelegate.instance().window?.makeToast("\(errorStr)")
                        }
                    }else if ret["access_token"].stringValue != ""{
                        AppDelegate.instance().accountManager.setTokenInfo(tokenInfo: ret)
                        AppDelegate.instance().accountManager.saveToken(tokenInfo: ret)
                        AppDelegate.instance().accountManager.refreshUserInfo(completionHandler: { (finish) in
                            if finish{
                                //                                self.loadUserInfo()
                                SVProgressHUD.dismiss()
                                //发出刷新首页通知
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshFirstVC"), object: nil)
                                self.back()
                            }else{
                                AppDelegate.instance().window?.makeToast("身份获取失败")
                                SVProgressHUD.dismiss()
                            }
                        })
                    }else{
                        SVProgressHUD.dismiss()
                        AppDelegate.instance().window?.makeToast("登录失败,请稍后重试")
                    }
                }else{
                    SVProgressHUD.dismiss()
                    AppDelegate.instance().window?.makeToast("登录失败")
                }
            }
        }else{
            self.view.makeToast("请输入正确手机号")
        }
    }
    func back(){
        self.navigationController!.popViewController(animated: true)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    @IBAction func forgetPassword(_ sender: UIButton) {
         let vc = Story.instantiateViewControllerWithIdentifier("ChangePassWordViewControllerVC", storyName: "User") as! ChangePassWordViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func registerAccount(_ sender: UIButton) {
        let vc = UIStoryboard(name: "Login", bundle: nil).instantiateViewController(withIdentifier: "RegisterViewControllerVC") as! RegisterViewController
        vc.title="注册"
        self.navigationController!.pushViewController(vc, animated: true)
    }

    func keyboardWillShow(){
        constraintContentOffset.constant=144
        UIView.animate(withDuration: 2, animations: { () -> Void in
            self.viewContent.layoutIfNeeded()
        })
        
    }
    func keyboardWillHide(){
        constraintContentOffset.constant=20
        UIView.animate(withDuration: 2, animations: { () -> Void in
            self.viewContent.layoutIfNeeded()
        })
    }
    // MARK: - 销毁通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}