LoginViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. //
  2. // LoginViewController.swift
  3. // MTP2_iOS
  4. //
  5. // Created by zhongyuan on 2018/5/10.
  6. // Copyright © 2018年 zhongyuan.All rights reserved.
  7. //
  8. import UIKit
  9. import NVActivityIndicatorView
  10. import WHToast
  11. import SwiftyAttributes
  12. import SafariServices
  13. /// 登录视图容器管理类
  14. class LoginViewController: BaseTableViewController<LsLoginUserModel>, UITextFieldDelegate {
  15. // MARK: - 生命周期
  16. private static let TAG_LOGIN = 100
  17. private static let TAG_REGIEST = 101
  18. private static let TAG_PULL = 102
  19. private static let TAG_WACHAT = 103
  20. private static let TAG_ALIPAY = 104
  21. private static let TAG_PHONE_LOGIN = 105
  22. private static let TAG_FORGETPWD = 106
  23. /// 账户名称
  24. @IBOutlet weak var usernameTextField: UITextField!
  25. /// 账户密码
  26. @IBOutlet weak var passwordTextField: UITextField!
  27. /// 登录按钮
  28. @IBOutlet weak var loginButton: UIButton!
  29. /// 手机号码登录
  30. @IBOutlet weak var phoneLoginButton: UIButton! {
  31. didSet {
  32. phoneLoginButton.isHidden = !((ConfigUtils.getValue(key: .SupportMobileLogin) as? Bool) ?? true)
  33. }
  34. }
  35. /// 账户信息下拉按钮
  36. @IBOutlet weak var userPull: UIButton!
  37. /// 用户信息
  38. @IBOutlet weak var userTableView: UITableView! {
  39. didSet {
  40. userTableView.layer.cornerRadius = 5.0
  41. userTableView.layer.borderWidth = 0.5
  42. userTableView.layer.borderColor = UIColorFromHex(rgbValue: 0xe0e0e0).cgColor
  43. userTableView.layer.masksToBounds = true
  44. }
  45. }
  46. /// cell的高度约束
  47. @IBOutlet weak var cellConstraints: NSLayoutConstraint!
  48. /// 微信
  49. @IBOutlet weak var weixinButton: UIButton!
  50. /// 支付宝
  51. @IBOutlet weak var alipayButton: UIButton!
  52. /// 忘记密码
  53. @IBOutlet weak var forgetPwdButton: UIButton! {
  54. didSet {
  55. forgetPwdButton.isHidden = !((ConfigUtils.getValue(key: .SupportResetPwd) as? Bool) ?? true)
  56. }
  57. }
  58. /// 版本号
  59. @IBOutlet weak var versionLabel: UILabel! {
  60. didSet {
  61. versionLabel.text = "版本号:V" + app_Version
  62. }
  63. }
  64. /// 是否张开状态
  65. private var isExpand = false
  66. // MARK: - 生命周期相关
  67. override func viewDidLoad() {
  68. super.viewDidLoad()
  69. /// 隐藏导航栏
  70. self.navigationController?.setNavigationBarHidden(true, animated: true)
  71. /// Loading
  72. addLoadingView()
  73. /// 界面内容初始化
  74. buildView()
  75. /// 数据初始化
  76. initData()
  77. /// 初始化用户信息
  78. initUser()
  79. }
  80. override func viewDidAppear(_ animated: Bool) {
  81. super.viewDidAppear(animated)
  82. /// stopAnimating
  83. if let isAnimating = self._anim?.isAnimating,
  84. isAnimating { self._anim?.stopAnimating() }
  85. }
  86. // MARK: - 初始化相关
  87. /// 数据初始化
  88. func initData() {
  89. /// 请求app版本更新
  90. self.requestAppVersionUpdate()
  91. }
  92. /// 界面内容初始化
  93. func buildView() {
  94. /// 设置attributedPlaceholder
  95. usernameTextField.attributedPlaceholder = "用户名/账号/手机号".withTextColor(Color_placeholder_text)
  96. passwordTextField.attributedPlaceholder = "请输入您的密码".withTextColor(Color_placeholder_text)
  97. /// 设置cell标识
  98. cellReuseIdentifier = "LoginUserCellID"
  99. /// tableView 设置
  100. userTableView.rowHeight = 44.0
  101. }
  102. // MARK: - 用户交互相关
  103. @IBAction func viewPassed(_ sender: UIButton) {
  104. if self.usernameTextField.isFirstResponder {
  105. self.usernameTextField.resignFirstResponder()
  106. }
  107. if self.passwordTextField.isFirstResponder {
  108. self.passwordTextField.resignFirstResponder()
  109. }
  110. switch sender.tag {
  111. case LoginViewController.TAG_LOGIN:
  112. if let _ = MTP2BusinessCore.shared.address {
  113. startLogin()
  114. } else {
  115. /// startAnimating
  116. self._anim?.startAnimating()
  117. /// requestAppAdress
  118. MTP2BusinessCore.shared.requestAppAdress { (isComplete, error) in
  119. DispatchQueue.main.async {
  120. /// stopAnimating
  121. self._anim?.stopAnimating()
  122. if !isComplete {
  123. WHToast.showError(withMessage: "登录失败,获取链路失败!", duration: 2.0, finishHandler: {})
  124. return
  125. }
  126. /// 开始登录
  127. self.startLogin()
  128. }
  129. }
  130. }
  131. case LoginViewController.TAG_PULL: /// 帐户列表
  132. getAllUser()
  133. case LoginViewController.TAG_FORGETPWD: /// 忘记密码
  134. /// 进入到重置密码
  135. self.present(storyboardName: "ResetPwd", storyboardId: "ResetPwdFirstStepID")
  136. case LoginViewController.TAG_PHONE_LOGIN: /// 帐户注册
  137. guard let url = URL(string: MTP2BusinessCore.shared.address?.mobileOpenUrl ?? "") else { return }
  138. let safriViewController = SFSafariViewController(url: url)
  139. safriViewController.delegate = self
  140. self.present(safriViewController, animated: true, completion: {})
  141. default:
  142. if (self.navigationController?.viewControllers.count ?? 0) > 1 {
  143. self.navigationController?.popViewController(animated: true)
  144. } else {
  145. self.dismiss(animated: true, completion: {})
  146. }
  147. }
  148. }
  149. /// 获取保存的用户账号
  150. func initUser() {
  151. if let userInfo = try? DatabaseHelper.getUsers(type: Int16(0)) {
  152. tableCellModels = userInfo.compactMap({ LsLoginUserModel(source: $0) }).sorted(by: { (obj1, obj2) -> Bool in
  153. return obj1.loginDate>obj2.loginDate
  154. })
  155. usernameTextField.text = tableCellModels[0].loginID
  156. userPull.isHidden = userInfo.count > 0 ? false : true
  157. } else {
  158. usernameTextField.text = ""
  159. tableCellModels.removeAll()
  160. userPull.isHidden = true
  161. }
  162. passwordTextField.text = ""
  163. }
  164. /// 显示所有的账户信息
  165. func getAllUser() {
  166. /// 是否展开
  167. isExpand = !isExpand
  168. /// 是否隐藏
  169. self.userTableView.isHidden = !self.isExpand
  170. /// 约束
  171. self.cellConstraints.constant = 0.0
  172. /// 动画
  173. UIView.animate(withDuration: 0.3) {
  174. self.cellConstraints.constant = self.isExpand ? CGFloat(self.tableCellModels.count > 5 ? 5 : self.tableCellModels.count) * 44 : 0
  175. self.view.layoutIfNeeded()
  176. }
  177. userTableView.reloadData()
  178. }
  179. // MARK: - 登录相关
  180. /// 用户登录校验
  181. ///
  182. /// - Returns: 是否成功
  183. private func checkValue() -> Bool {
  184. if let account = self.usernameTextField.text {
  185. if account.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty {
  186. WHToast.showError(withMessage: "请输入登录账户", duration: 1.0) {
  187. self.usernameTextField.becomeFirstResponder()
  188. }
  189. return false
  190. }
  191. }
  192. if let password = self.passwordTextField.text {
  193. if password.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty {
  194. WHToast.showError(withMessage: "请输入账户密码", duration: 1.0) {
  195. self.passwordTextField.becomeFirstResponder()
  196. }
  197. return false
  198. }
  199. }
  200. return true
  201. }
  202. /// 登录方法
  203. func startLogin() {
  204. /// 异常
  205. guard checkValue(),
  206. let accountManager = MTP2BusinessCore.shared.accountManager else { return }
  207. /// account
  208. let account = self.usernameTextField.text
  209. /// password
  210. let password = self.passwordTextField.text
  211. self._anim?.startAnimating()
  212. self.view.isUserInteractionEnabled = false
  213. self.loginButton.isEnabled = false
  214. let faidBlock = { (error: ErrorInfo?) in
  215. DispatchQueue.main.async {
  216. self._anim?.stopAnimating()
  217. self.view.isUserInteractionEnabled = true
  218. self.loginButton.isEnabled = true
  219. if let error = error,
  220. error.retCode == 1003,
  221. let loginrsp = accountManager.loginRsp {
  222. let message = "还剩\(loginrsp.pwdWrongLockCnt - loginrsp.pwdWrongCnt)次错误机会,账号或密码不匹配达到\(loginrsp.pwdWrongLockCnt)次,登录账号将锁定\(loginrsp.loginLockHourNum)小时。请联系管理员966000处理。" + "您也可通过手机验证码登录!"
  223. self.showHintController(title: "提示", message: message)
  224. } else {
  225. self.showErrorMessgae(error: error)
  226. }
  227. }
  228. }
  229. guard let trade_address = MTP2BusinessCore.shared.address?.tradeHost,
  230. let trade_port = MTP2BusinessCore.shared.address?.tradePort,
  231. let intPort = UInt16(trade_port) else { return }
  232. /// 获取登录ID
  233. accountManager.getUserLoginID(account ?? "") { (isSuccess, err, loginId) in
  234. if !isSuccess {
  235. faidBlock(err)
  236. return
  237. }
  238. DispatchQueue.main.async {
  239. accountManager.login(address: trade_address, port: intPort, userName: loginId!, password: password!, deviceID: NSUUID().uuidString, version: app_Version) { isCompleted, error in
  240. if isCompleted {
  241. /// 用户与商品信息统一查询
  242. accountManager.queryAccountAndGoods(callback: { (isCompleted, error) in
  243. if isCompleted {
  244. DispatchQueue.main.async {
  245. /// 如果有 先删除
  246. if let _ = try? DatabaseHelper.getUser(userID: MTP2BusinessCore.shared.getUserID(), type: Int16(0)) {
  247. try? DatabaseHelper.deleteUser(userID: MTP2BusinessCore.shared.getUserID())
  248. }
  249. DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+0.5, execute: {
  250. /// 记录本地用户信息
  251. try? DatabaseHelper.addUser(userID: MTP2BusinessCore.shared.getUserID(), loginID: account ?? "", loginDate: Date(), type: Int16(0))
  252. })
  253. self._anim?.stopAnimating()
  254. self.view.isUserInteractionEnabled = true
  255. self.loginButton.isEnabled = true
  256. /// 进入主界面
  257. if let mainTabBarController: UITabBarController = self.storyboard?.instantiateViewController(withIdentifier: "MainTabBarController") as? UITabBarController {
  258. /// 设置根视图
  259. (UIApplication.shared.delegate as? AppDelegate)?.window?.rootViewController = mainTabBarController
  260. }
  261. }
  262. } else {
  263. faidBlock(error)
  264. }
  265. })
  266. } else {
  267. faidBlock(error)
  268. }
  269. }
  270. }
  271. }
  272. }
  273. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  274. super.touchesBegan(touches, with: event)
  275. /// 关闭
  276. if !userTableView.isHidden {
  277. isExpand = false
  278. userTableView.isHidden = true
  279. }
  280. }
  281. // MARK: - 版本更新相关
  282. /// app检测版本更新
  283. fileprivate func requestAppVersionUpdate() {
  284. /// 地址信息为空
  285. guard let updateUrl = ConfigUtils.getServiceUrl(resourceType: .UpdateUrl),
  286. updateUrl != "" else { return }
  287. /// 请求更新
  288. HttpUtils.callInterface(url: updateUrl, type: .GET, params: nil) { (isComplete, response) in
  289. if isComplete == true,
  290. let dic = response as? NSDictionary, let arrays = (dic["results"] as? [NSDictionary]), arrays.count != 0 {
  291. DispatchQueue.main.async {
  292. guard let appStoreVersion = (arrays[0])["version"] as? String else {return}
  293. guard let releaseNotes = (arrays[0])["releaseNotes"] as? String else {return}
  294. guard let trackViewUrl = (arrays[0])["trackViewUrl"] as? String else {return}
  295. let storeStr = NSString(string: appStoreVersion).replacingOccurrences(of: ".", with: "")
  296. let appStr = NSString(string: app_Version).replacingOccurrences(of: ".", with: "")
  297. if storeStr > appStr {
  298. /// 提示更新
  299. AppUpdateAlert.showUpdateAlert(version: appStoreVersion, description: releaseNotes, trackViewUrl)
  300. }
  301. }
  302. }
  303. }
  304. }
  305. // MARK: - UITextFieldDelegate
  306. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  307. /// 失去焦点
  308. self.view.endEditing(true)
  309. /// 开始登录
  310. if textField == passwordTextField {
  311. if let _ = MTP2BusinessCore.shared.address {
  312. startLogin()
  313. } else {
  314. /// startAnimating
  315. self._anim?.startAnimating()
  316. /// requestAppAdress
  317. MTP2BusinessCore.shared.requestAppAdress { (isComplete, error) in
  318. DispatchQueue.main.async {
  319. /// stopAnimating
  320. self._anim?.stopAnimating()
  321. if !isComplete {
  322. WHToast.showError(withMessage: "登录失败,获取链路失败!", duration: 2.0, finishHandler: {})
  323. return
  324. }
  325. /// 开始登录
  326. self.startLogin()
  327. }
  328. }
  329. }
  330. }
  331. return true
  332. }
  333. func textFieldDidBeginEditing(_ textField: UITextField) {
  334. if Is_Iphone_678 {
  335. if textField == usernameTextField {
  336. UIView.animate(withDuration: 0.3) { self.view.top = -100.0 }
  337. }
  338. if textField == passwordTextField {
  339. UIView.animate(withDuration: 0.3) { self.view.top = -140.0 }
  340. }
  341. }
  342. if !userTableView.isHidden {
  343. isExpand = false
  344. userTableView.isHidden = true
  345. }
  346. }
  347. func textFieldDidEndEditing(_ textField: UITextField) {
  348. UIView.animate(withDuration: 0.3) { self.view.top = 0.0 }
  349. }
  350. // MARK: - UITableViewDelegate
  351. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  352. super.tableView(tableView, didSelectRowAt: indexPath)
  353. usernameTextField.text = tableCellModels[indexPath.row].loginID
  354. userTableView.isHidden = true
  355. }
  356. }
  357. // MARK: - LoginUserCellDelegate
  358. extension LoginViewController: LoginUserCellDelegate {
  359. func delete(rowNum: Int) {
  360. do {
  361. try DatabaseHelper.deleteUser(userID: UInt32(tableCellModels[rowNum].userID))
  362. } catch {
  363. WHToast.showError(withMessage: error.localizedDescription, duration: 1.5, finishHandler: {})
  364. }
  365. tableCellModels.remove(at: rowNum)
  366. userTableView.deleteRows(at:[IndexPath(row: rowNum, section: 0)], with: .right)
  367. if tableCellModels.count == 0 { userPull.isHidden = true }
  368. UIView.animate(withDuration: 0.3) {
  369. self.cellConstraints.constant = CGFloat(self.tableCellModels.count > 5 ? 5 : self.tableCellModels.count) * 44
  370. self.view.layoutIfNeeded()
  371. }
  372. }
  373. }
  374. extension LoginViewController: UIPopoverPresentationControllerDelegate {
  375. func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
  376. return .none
  377. }
  378. }
  379. extension LoginViewController: SFSafariViewControllerDelegate {
  380. func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
  381. controller.dismiss(animated: true, completion: {})
  382. }
  383. }