O2MainController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. //
  2. // O2MainController.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/1/25.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import CocoaLumberjack
  10. import Starscream
  11. import AudioToolbox
  12. class O2MainController: O2BaseForRotateUITabBarController, UITabBarControllerDelegate {
  13. static var tabBarVC: O2MainController!
  14. static func genernateVC() -> O2MainController {
  15. return O2MainController()
  16. }
  17. private var isSimple = false
  18. private var currentIndex: Int = 0
  19. // demo服务器弹出公告
  20. private var demoAlertView = O2DemoAlertView()
  21. private let viewModel: OOLoginViewModel = {
  22. return OOLoginViewModel()
  23. }()
  24. private lazy var mainViewModel: O2MainViewModel = {
  25. return O2MainViewModel()
  26. }()
  27. //获取消息数量
  28. private lazy var imViewModel: IMViewModel = {
  29. return IMViewModel()
  30. }()
  31. //考勤判断版本
  32. private lazy var attendanceViewModel: OOAttandanceViewModel = {
  33. return OOAttandanceViewModel()
  34. }()
  35. // 云盘
  36. private lazy var cFileVM: CloudFileViewModel = {
  37. return CloudFileViewModel()
  38. }()
  39. // 论坛
  40. private lazy var bbsVm: BBSViewModel = {
  41. return BBSViewModel()
  42. }()
  43. private let barIm = L10n.mainBarIm
  44. private let barContact = L10n.mainBarContacts
  45. private let barApps = L10n.mainBarApps
  46. private let barSettings = L10n.mainBarSettings
  47. override func viewDidLoad() {
  48. super.viewDidLoad()
  49. if UIDevice.deviceModelReadable() != "Simulator" {
  50. self.checkAppVersion()
  51. }
  52. //查询通讯录权限
  53. self.mainViewModel.loadOrgContactPermission()
  54. self.tabBar.tintColor = O2ThemeManager.color(for: "Base.base_color")!
  55. self.delegate = self
  56. // 配置是否简易模式
  57. if let mode = O2AuthSDK.shared.customStyle()?.simpleMode, mode == true {
  58. DDLogDebug("进入简易模式!!!!!!!")
  59. isSimple = true
  60. }
  61. if isSimple {
  62. _initSimpleControllers()
  63. selectedIndex = 0
  64. currentIndex = 0
  65. }else {
  66. _initControllers()
  67. selectedIndex = 2
  68. currentIndex = 2
  69. }
  70. O2JPushManager.shared.o2JPushBind()
  71. // if O2IsConnect2Collect == false {
  72. // //处理内部直连的时候推送的设备绑定
  73. //
  74. // }
  75. //连接websocket
  76. self._startWebsocket()
  77. //读取消息
  78. self.getConversationList()
  79. //检查考勤版本
  80. self.checkAttendanceVersion()
  81. //检查云盘版本
  82. self.checkCloudFileVersion()
  83. // 论坛禁言问题
  84. self.checkBBSMuteInfo()
  85. }
  86. deinit {
  87. //关闭websocket
  88. self._stopWebsocket()
  89. }
  90. override func viewDidAppear(_ animated: Bool) {
  91. // 判断是否 第一次安装 是否是连接的demo服务器
  92. if let unit = O2AuthSDK.shared.bindUnit() {
  93. if "demo.o2oa.net" == unit.centerHost || "demo.o2oa.io" == unit.centerHost || "demo.o2server.io" == unit.centerHost || "sample.o2oa.net" == unit.centerHost {
  94. let tag = AppConfigSettings.shared.demoAlertTag
  95. if !tag {
  96. demoAlertView.showFallDown()
  97. AppConfigSettings.shared.demoAlertTag = true
  98. }
  99. }
  100. }
  101. }
  102. //MARK: -- delegate
  103. func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
  104. self.currentIndex = tabBarController.selectedIndex
  105. }
  106. /// 普通模式
  107. private func _initControllers() {
  108. //消息
  109. let conversationVC = IMConversationListViewController()
  110. conversationVC.title = barIm
  111. let messages = ZLNavigationController(rootViewController: conversationVC)
  112. messages.tabBarItem = UITabBarItem(title: barIm, image: UIImage(named: "icon_news_nor"), selectedImage: O2ThemeManager.image(for: "Icon.icon_news_pre"))
  113. //通讯录
  114. let addressVC = OOTabBarHelper.getVC(storyboardName: "contacts", vcName: nil)
  115. let address = ZLNavigationController(rootViewController: addressVC)
  116. address.tabBarItem = UITabBarItem(title: barContact, image: UIImage(named: "icon_address_g"), selectedImage: O2ThemeManager.image(for: "Icon.icon_address_list_pro"))
  117. // main
  118. let mainVC = mainController()
  119. mainVC.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "icon_zhuye_nor"), selectedImage: O2ThemeManager.image(for: "Icon.icon_zhuye_pre"))
  120. mainVC.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
  121. let blurImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_blur)
  122. let newBlurImage = blurImage?.withRenderingMode(.alwaysOriginal)
  123. mainVC.tabBarItem.image = newBlurImage
  124. let focusImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_focus)
  125. let newFocusImage = focusImage?.withRenderingMode(.alwaysOriginal)
  126. mainVC.tabBarItem.selectedImage = newFocusImage
  127. //应用
  128. let appsVC = OOTabBarHelper.getVC(storyboardName: "apps", vcName: nil)
  129. let apps = ZLNavigationController(rootViewController: appsVC)
  130. apps.tabBarItem = UITabBarItem(title: barApps, image: UIImage(named: "icon_yingyong"), selectedImage: O2ThemeManager.image(for: "Icon.icon_yingyong_pro"))
  131. //设置
  132. let settingsVC = OOTabBarHelper.getVC(storyboardName: "setting", vcName: nil)
  133. let settings = ZLNavigationController(rootViewController: settingsVC)
  134. settings.tabBarItem = UITabBarItem(title: barSettings, image: UIImage(named: "setting_normal"), selectedImage: O2ThemeManager.image(for: "Icon.setting_selected"))
  135. self.viewControllers = [messages, address, mainVC, apps, settings]
  136. }
  137. /// 简版 只有首页和设置
  138. private func _initSimpleControllers() {
  139. // main
  140. let mainVC = mainController()
  141. mainVC.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "icon_zhuye_nor"), selectedImage: O2ThemeManager.image(for: "Icon.icon_zhuye_pre"))
  142. mainVC.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
  143. let blurImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_blur)
  144. let newBlurImage = blurImage?.withRenderingMode(.alwaysOriginal)
  145. mainVC.tabBarItem.image = newBlurImage
  146. let focusImage = OOCustomImageManager.default.loadImage(.index_bottom_menu_logo_focus)
  147. let newFocusImage = focusImage?.withRenderingMode(.alwaysOriginal)
  148. mainVC.tabBarItem.selectedImage = newFocusImage
  149. //设置
  150. let settingsVC = OOTabBarHelper.getVC(storyboardName: "setting", vcName: nil)
  151. let settings = ZLNavigationController(rootViewController: settingsVC)
  152. settings.tabBarItem = UITabBarItem(title: barSettings, image: UIImage(named: "setting_normal"), selectedImage: O2ThemeManager.image(for: "Icon.setting_selected"))
  153. self.viewControllers = [mainVC, settings]
  154. }
  155. private func mainController() -> UIViewController {
  156. let appid = O2AuthSDK.shared.customStyle()?.indexPortal
  157. let indexType = O2AuthSDK.shared.customStyle()?.indexType ?? "default"
  158. if indexType == "portal" {
  159. let app = DBManager.shared.queryData(appid!)
  160. let destVC = OOTabBarHelper.getVC(storyboardName: "apps", vcName: "OOMainWebVC")
  161. if let mail = destVC as? MailViewController {
  162. mail.app = app
  163. mail.isIndexShow = true
  164. let nav = ZLNavigationController(rootViewController: mail)
  165. return nav
  166. } else {
  167. let nav = ZLNavigationController(rootViewController: destVC)
  168. return nav
  169. }
  170. } else {
  171. let destVC = OOTabBarHelper.getVC(storyboardName: "task", vcName: nil)
  172. let nav = ZLNavigationController(rootViewController: destVC)
  173. return nav
  174. }
  175. }
  176. // MARK: - 论坛 禁言问题查询
  177. private func checkBBSMuteInfo() {
  178. self.bbsVm.getMuteInfo().then { info in
  179. O2AuthSDK.shared.setupMuteInfo(muteInfo: info)
  180. }.catch { err in
  181. O2AuthSDK.shared.setupMuteInfo(muteInfo: nil)
  182. }
  183. }
  184. // MARK: - 考勤判断版本
  185. private func checkAttendanceVersion() {
  186. self.attendanceViewModel.listMyRecords { (result) in
  187. switch result {
  188. case .ok(let data):
  189. let model = data as? OOMyAttandanceRecords
  190. if let s = model?.scheduleInfos, s.count > 0 {
  191. StandDefaultUtil.share.userDefaultCache(value: true as AnyObject, key: O2.O2_Attendance_version_key)
  192. DDLogDebug("考勤打卡新版。。。。。。。。。。。。。。。。。。")
  193. }else {
  194. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  195. }
  196. break
  197. case .fail(let err):
  198. DDLogError(err)
  199. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  200. break
  201. default:
  202. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2_Attendance_version_key)
  203. break
  204. }
  205. }
  206. }
  207. // MARK: - 云盘判断是否v3版本
  208. private func checkCloudFileVersion() {
  209. self.cFileVM.v3Echo().then { result in
  210. StandDefaultUtil.share.userDefaultCache(value: result as AnyObject, key: O2.O2CloudFileVersionKey)
  211. }.catch { error in
  212. StandDefaultUtil.share.userDefaultCache(value: false as AnyObject, key: O2.O2CloudFileVersionKey)
  213. DDLogError(error.localizedDescription)
  214. }
  215. }
  216. // MARK: - IM message
  217. func getConversationList() {
  218. imViewModel.myConversationList().then { (list) in
  219. var n = 0
  220. if !list.isEmpty {
  221. for item in list {
  222. if let number = item.unreadNumber {
  223. n += number
  224. }
  225. }
  226. }
  227. DispatchQueue.main.async {
  228. DDLogDebug("消息数量: \(n)")
  229. if n > 0 && n < 100 {
  230. self.showRedPoint(number: "\(n)")
  231. } else if n >= 100 {
  232. self.showRedPoint(number: "99..")
  233. }
  234. }
  235. }
  236. }
  237. private func showRedPoint(number: String) {
  238. self.viewControllers?.forEach({ (vc) in
  239. if let zl = vc as? ZLNavigationController, zl.tabBarItem?.title == barIm {
  240. zl.tabBarItem.badgeValue = number
  241. }
  242. })
  243. }
  244. //消息模块未读消息数量加1
  245. private func addUnreadNumber() {
  246. self.viewControllers?.forEach({ (vc) in
  247. if let zl = vc as? ZLNavigationController, zl.tabBarItem?.title == barIm {
  248. if let badge = zl.tabBarItem.badgeValue {
  249. if badge != "99.." {
  250. if let n = Int(string: badge) {
  251. let number = n + 1
  252. if number > 0 && number < 100 {
  253. self.showRedPoint(number: "\(number)")
  254. } else if number >= 100 {
  255. self.showRedPoint(number: "99..")
  256. }
  257. }
  258. }
  259. }else {
  260. self.showRedPoint(number: "1")
  261. }
  262. }
  263. })
  264. }
  265. // MARK: - app update
  266. private func checkAppVersion() {
  267. O2VersionManager.shared.checkAppUpdate { (info, error) in
  268. if let iosInfo = info {
  269. DDLogDebug(iosInfo.toJSONString() ?? "")
  270. let alertController = UIAlertController(title: "版本更新", message: "更新内容:\(iosInfo.content ?? "")", preferredStyle: .alert)
  271. let okAction = UIAlertAction(title: "确定", style: .default, handler: { ok in
  272. O2VersionManager.shared.updateAppVersion(info?.downloadUrl)
  273. })
  274. let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { c in
  275. //
  276. })
  277. alertController.addAction(cancelAction)
  278. alertController.addAction(okAction)
  279. UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
  280. } else {
  281. DDLogInfo("没有版本更新:\(error ?? "")")
  282. }
  283. }
  284. }
  285. // MARK: - websocket
  286. private var timer: Timer?
  287. private var isWsOpen = false
  288. private func _startWebsocket() {
  289. DDLogDebug("启动websocket连接。。。。。。")
  290. let url = AppDelegate.o2Collect.generateWebsocketURL()
  291. DDLogDebug("这个是wsurl :\(url)")
  292. O2WebsocketManager.instance.startConnect(wsUrl: url, delegate: self)
  293. }
  294. private func _stopWebsocket() {
  295. DDLogDebug("关闭websocket连接。。。。。。")
  296. self.stopTiming()
  297. O2WebsocketManager.instance.closeConnect()
  298. }
  299. private func startTiming() {
  300. DDLogDebug("开启定时器 。。。。。。")
  301. if timer != nil {
  302. timer?.invalidate()
  303. timer = nil
  304. }
  305. timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(sendHeartbeatMsg), userInfo: nil, repeats: true)
  306. timer?.fire()
  307. }
  308. private func stopTiming() {
  309. DDLogDebug("关闭定时器 。。。。。。")
  310. if timer != nil {
  311. timer?.invalidate()
  312. timer = nil
  313. }
  314. }
  315. //发送心跳
  316. @objc private func sendHeartbeatMsg() {
  317. if isWsOpen {
  318. O2WebsocketManager.instance.send(msg: o2_im_ws_heartbeat)
  319. } else { //重新启动
  320. _startWebsocket()
  321. }
  322. }
  323. }
  324. extension O2MainController: WebSocketDelegate {
  325. func didReceive(event: WebSocketEvent, client: WebSocket) {
  326. switch event {
  327. case .text(let text):
  328. if text != o2_im_ws_heartbeat { //忽略心跳消息
  329. DDLogDebug("接收的ws消息:\(text)")
  330. //判断type im消息就发送通知
  331. do {
  332. if let dicArr = try JSONSerialization.jsonObject(with: String(text).data(using: .utf8)!, options: .allowFragments) as? [String: AnyObject] {
  333. if let type = dicArr["type"] as? String, type == "im_create" {
  334. if let messageInfo = WsMessage.deserialize(from: text) {
  335. DDLogDebug("接收到im消息 发送通知。。")
  336. NotificationCenter.post(customeNotification: OONotification.websocket, object: messageInfo.body)
  337. }
  338. self.addUnreadNumber()
  339. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
  340. }
  341. }
  342. } catch { }
  343. }
  344. break
  345. case .connected(let headers):
  346. DDLogDebug("websocket is connected: \(headers)")
  347. isWsOpen = true
  348. self.startTiming()
  349. break
  350. case .disconnected(let reason, let code):
  351. DDLogDebug("websocket is disconnected: \(reason) with code: \(code)")
  352. isWsOpen = false
  353. break
  354. case .binary(let data):
  355. DDLogDebug("websocket binary Received 二进制对象: \(data.count)")
  356. break
  357. case .ping(_):
  358. break
  359. case .pong(_):
  360. break
  361. // case .viablityChanged(_):
  362. // DDLogDebug("websocket viablityChanged")
  363. // break
  364. case .reconnectSuggested(_):
  365. DDLogDebug("websocket reconnectSuggested")
  366. break
  367. case .cancelled:
  368. DDLogDebug("websocket is canceled")
  369. isWsOpen = false
  370. break
  371. case .error(let error):
  372. DDLogError("websocket is error, \(String(describing: error?.localizedDescription))")
  373. isWsOpen = false
  374. break
  375. case .viabilityChanged(_):
  376. DDLogDebug("websocket viablityChanged")
  377. break
  378. }
  379. }
  380. }