| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- //
- // LoginViewController.swift
- // MTP2_iOS
- //
- // Created by zhongyuan on 2018/5/10.
- // Copyright © 2018年 zhongyuan.All rights reserved.
- //
- import UIKit
- import NVActivityIndicatorView
- import WHToast
- import SwiftyAttributes
- import SafariServices
- /// 登录视图容器管理类
- class LoginViewController: BaseTableViewController<LsLoginUserModel>, UITextFieldDelegate {
-
- // MARK: - 生命周期
- private static let TAG_LOGIN = 100
- private static let TAG_REGIEST = 101
- private static let TAG_PULL = 102
- private static let TAG_WACHAT = 103
- private static let TAG_ALIPAY = 104
- private static let TAG_PHONE_LOGIN = 105
- private static let TAG_FORGETPWD = 106
-
- /// 账户名称
- @IBOutlet weak var usernameTextField: UITextField!
- /// 账户密码
- @IBOutlet weak var passwordTextField: UITextField!
- /// 登录按钮
- @IBOutlet weak var loginButton: UIButton!
- /// 手机号码登录
- @IBOutlet weak var phoneLoginButton: UIButton! {
- didSet {
- phoneLoginButton.isHidden = !((ConfigUtils.getValue(key: .SupportMobileLogin) as? Bool) ?? true)
- }
- }
- /// 账户信息下拉按钮
- @IBOutlet weak var userPull: UIButton!
- /// 用户信息
- @IBOutlet weak var userTableView: UITableView! {
- didSet {
- userTableView.layer.cornerRadius = 5.0
- userTableView.layer.borderWidth = 0.5
- userTableView.layer.borderColor = UIColorFromHex(rgbValue: 0xe0e0e0).cgColor
- userTableView.layer.masksToBounds = true
- }
- }
- /// cell的高度约束
- @IBOutlet weak var cellConstraints: NSLayoutConstraint!
- /// 微信
- @IBOutlet weak var weixinButton: UIButton!
- /// 支付宝
- @IBOutlet weak var alipayButton: UIButton!
- /// 忘记密码
- @IBOutlet weak var forgetPwdButton: UIButton! {
- didSet {
- forgetPwdButton.isHidden = !((ConfigUtils.getValue(key: .SupportResetPwd) as? Bool) ?? true)
- }
- }
- /// 版本号
- @IBOutlet weak var versionLabel: UILabel! {
- didSet {
- versionLabel.text = "版本号:V" + app_Version
- }
- }
- /// 是否张开状态
- private var isExpand = false
-
- // MARK: - 生命周期相关
- override func viewDidLoad() {
- super.viewDidLoad()
-
- /// 隐藏导航栏
- self.navigationController?.setNavigationBarHidden(true, animated: true)
- /// Loading
- addLoadingView()
- /// 界面内容初始化
- buildView()
- /// 数据初始化
- initData()
- /// 初始化用户信息
- initUser()
- }
-
- override func viewDidAppear(_ animated: Bool) {
- super.viewDidAppear(animated)
-
- /// stopAnimating
- if let isAnimating = self._anim?.isAnimating,
- isAnimating { self._anim?.stopAnimating() }
- }
-
- // MARK: - 初始化相关
- /// 数据初始化
- func initData() {
- /// 请求app版本更新
- self.requestAppVersionUpdate()
- }
-
- /// 界面内容初始化
- func buildView() {
- /// 设置attributedPlaceholder
- usernameTextField.attributedPlaceholder = "用户名/账号/手机号".withTextColor(Color_placeholder_text)
- passwordTextField.attributedPlaceholder = "请输入您的密码".withTextColor(Color_placeholder_text)
-
- /// 设置cell标识
- cellReuseIdentifier = "LoginUserCellID"
- /// tableView 设置
- userTableView.rowHeight = 44.0
- }
-
- // MARK: - 用户交互相关
- @IBAction func viewPassed(_ sender: UIButton) {
- if self.usernameTextField.isFirstResponder {
- self.usernameTextField.resignFirstResponder()
- }
- if self.passwordTextField.isFirstResponder {
- self.passwordTextField.resignFirstResponder()
- }
- switch sender.tag {
- case LoginViewController.TAG_LOGIN:
- if let _ = MTP2BusinessCore.shared.address {
- startLogin()
- } else {
- /// startAnimating
- self._anim?.startAnimating()
- /// requestAppAdress
- MTP2BusinessCore.shared.requestAppAdress { (isComplete, error) in
- DispatchQueue.main.async {
- /// stopAnimating
- self._anim?.stopAnimating()
-
- if !isComplete {
- WHToast.showError(withMessage: "登录失败,获取链路失败!", duration: 2.0, finishHandler: {})
- return
- }
- /// 开始登录
- self.startLogin()
- }
- }
- }
- case LoginViewController.TAG_PULL: /// 帐户列表
- getAllUser()
- case LoginViewController.TAG_FORGETPWD: /// 忘记密码
- /// 进入到重置密码
- self.present(storyboardName: "ResetPwd", storyboardId: "ResetPwdFirstStepID")
- case LoginViewController.TAG_PHONE_LOGIN: /// 帐户注册
- guard let url = URL(string: MTP2BusinessCore.shared.address?.mobileOpenUrl ?? "") else { return }
- let safriViewController = SFSafariViewController(url: url)
- safriViewController.delegate = self
- self.present(safriViewController, animated: true, completion: {})
- default:
- if (self.navigationController?.viewControllers.count ?? 0) > 1 {
- self.navigationController?.popViewController(animated: true)
- } else {
- self.dismiss(animated: true, completion: {})
- }
- }
- }
-
- /// 获取保存的用户账号
- func initUser() {
- if let userInfo = try? DatabaseHelper.getUsers(type: Int16(0)) {
- tableCellModels = userInfo.compactMap({ LsLoginUserModel(source: $0) }).sorted(by: { (obj1, obj2) -> Bool in
- return obj1.loginDate>obj2.loginDate
- })
- usernameTextField.text = tableCellModels[0].loginID
- userPull.isHidden = userInfo.count > 0 ? false : true
- } else {
- usernameTextField.text = ""
- tableCellModels.removeAll()
- userPull.isHidden = true
- }
- passwordTextField.text = ""
- }
-
- /// 显示所有的账户信息
- func getAllUser() {
- /// 是否展开
- isExpand = !isExpand
- /// 是否隐藏
- self.userTableView.isHidden = !self.isExpand
- /// 约束
- self.cellConstraints.constant = 0.0
- /// 动画
- UIView.animate(withDuration: 0.3) {
- self.cellConstraints.constant = self.isExpand ? CGFloat(self.tableCellModels.count > 5 ? 5 : self.tableCellModels.count) * 44 : 0
- self.view.layoutIfNeeded()
- }
- userTableView.reloadData()
- }
-
- // MARK: - 登录相关
- /// 用户登录校验
- ///
- /// - Returns: 是否成功
- private func checkValue() -> Bool {
- if let account = self.usernameTextField.text {
- if account.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty {
- WHToast.showError(withMessage: "请输入登录账户", duration: 1.0) {
- self.usernameTextField.becomeFirstResponder()
- }
- return false
- }
- }
- if let password = self.passwordTextField.text {
- if password.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty {
- WHToast.showError(withMessage: "请输入账户密码", duration: 1.0) {
- self.passwordTextField.becomeFirstResponder()
- }
- return false
- }
- }
- return true
- }
-
- /// 登录方法
- func startLogin() {
-
- /// 异常
- guard checkValue(),
- let accountManager = MTP2BusinessCore.shared.accountManager else { return }
- /// account
- let account = self.usernameTextField.text
- /// password
- let password = self.passwordTextField.text
-
- self._anim?.startAnimating()
- self.view.isUserInteractionEnabled = false
- self.loginButton.isEnabled = false
-
- let faidBlock = { (error: ErrorInfo?) in
- DispatchQueue.main.async {
- self._anim?.stopAnimating()
- self.view.isUserInteractionEnabled = true
- self.loginButton.isEnabled = true
-
- if let error = error,
- error.retCode == 1003,
- let loginrsp = accountManager.loginRsp {
- let message = "还剩\(loginrsp.pwdWrongLockCnt - loginrsp.pwdWrongCnt)次错误机会,账号或密码不匹配达到\(loginrsp.pwdWrongLockCnt)次,登录账号将锁定\(loginrsp.loginLockHourNum)小时。请联系管理员966000处理。" + "您也可通过手机验证码登录!"
- self.showHintController(title: "提示", message: message)
- } else {
- self.showErrorMessgae(error: error)
- }
- }
- }
-
- guard let trade_address = MTP2BusinessCore.shared.address?.tradeHost,
- let trade_port = MTP2BusinessCore.shared.address?.tradePort,
- let intPort = UInt16(trade_port) else { return }
-
- /// 获取登录ID
- accountManager.getUserLoginID(account ?? "") { (isSuccess, err, loginId) in
- if !isSuccess {
- faidBlock(err)
- return
- }
- DispatchQueue.main.async {
- accountManager.login(address: trade_address, port: intPort, userName: loginId!, password: password!, deviceID: NSUUID().uuidString, version: app_Version) { isCompleted, error in
- if isCompleted {
- /// 用户与商品信息统一查询
- accountManager.queryAccountAndGoods(callback: { (isCompleted, error) in
- if isCompleted {
- DispatchQueue.main.async {
- /// 如果有 先删除
- if let _ = try? DatabaseHelper.getUser(userID: MTP2BusinessCore.shared.getUserID(), type: Int16(0)) {
- try? DatabaseHelper.deleteUser(userID: MTP2BusinessCore.shared.getUserID())
- }
- DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+0.5, execute: {
- /// 记录本地用户信息
- try? DatabaseHelper.addUser(userID: MTP2BusinessCore.shared.getUserID(), loginID: account ?? "", loginDate: Date(), type: Int16(0))
- })
- self._anim?.stopAnimating()
- self.view.isUserInteractionEnabled = true
- self.loginButton.isEnabled = true
- /// 进入主界面
- if let mainTabBarController: UITabBarController = self.storyboard?.instantiateViewController(withIdentifier: "MainTabBarController") as? UITabBarController {
- /// 设置根视图
- (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController = mainTabBarController
- }
- }
- } else {
- faidBlock(error)
- }
- })
- } else {
- faidBlock(error)
- }
- }
- }
- }
- }
-
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- super.touchesBegan(touches, with: event)
-
- /// 关闭
- if !userTableView.isHidden {
- isExpand = false
- userTableView.isHidden = true
- }
- }
-
- // MARK: - 版本更新相关
- /// app检测版本更新
- fileprivate func requestAppVersionUpdate() {
- /// 地址信息为空
- guard let updateUrl = ConfigUtils.getServiceUrl(resourceType: .UpdateUrl),
- updateUrl != "" else { return }
- /// 请求更新
- HttpUtils.callInterface(url: updateUrl, type: .GET, params: nil) { (isComplete, response) in
- if isComplete == true,
- let dic = response as? NSDictionary, let arrays = (dic["results"] as? [NSDictionary]), arrays.count != 0 {
- DispatchQueue.main.async {
- guard let appStoreVersion = (arrays[0])["version"] as? String else {return}
- guard let releaseNotes = (arrays[0])["releaseNotes"] as? String else {return}
- guard let trackViewUrl = (arrays[0])["trackViewUrl"] as? String else {return}
- let storeStr = NSString(string: appStoreVersion).replacingOccurrences(of: ".", with: "")
- let appStr = NSString(string: app_Version).replacingOccurrences(of: ".", with: "")
- if storeStr > appStr {
- /// 提示更新
- AppUpdateAlert.showUpdateAlert(version: appStoreVersion, description: releaseNotes, trackViewUrl)
- }
- }
- }
- }
- }
-
- // MARK: - UITextFieldDelegate
- func textFieldShouldReturn(_ textField: UITextField) -> Bool {
- /// 失去焦点
- self.view.endEditing(true)
- /// 开始登录
- if textField == passwordTextField {
- if let _ = MTP2BusinessCore.shared.address {
- startLogin()
- } else {
- /// startAnimating
- self._anim?.startAnimating()
- /// requestAppAdress
- MTP2BusinessCore.shared.requestAppAdress { (isComplete, error) in
- DispatchQueue.main.async {
- /// stopAnimating
- self._anim?.stopAnimating()
- if !isComplete {
- WHToast.showError(withMessage: "登录失败,获取链路失败!", duration: 2.0, finishHandler: {})
- return
- }
- /// 开始登录
- self.startLogin()
- }
- }
- }
- }
- return true
- }
-
- func textFieldDidBeginEditing(_ textField: UITextField) {
-
- if Is_Iphone_678 {
- if textField == usernameTextField {
- UIView.animate(withDuration: 0.3) { self.view.top = -100.0 }
- }
-
- if textField == passwordTextField {
- UIView.animate(withDuration: 0.3) { self.view.top = -140.0 }
- }
- }
-
- if !userTableView.isHidden {
- isExpand = false
- userTableView.isHidden = true
- }
- }
-
- func textFieldDidEndEditing(_ textField: UITextField) {
- UIView.animate(withDuration: 0.3) { self.view.top = 0.0 }
- }
-
- // MARK: - UITableViewDelegate
- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
-
- super.tableView(tableView, didSelectRowAt: indexPath)
-
- usernameTextField.text = tableCellModels[indexPath.row].loginID
- userTableView.isHidden = true
- }
- }
- // MARK: - LoginUserCellDelegate
- extension LoginViewController: LoginUserCellDelegate {
- func delete(rowNum: Int) {
- do {
- try DatabaseHelper.deleteUser(userID: UInt32(tableCellModels[rowNum].userID))
- } catch {
- WHToast.showError(withMessage: error.localizedDescription, duration: 1.5, finishHandler: {})
- }
- tableCellModels.remove(at: rowNum)
- userTableView.deleteRows(at:[IndexPath(row: rowNum, section: 0)], with: .right)
- if tableCellModels.count == 0 { userPull.isHidden = true }
- UIView.animate(withDuration: 0.3) {
-
- self.cellConstraints.constant = CGFloat(self.tableCellModels.count > 5 ? 5 : self.tableCellModels.count) * 44
- self.view.layoutIfNeeded()
- }
- }
- }
- extension LoginViewController: UIPopoverPresentationControllerDelegate {
- func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
- return .none
- }
- }
- extension LoginViewController: SFSafariViewControllerDelegate {
-
- func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
- controller.dismiss(animated: true, completion: {})
- }
- }
|