// // 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 import SwiftDate /// 登录视图容器管理类 class LoginViewController: BaseTableViewController, 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 savePwd: UISwitch! /// 账户信息下拉按钮 @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) /// 获取是否记录密码 self.savePwd.isOn = UserDefaultsUtils.isSavePwd() /// 记住了密码 并且密码不为空 并且6小时有效 if self.savePwd.isOn, let pwd = UserDefaultsUtils.savePwd(), let date = UserDefaultsUtils.savePwdTime(), ((Date()-date).hour ?? 0)<=6 { /// 填入密码 passwordTextField.text = pwd } /// 设置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: {}) } } } @IBAction func onValueChanged(_ sender: UISwitch) { /// 记录是否记住密码 UserDefaultsUtils.setIsSavePwd(sender.isOn) } /// 获取保存的用户账号 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 } } /// 显示所有的账户信息 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, let account = self.usernameTextField.text, let password = self.passwordTextField.text else { return } /// startAnimating self._anim?.startAnimating() /// isUserInteractionEnabled self.view.isUserInteractionEnabled = false /// isEnabled 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 } /// 每次登录前重新请求地址信息 MTP2BusinessCore.shared.requestAppAdress(true) { (isAddress, er) in if !isAddress { faidBlock(er) 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)) }) if self.savePwd.isOn { /// 记住密码和时间 UserDefaultsUtils.setSavePwd(password) UserDefaultsUtils.setSavePwdTime(Date()) } 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, 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 /// 清空密码输入框 passwordTextField.text = "" } } // 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: {}) } }