Newer
Older
Meterage_iOS / Meterage / ViewControllers / Login / LoginViewController.swift
//
//  LoginViewController.swift
//  Meterage
//
//  Created by 203 on 2023/2/1.
//

import Alamofire
import DefaultsKit
import SwiftyJSON
import UIKit
import IQKeyboardManagerSwift

class LoginViewController: UIViewController, UITextFieldDelegate {

    private let keyboardManager = IQKeyboardManager.shared
    private let defaults = Defaults.shared
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var userNameView: UITextField!
    @IBOutlet weak var passwordView: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        keyboardManager.enable = true
        keyboardManager.keyboardDistanceFromTextField = 30
        keyboardManager.shouldResignOnTouchOutside = true
        keyboardManager.toolbarDoneBarButtonItemText = "完成"

        textLabel.textColor = .mainThemeColor

        loginButton.backgroundColor = .mainThemeColor
        loginButton.layer.cornerRadius = 5 // 设置圆角

        // 实现UITextField代理
        passwordView.delegate = self

        // 设置默认账号密码
        userNameView.text = defaults.get(for: userNameKey) ?? ""
        passwordView.text = defaults.get(for: passwordKey) ?? ""
    }

    @IBAction func loginAction(_ sender: UIButton) {
        let userName = userNameView.text
        if userName == "" {
            AlertHub.shared.showWaringAlert(controller: self, message: "登录用户名不能为空")
            return
        }
        let password = passwordView.text
        if password == "" {
            AlertHub.shared.showWaringAlert(controller: self, message: "密码不能为空")
            return
        }
        // 记录账号密码
        defaults.set(userName!, for: userNameKey)
        defaults.set(password!, for: passwordKey)

        // 访问后台,开始登录
        let baseURL = defaults.get(for: serverConfigKey)!
        let configURL = baseURL + Constant.baseConfig.rawValue
        LoadingHub.shared.showLoading(text: "登录中,请稍后")
        Alamofire.request(configURL, method: .get).responseJSON { [self] 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
                let paramDic = ["sid": configModel.data.sid, "username": userName!, "password": pwdWithKey]

                Alamofire.request(HttpRequestCreator.shared.createPostRequest(url: loginURL, dic: paramDic)).responseJSON { [self] response in
                    switch response.result {
                    case let .success(value):
                        let loginModel = LoginResultModel(respJson: JSON(value))
                        if loginModel.code == 200 {
                            // 将token存起来
                            defaults.set(loginModel.data!.token, for: tokenKey)

                            // 进入主页
                            AppCoordinator.shared.setTabBarViewController()
                        } else {
                            AlertHub.shared.showWaringAlert(controller: self, message: "密码错误,无法登陆")
                        }
                    case .failure:
                        AlertHub.shared.showWaringAlert(controller: self, message: "未知异常,无法登陆")
                    }
                    LoadingHub.shared.hideLoading()
                }
            case .failure:
                AlertHub.shared.showWaringAlert(controller: self, message: "检验失败,无法登陆")
                LoadingHub.shared.hideLoading()
            }
        }
    }

    // 输入框委托方法具体实现
    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, message: "密码最长只能输入12位")
            return false
        }
        return true
    }
}