O2BaseJsMessageHandler.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //
  2. // O2BaseJsMessageHandler.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/4/26.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import WebKit
  10. import Alamofire
  11. import ObjectMapper
  12. import CocoaLumberjack
  13. import BSImagePicker
  14. import Photos
  15. import O2OA_Auth_SDK
  16. import SwiftyJSON
  17. class O2BaseJsMessageHandler: O2WKScriptMessageHandlerImplement {
  18. let viewController: BaseWebViewUIViewController
  19. init(viewController: BaseWebViewUIViewController) {
  20. self.viewController = viewController
  21. }
  22. func userController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  23. let name = message.name
  24. switch name {
  25. case "o2mLog":
  26. if message.body is NSString {
  27. let log = message.body as! NSString
  28. DDLogDebug("console.log: \(log)")
  29. }else {
  30. DDLogDebug("console.log: unkown type \(message.body)")
  31. }
  32. case "ReplyAction":
  33. DDLogDebug("回复 帖子 message.body = \(message.body)")
  34. let pId : String?
  35. if message.body is NSDictionary {
  36. let parentId:NSDictionary = message.body as! NSDictionary
  37. pId = parentId["body"] as? String
  38. }else if message.body is NSString {
  39. pId = String(message.body as! NSString)
  40. }else {
  41. pId = nil
  42. }
  43. self.viewController.performSegue(withIdentifier: "showReplyActionSegue", sender: pId)
  44. break
  45. case "openO2Work":
  46. DDLogDebug("打开工作界面。。。。。")
  47. let body = message.body
  48. if body is NSDictionary {
  49. let dic = body as! NSDictionary
  50. let work = dic["work"] as? String
  51. let workCompleted = dic["workCompleted"] as? String
  52. let title = dic["title"] as? String
  53. self.openWork(work: (work ?? ""), workCompleted: (workCompleted ?? ""), title: (title ?? ""))
  54. }else {
  55. DDLogError("message body 不是一个字典。。。。。。")
  56. }
  57. break
  58. case "openO2WorkSpace":
  59. DDLogDebug("打开工作列表。。。。。")
  60. if message.body is NSString {
  61. let type = message.body as! NSString
  62. self.openO2WorkSpace(type: String(type))
  63. }else {
  64. DDLogError("打开工作列表失败, type不存在!!!!!")
  65. }
  66. break
  67. case "openO2CmsApplication":
  68. DDLogDebug("打开cms栏目。。。。。")
  69. if message.body is NSString {
  70. let appId = message.body as! NSString
  71. self.openCmsApplication(appId: String(appId))
  72. }else if message.body is NSDictionary {
  73. let appBody = message.body as! NSDictionary
  74. if let appId = appBody["appId"] {
  75. self.openCmsApplication(appId: (appId as! String))
  76. }
  77. }else {
  78. DDLogError("打开cms栏目失败, appId不存在!!!!!")
  79. }
  80. break
  81. case "openO2CmsDocument":
  82. DDLogDebug("打开cms 文档。。。。。")
  83. if message.body is NSDictionary {
  84. let appBody = message.body as! NSDictionary
  85. let docId = appBody["docId"] as? String
  86. let docTitle = appBody["docTitle"] as? String
  87. self.openCmsDocument(docId: (docId ?? "" ), docTitle: (docTitle ?? ""))
  88. }else {
  89. DDLogError("打开cms文档失败, 参数不存在!!!!!")
  90. }
  91. break
  92. case "openO2Meeting":
  93. DDLogDebug("打开会议管理。。。。。")
  94. self.openO2Meeting()
  95. break
  96. case "openO2Calendar":
  97. DDLogDebug("打开日程管理。。。。。")
  98. self.openO2Calendar()
  99. break
  100. case "openScan":
  101. self.openScan()
  102. break
  103. case "openO2Alert":
  104. if message.body is NSString {
  105. let msg = message.body as! NSString
  106. self.openO2Alert(message: String(msg))
  107. }
  108. break
  109. case "closeNativeWindow":
  110. DDLogDebug("关闭窗口!!!!")
  111. self.viewController.delegate?.closeUIViewWindow()
  112. break
  113. case "openDingtalk":
  114. self.openDingtalk()
  115. break
  116. case "actionBarLoaded":
  117. self.viewController.delegate?.actionBarLoaded(show: true)
  118. break
  119. case "uploadImage2FileStorage":
  120. DDLogDebug("这里进入了上传图片控件。。。。。。。。。。。。。。。")
  121. if message.body is NSString {
  122. let json = message.body as! NSString
  123. DDLogDebug("上传图片:\(json)")
  124. if let uploadImage = O2WebViewUploadImage.deserialize(from: String(json)) {
  125. self.uploadImage(data: uploadImage)
  126. }else {
  127. DDLogError("解析json失败")
  128. self.viewController.showError(title: "参数不正确!")
  129. }
  130. }else {
  131. DDLogError("传入参数类型不正确!")
  132. self.viewController.showError(title: "参数不正确!")
  133. }
  134. break
  135. default:
  136. DDLogError("传入js变量名称不正确,name:\(name)")
  137. if message.body is NSString {
  138. let json = message.body as! NSString
  139. DDLogDebug("console.log: \(json)")
  140. }
  141. break
  142. }
  143. }
  144. private func openO2Alert(message: String) {
  145. DDLogDebug("O2 alert msg:\(message)")
  146. self.viewController.showSystemAlert(title: "", message: message) { (action) in
  147. DDLogDebug("O2 alert ok button clicked! ")
  148. }
  149. }
  150. private func openWork(work: String, workCompleted: String, title: String) {
  151. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  152. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTaskDetailVC") as! TodoTaskDetailViewController
  153. let json = """
  154. {"work":"\(work)", "workCompleted":"\(workCompleted)", "title":"\(title)"}
  155. """
  156. DDLogDebug("openWork json: \(json)")
  157. let todo = TodoTask(JSONString: json)
  158. destVC.todoTask = todo
  159. destVC.backFlag = 3 //隐藏就行
  160. self.viewController.show(destVC, sender: nil)
  161. }
  162. // task taskCompleted read readCompleted
  163. private func openO2WorkSpace(type: String) {
  164. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  165. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTask")
  166. let nsType = NSString(string: type).lowercased
  167. DDLogDebug("打开工作区, type:\(nsType)")
  168. if "taskcompleted" == nsType {
  169. AppConfigSettings.shared.taskIndex = 2
  170. }else if "read" == nsType {
  171. AppConfigSettings.shared.taskIndex = 1
  172. }else if "readcompleted" == nsType {
  173. AppConfigSettings.shared.taskIndex = 3
  174. }else {
  175. AppConfigSettings.shared.taskIndex = 0
  176. }
  177. self.viewController.show(destVC, sender: nil)
  178. }
  179. private func openCmsApplication(appId: String) {
  180. DDLogInfo("打开栏目, appId:\(appId)")
  181. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsCategoryListQuery, parameter: ["##appId##": appId as AnyObject])
  182. self.viewController.showMessage(title: "Loading...")
  183. Alamofire.request(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
  184. switch response.result {
  185. case .success(let val):
  186. let categroyList = Mapper<CMSCategoryData>().map(JSONObject: val)
  187. if let count = categroyList?.data?.count {
  188. if count > 0 {
  189. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  190. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSCategoryListController") as! CMSCategoryListViewController
  191. destVC.title = categroyList?.data?.first?.appName ?? ""
  192. let d = CMSData(JSONString: "{\"id\":\"\"}")
  193. d?.wrapOutCategoryList = categroyList?.data
  194. destVC.cmsData = d
  195. self.viewController.show(destVC, sender: nil)
  196. }
  197. }
  198. self.viewController.dismissProgressHUD()
  199. case .failure(let err):
  200. DDLogError(err.localizedDescription)
  201. self.viewController.dismissProgressHUD()
  202. }
  203. }
  204. }
  205. private func openCmsDocument(docId: String, docTitle: String) {
  206. DDLogInfo("打开文档, docId:\(docId) , docTitle:\(docTitle)")
  207. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  208. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSSubjectDetailVC") as! CMSItemDetailViewController
  209. let json = """
  210. {"title":"\(docTitle)", "id":"\(docId)"}
  211. """
  212. destVC.itemData = CMSCategoryItemData(JSONString: json)
  213. self.viewController.show(destVC, sender: nil)
  214. }
  215. private func openO2Meeting() {
  216. let storyBoard = UIStoryboard(name: "meeting", bundle: nil)
  217. if let destVC = storyBoard.instantiateInitialViewController() {
  218. self.viewController.show(destVC, sender: nil)
  219. }else {
  220. DDLogError("会议 模块打开失败,没有找到vc")
  221. }
  222. }
  223. private func openO2Calendar() {
  224. let storyBoard = UIStoryboard(name: "calendar", bundle: nil)
  225. if let destVC = storyBoard.instantiateInitialViewController() {
  226. self.viewController.show(destVC, sender: nil)
  227. }else {
  228. DDLogError("calendar 模块打开失败,没有找到vc")
  229. }
  230. }
  231. private func openScan() {
  232. ScanHelper.openScan(vc: self.viewController)
  233. }
  234. private func openDingtalk() {
  235. UIApplication.shared.open(URL(string: "dingtalk://dingtalkclient/")!, options: [:]) { (result) in
  236. DDLogInfo("打开了钉钉。。。。\(result)")
  237. }
  238. }
  239. // 表单图片控件
  240. private func uploadImage(data: O2WebViewUploadImage) {
  241. if data.callback == nil || data.callback.isEmpty || data.reference == nil || data.reference.isEmpty
  242. || data.referencetype == nil || data.referencetype.isEmpty {
  243. self.viewController.showError(title: "参数传入为空,无法上传图片")
  244. return
  245. }
  246. data.scale = 800
  247. let chooseImage = FileBSImagePickerViewController()
  248. self.viewController.bs_presentImagePickerController(chooseImage, animated: true, select: nil, deselect: nil, cancel: nil, finish: { (arr) in
  249. let count = arr.count
  250. DDLogDebug("选择了照片数量:\(count)")
  251. if count > 0 {
  252. //获取照片
  253. let asset = arr[0]
  254. if asset.mediaType == .image {
  255. let options = PHImageRequestOptions()
  256. options.isSynchronous = true
  257. options.deliveryMode = .fastFormat
  258. options.resizeMode = .none
  259. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  260. DispatchQueue.main.async {
  261. self.viewController.showMessage(title: "上传中...")
  262. }
  263. var newData = imageData
  264. //处理图片旋转的问题
  265. if imageOrientation != UIImage.Orientation.up && imageData != nil {
  266. let newImage = UIImage(data: imageData!)?.fixOrientation()
  267. if newImage != nil {
  268. newData = newImage?.pngData()
  269. }
  270. }
  271. let fileUploadURL = AppDelegate.o2Collect
  272. .generateURLWithAppContextKey(
  273. FileContext.fileContextKey,
  274. query: FileContext.fileUploadReference,
  275. parameter: [
  276. "##referencetype##": data.referencetype as AnyObject,
  277. "##reference##": data.reference as AnyObject,
  278. "##scale##": String(data.scale) as AnyObject
  279. ],
  280. coverted: true)!
  281. DDLogDebug(fileUploadURL)
  282. let headers:HTTPHeaders = ["x-token":(O2AuthSDK.shared.myInfo()?.token!)!]
  283. let fileURL = dict?["PHImageFileURLKey"] as! URL
  284. DispatchQueue.global(qos: .userInitiated).async {
  285. Alamofire.upload(multipartFormData: { (mData) in
  286. mData.append(newData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "image/png")
  287. }, to: fileUploadURL, method: .put, headers: headers, encodingCompletion: { (encodingResult) in
  288. switch encodingResult {
  289. case .success(let upload, _, _):
  290. upload.responseJSON {
  291. respJSON in
  292. switch respJSON.result {
  293. case .success(let val):
  294. let attachId = JSON(val)["data"]["id"].string!
  295. data.fileId = attachId
  296. let callback = data.callback!
  297. let callbackParameterJson = data.toJSONString()
  298. if callbackParameterJson != nil {
  299. DDLogDebug("json:\(callbackParameterJson!)")
  300. DispatchQueue.main.async {
  301. let callJS = "\(callback)('\(callbackParameterJson!)')"
  302. DDLogDebug("执行js:\(callJS)")
  303. self.viewController.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  304. self.viewController.showSuccess(title: "上传成功")
  305. })
  306. }
  307. }
  308. case .failure(let err):
  309. DispatchQueue.main.async {
  310. DDLogError(err.localizedDescription)
  311. self.viewController.showError(title: "上传图片失败")
  312. }
  313. break
  314. }
  315. }
  316. case .failure(let errType):
  317. DispatchQueue.main.async {
  318. DDLogError(errType.localizedDescription)
  319. self.viewController.showError(title: "上传图片失败")
  320. }
  321. }
  322. })
  323. }
  324. })
  325. }else {
  326. DDLogError("选择类型不正确,不是照片")
  327. }
  328. }
  329. }, completion: nil)
  330. }
  331. }