TodoTaskProcessViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. //
  2. // TodoTaskProcessViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 16/8/5.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import Alamofire
  10. import AlamofireImage
  11. import AlamofireObjectMapper
  12. import ObjectMapper
  13. import Eureka
  14. import CocoaLumberjack
  15. import Promises
  16. enum TaskError: Error {
  17. case apiError(String)
  18. }
  19. class TodoTaskProcessViewController:FormViewController {
  20. @IBOutlet weak var submitButton: TaskBarButtonItem!
  21. @IBOutlet weak var taskToolbar: TaskUIToolbar!
  22. var backFlag:Int = 0
  23. var taskProcess:TaskProcess?
  24. var option:String?
  25. var ideaText:String?
  26. var mediaOpinion: String = ""
  27. override func viewDidLoad() {
  28. super.viewDidLoad()
  29. //self.tableView?.backgroundColor = UIColor.blue
  30. let continents = taskProcess?.decisonList
  31. var oneFlag = false
  32. if continents!.count == 1 {
  33. oneFlag = true
  34. }
  35. form +++ SelectableSection<ImageCheckRow<String>>() { section in
  36. section.header = HeaderFooterView(title: "选择决策")
  37. }
  38. self.option = continents?[0]
  39. for option in continents! {
  40. form.last! <<< ImageCheckRow<String>(option){ lrow in
  41. lrow.title = option
  42. lrow.selectableValue = option
  43. lrow.value = (oneFlag == true ? option : (option == self.option ? option : nil))
  44. //lrow.cell.isSelected = option == self.option
  45. }
  46. }
  47. form +++ Section("流程意见")
  48. <<< SegmentedRow<String>("segments"){
  49. $0.options = ["输入意见", "手写意见"]
  50. $0.value = "输入意见"
  51. }
  52. <<< TextAreaRow("idea") { row in
  53. row.hidden = "$segments != '输入意见'"
  54. row.placeholder = "请输入意见"
  55. row.value = self.taskProcess?.opinion ?? ""
  56. }
  57. <<< SignatureViewRow("sign") { row in
  58. row.hidden = "$segments != '手写意见'"
  59. }
  60. self.view.bringSubviewToFront(taskToolbar)
  61. }
  62. private func finishSubmit() {
  63. if self.backFlag != 1 && self.backFlag != 2 && self.backFlag != 5 {
  64. // 3, 4 特殊处理 门户页面跳过来的情况
  65. self.navigationController?.popToRootViewController(animated: true)
  66. }else {
  67. //原路返回
  68. self.performSegue(withIdentifier: "backTodoMe", sender: self.backFlag)
  69. }
  70. }
  71. private func validateFailPopBack() {
  72. DDLogError("返回表单页面")
  73. self.navigationController?.popViewController(animated: true)
  74. }
  75. @IBAction func submitFlowButton(_ sender: UIBarButtonItem) {
  76. DDLogDebug("submit Button Tap")
  77. guard let _ = self.option else {
  78. self.showError(title: "请选择决策")
  79. return
  80. }
  81. if let vies = (parent as? ZLNavigationController)?.viewControllers {
  82. for vc in vies {
  83. if vc is TodoTaskDetailViewController {
  84. DDLogDebug("开始验证表单。。")
  85. (vc as! TodoTaskDetailViewController).checkFormBeforeProcessSubmit(routeName: self.option ?? "", opinion: self.ideaText ?? "", callback: { (result) in
  86. DDLogDebug("验证返回了:\(result)")
  87. if result {
  88. self.letSubmitBegin()
  89. }else {
  90. self.showError(title: "表单验证不通过,无法提交!")
  91. self.validateFailPopBack()
  92. }
  93. })
  94. break
  95. }
  96. }
  97. }else {
  98. self.showError(title: "异常,无法提交!")
  99. }
  100. }
  101. private func letSubmitBegin() {
  102. self.showLoading(title: "提交中...")
  103. //保存、提交
  104. self.saveTaskData().then { (result) -> Promise<String> in
  105. DDLogDebug("save task is success ....\(result)")
  106. let signRow = self.form.rowBy(tag: "sign")
  107. let signImage = (signRow as? SignatureViewRow)?.cell.signView.getSignatureImage()
  108. return self.uploadSignaturePNG(image: signImage)
  109. }.then({ (result) -> Promise<Bool> in
  110. if result != "" { // 签名上传后的id
  111. self.mediaOpinion = result
  112. }
  113. return self.submitWork()
  114. }).then { (result) in
  115. DDLogDebug("submit work is success....\(result)")
  116. self.showSuccess(title: "提交成功")
  117. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
  118. self.finishSubmit()
  119. })
  120. }.catch { (err) in
  121. DDLogError("提交异常。。。。\(err.localizedDescription)")
  122. DispatchQueue.main.async {
  123. self.showError(title: "提交失败,\(err.localizedDescription)")
  124. }
  125. }
  126. }
  127. func saveTaskData() -> Promise<Bool> {
  128. DDLogDebug("保存表单数据,。。。。。。。。。")
  129. return Promise { fulfill, reject in
  130. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskDataContextKey, query: TaskContext.taskDataSaveQuery, parameter: ["##id##":self.taskProcess!.workId! as AnyObject])
  131. AF.request(url!,method:.put, parameters: self.taskProcess!.businessDataDict!, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
  132. switch response.result {
  133. case .success(let val):
  134. let json = JSON(val)
  135. if json["type"] == "success" {
  136. fulfill(true)
  137. }else{
  138. DDLogError(json.description)
  139. reject(TaskError.apiError(json.description))
  140. }
  141. case .failure(let err):
  142. DDLogError(err.localizedDescription)
  143. reject(err)
  144. }
  145. }
  146. }
  147. }
  148. func uploadSignaturePNG(image: UIImage?) -> Promise<String> {
  149. DDLogDebug("上传签名。。。。。。。。。。。")
  150. return Promise { fulfill, reject in
  151. if image == nil {
  152. //没有签名图片 不上传
  153. DDLogDebug("没有签名图片 不上。。。。。。")
  154. fulfill("")
  155. }else {
  156. let updloadURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskUploadAttachmentQuery, parameter: ["##workId##":self.taskProcess!.workId! as AnyObject])
  157. let site = "$mediaOpinion"
  158. AF.upload(multipartFormData: { (mData) in
  159. let pngData = image?.pngData()
  160. mData.append(pngData!, withName: "file", fileName: "signature.png", mimeType: "application/octet-stream")
  161. let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  162. mData.append(siteData!, withName: "site")
  163. }, to: updloadURL!).responseJSON { (response) in
  164. print(response)
  165. if let err = response.error {
  166. reject(err)
  167. }else {
  168. let attachId = JSON(response.data)["data"]["id"].string!
  169. DDLogDebug("上传签名成功。。。id:\(attachId)")
  170. fulfill(attachId)
  171. }
  172. }
  173. // AF.upload(multipartFormData: { (mData) in
  174. // let pngData = image?.pngData()
  175. // mData.append(pngData!, withName: "file", fileName: "signature.png", mimeType: "application/octet-stream")
  176. // let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  177. // mData.append(siteData!, withName: "site")
  178. // }, to: updloadURL!, encodingCompletion: { (encodingResult) in
  179. // switch encodingResult {
  180. // case .success(let upload, _, _):
  181. // upload.responseJSON {
  182. // respJSON in
  183. // switch respJSON.result {
  184. // case .success(let val):
  185. // let attachId = JSON(val)["data"]["id"].string!
  186. // DDLogDebug("上传签名成功。。。id:\(attachId)")
  187. // fulfill(attachId)
  188. // case .failure(let err):
  189. // reject(err)
  190. // break
  191. // }
  192. //
  193. // }
  194. // case .failure(let errType):
  195. // reject(errType)
  196. // }
  197. //
  198. // })
  199. }
  200. }
  201. }
  202. func submitWork() -> Promise<Bool> {
  203. return Promise { fulfill, reject in
  204. self.taskProcess?.decisionRoute = self.option
  205. self.taskProcess?.decisionIdea = self.ideaText ?? ""
  206. var params:[String:String] = [:]
  207. params["routeName"]=self.option
  208. params["opinion"]=self.ideaText ?? ""
  209. params["mediaOpinion"] = self.mediaOpinion
  210. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskSaveAndSubmitQuery, parameter: ["##id##":(self.taskProcess?.taskId)! as AnyObject])
  211. AF.request(url!,method:.post, parameters: params, encoding:JSONEncoding.default, headers: nil).responseJSON { response in
  212. switch response.result {
  213. case .success(let val):
  214. let json = JSON(val)
  215. if json["type"] == "success" {
  216. fulfill(true)
  217. }else{
  218. DDLogError(json.description)
  219. reject(TaskError.apiError(json.description))
  220. }
  221. case .failure(let err):
  222. DDLogError(err.localizedDescription)
  223. reject(err)
  224. }
  225. }
  226. }
  227. }
  228. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  229. if segue.identifier == "backTodoMe" {
  230. let destVC = segue.destination as! TodoTaskDetailViewController
  231. destVC.backFlag = backFlag
  232. }
  233. }
  234. /**
  235. 自动监测各行变化的值
  236. - parameter row: row
  237. - parameter oldValue: 旧值
  238. - parameter newValue: 新值
  239. */
  240. override func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) {
  241. DDLogDebug("oldValue = \(String(describing: oldValue)),newValue=\(String(describing: newValue))")
  242. if row.section == form[0] {
  243. //if newValue != nil {
  244. self.option = newValue as? String
  245. //}
  246. }
  247. if row.section == form[1] {
  248. if row.tag == "idea" {
  249. self.ideaText = newValue as? String
  250. }
  251. if row.tag == "segments" {
  252. DDLogDebug("切换。。。。。。。。。")
  253. let key = newValue as? String
  254. if key == "输入意见" {
  255. let signRow = form.rowBy(tag: "sign") as? SignatureViewRow
  256. signRow?.cell.signView.clearSignature()
  257. self.tableView.isScrollEnabled = true
  258. }else if key == "手写意见" {
  259. let editRow = form.rowBy(tag: "idea") as? TextAreaRow
  260. editRow?.value = ""
  261. self.tableView.isScrollEnabled = false
  262. }
  263. }
  264. }
  265. }
  266. }