O2BaseJsMessageHandler.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 SwiftyJSON
  16. class O2BaseJsMessageHandler: O2WKScriptMessageHandlerImplement {
  17. let viewController: BaseWebViewUIViewController
  18. init(viewController: BaseWebViewUIViewController) {
  19. self.viewController = viewController
  20. }
  21. func userController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  22. let name = message.name
  23. switch name {
  24. case "o2mLog":
  25. if message.body is NSString {
  26. let log = message.body as! NSString
  27. DDLogDebug("console.log: \(log)")
  28. }else {
  29. DDLogDebug("console.log: unkown type \(message.body)")
  30. }
  31. break
  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.showLoading(title: "Loading...")
  183. AF.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.hideLoading()
  199. case .failure(let err):
  200. DDLogError(err.localizedDescription)
  201. self.viewController.hideLoading()
  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 vc = FileBSImagePickerViewController().bsImagePicker()
  248. self.viewController.presentImagePicker(vc, 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. var fName = (asset.value(forKey: "filename") as? String) ?? "untitle.png"
  260. // 判断是否是heif
  261. var isHEIF = false
  262. if #available(iOS 9.0, *) {
  263. let resList = PHAssetResource.assetResources(for: asset)
  264. resList.forEachEnumerated { (idx, res) in
  265. let uti = res.uniformTypeIdentifier
  266. if uti == "public.heif" || uti == "public.heic" {
  267. isHEIF = true
  268. }
  269. }
  270. } else {
  271. if let uti = asset.value(forKey: "uniformTypeIdentifier") as? String {
  272. if uti == "public.heif" || uti == "public.heic" {
  273. isHEIF = true
  274. }
  275. }
  276. }
  277. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  278. DispatchQueue.main.async {
  279. self.viewController.showLoading(title: "上传中...")
  280. }
  281. var newData = imageData
  282. if isHEIF {
  283. let image: UIImage = UIImage(data: imageData!)!
  284. newData = image.jpegData(compressionQuality: 1.0)!
  285. fName += ".jpg"
  286. }
  287. //处理图片旋转的问题
  288. if imageOrientation != UIImage.Orientation.up && newData != nil {
  289. let newImage = UIImage(data: newData!)?.fixOrientation()
  290. if newImage != nil {
  291. newData = newImage?.pngData()
  292. }
  293. }
  294. let fileUploadURL = AppDelegate.o2Collect
  295. .generateURLWithAppContextKey(
  296. FileContext.fileContextKey,
  297. query: FileContext.fileUploadReference,
  298. parameter: [
  299. "##referencetype##": data.referencetype as AnyObject,
  300. "##reference##": data.reference as AnyObject,
  301. "##scale##": String(data.scale) as AnyObject
  302. ],
  303. coverted: true)!
  304. DDLogDebug(fileUploadURL)
  305. let tokenName = O2AuthSDK.shared.tokenName()
  306. let headers:HTTPHeaders = [tokenName:(O2AuthSDK.shared.myInfo()?.token!)!]
  307. // let fileURL = dict?["PHImageFileURLKey"] as! URL
  308. DispatchQueue.global(qos: .userInitiated).async {
  309. AF.upload(multipartFormData: { (mData) in
  310. mData.append(newData!, withName: "file", fileName: fName, mimeType: "image/png")
  311. }, to: fileUploadURL, method: .put, headers: headers).responseJSON { (response) in
  312. if let err = response.error {
  313. DispatchQueue.main.async {
  314. DDLogError(err.localizedDescription)
  315. self.viewController.showError(title: "上传图片失败")
  316. }
  317. }else {
  318. let attachId = JSON(response.data)["data"]["id"].string!
  319. data.fileId = attachId
  320. let callback = data.callback!
  321. let callbackParameterJson = data.toJSONString()
  322. if callbackParameterJson != nil {
  323. DDLogDebug("json:\(callbackParameterJson!)")
  324. DispatchQueue.main.async {
  325. let callJS = "\(callback)('\(callbackParameterJson!)')"
  326. DDLogDebug("执行js:\(callJS)")
  327. self.viewController.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  328. self.viewController.showSuccess(title: "上传成功")
  329. })
  330. }
  331. }
  332. }
  333. }
  334. // AF.upload(multipartFormData: { (mData) in
  335. // mData.append(newData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "image/png")
  336. // }, to: fileUploadURL, method: .put, headers: headers, encodingCompletion: { (encodingResult) in
  337. // switch encodingResult {
  338. // case .success(let upload, _, _):
  339. //
  340. // upload.responseJSON {
  341. // respJSON in
  342. // switch respJSON.result {
  343. // case .success(let val):
  344. // let attachId = JSON(val)["data"]["id"].string!
  345. // data.fileId = attachId
  346. // let callback = data.callback!
  347. // let callbackParameterJson = data.toJSONString()
  348. // if callbackParameterJson != nil {
  349. // DDLogDebug("json:\(callbackParameterJson!)")
  350. // DispatchQueue.main.async {
  351. // let callJS = "\(callback)('\(callbackParameterJson!)')"
  352. // DDLogDebug("执行js:\(callJS)")
  353. // self.viewController.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  354. // self.viewController.showSuccess(title: "上传成功")
  355. // })
  356. // }
  357. // }
  358. //
  359. // case .failure(let err):
  360. // DispatchQueue.main.async {
  361. // DDLogError(err.localizedDescription)
  362. // self.viewController.showError(title: "上传图片失败")
  363. // }
  364. // break
  365. // }
  366. //
  367. // }
  368. // case .failure(let errType):
  369. // DispatchQueue.main.async {
  370. // DDLogError(errType.localizedDescription)
  371. // self.viewController.showError(title: "上传图片失败")
  372. // }
  373. // }
  374. //
  375. // })
  376. }
  377. })
  378. }else {
  379. DDLogError("选择类型不正确,不是照片")
  380. }
  381. }
  382. }, completion: nil)
  383. }
  384. }