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