Newer
Older
LaserMethane / LaserMethane / ViewController / Login / LoginViewController.swift
Pengxh on 28 Jul 2021 5 KB first commit
//
//  LoginViewController.swift
//  LaserMethane
//
//  Created by 203 on 2021/7/27.
//

import Alamofire
import KeychainAccess
import SwiftyJSON
import UIKit

class LoginViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var userNameView: UITextField!
    @IBOutlet var passwordView: UITextField!
    @IBOutlet var loginButton: UIButton!
    var keychain: Keychain!

    override func viewDidLoad() {
        super.viewDidLoad()
        keychain = Keychain()
        // 实现UITextField代理
        passwordView.delegate = self

        // rgb 色值为(21,101,227)那么给UIColor设置里面要除以255,设置16进制颜色也同理
        loginButton.backgroundColor = UIColor(red: 21 / 255, green: 101 / 255, blue: 227 / 255, alpha: 1.0)
        loginButton.layer.cornerRadius = 18 // 设置圆角
    }

    @IBAction func loginAction(_ sender: UIButton) {
        let userName = userNameView.text
        if userName == "" {
            AlertHub.shared.showWaringAlert(controller: self, messge: "登录用户名不能为空")
            return
        }
        let password = passwordView.text
        if password == "" {
            AlertHub.shared.showWaringAlert(controller: self, messge: "密码不能为空")
            return
        }
        // 访问后台,开始登录
        let baseURL = keychain[Constant.ServerConfig.rawValue]
        let configURL = baseURL! + Constant.baseConfig.rawValue
        Alamofire.request(configURL, method: .get).responseJSON { response in
            switch response.result {
            case let .success(value):
                let configModel = BaseConfigModel(respJson: JSON(value))
                // 将密码经由RSA和publicKey加密
                guard let pwdWithKey = try? password?.encryptByRSA(publicKey: (configModel.data?.publicKey)!)
                else { return }

                // 登录
                let loginURL = baseURL! + Constant.login.rawValue
                Alamofire.request(loginURL, method: .post,
                                  parameters: ["username": userName!, "password": pwdWithKey]).responseJSON { response in
                    switch response.result {
                    case let .success(value):
                        let loginModel = LoginResultModel(respJson: JSON(value))
                        if loginModel.code == 200 {
                            // 将token存起来
                            self.keychain[Constant.Token.rawValue] = loginModel.data!.token
                            // 跳转主页
                            self.startMainMenuView()
                        } else {
                            AlertHub.shared.showWaringAlert(controller: self, messge: "密码错误,无法登陆")
                        }
                    case .failure:
                        AlertHub.shared.showWaringAlert(controller: self, messge: "未知异常,无法登陆")
                    }
                }
            case .failure:
                AlertHub.shared.showWaringAlert(controller: self, messge: "检验失败,无法登陆")
            }
        }
    }

    // 跳转到主页
    @objc func startMainMenuView() {
        let homePage = MainMenuViewController(nibName: "MainMenuViewController", bundle: nil)
        let destinationController = UINavigationController(rootViewController: homePage)
        destinationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        destinationController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
        present(destinationController, animated: true, completion: nil)
    }

    // 输入框委托方法具体实现
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentLength = (textField.text?.lengthOfBytes(using: .utf8))! - range.length + string.lengthOfBytes(using: .utf8)
        if currentLength > 12 {
            AlertHub.shared.showWaringAlert(controller: self, messge: "密码最长只能输入12位")
            return false
        }
        return true
    }

    // 修改服务器IP
    @IBAction func changeServerConfig(_ sender: UIButton) {
        var inputText: UITextField!
        // 读取本地数据,输入框显示默认IP
        let ip = keychain[Constant.ServerConfig.rawValue]
        let msgAlertCtr = UIAlertController(title: nil, message: "请输入后台服务器地址", preferredStyle: .alert)
        msgAlertCtr.addTextField { textField in
            textField.text = ip
            inputText = textField
        }
        let actionOK = UIAlertAction(title: "保存", style: .default) { (_: UIAlertAction) -> Void in
            let configData = inputText.text
            if configData == "" {
                return
            }
            // 存本地
            self.keychain[Constant.ServerConfig.rawValue] = configData!
        }
        let actionCancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        // 设置取消按钮颜色为红色
        actionCancel.setValue(UIColor(red: 255 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1), forKey: "titleTextColor")
        msgAlertCtr.addAction(actionOK)
        msgAlertCtr.addAction(actionCancel)
        present(msgAlertCtr, animated: true, completion: nil)
    }
}