O2BaseJsMessageHandler.swift 16 KB

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