OOCalendarMainMonthViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //
  2. // OOCalendarMainMonthViewController.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2018/7/30.
  6. // Copyright © 2018 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import FSCalendar
  10. import CocoaLumberjack
  11. import Promises
  12. class OOCalendarMainMonthViewController: UIViewController {
  13. //MARK: - arguments
  14. var eventsByDate:[String:[OOCalendarEventInfo]]?{
  15. didSet {
  16. //todo
  17. }
  18. }
  19. var calendarIds:[String] = []
  20. private var eventShowList:[OOCalendarEventInfo] = []
  21. private var _today: Date?
  22. private var _selectDay: Date?
  23. private var _currentPerson: String?
  24. private var _startTime: Date?
  25. private var _endTime: Date?
  26. private lazy var viewModel: OOCalendarViewModel = {
  27. return OOCalendarViewModel()
  28. }()
  29. //MARK: - IB
  30. fileprivate var calendarViewDic: [Int : FSCalendar] = [:]
  31. // 这个按钮是日历
  32. @IBAction func todayAction(_ sender: Any) {
  33. _selectDay = _today
  34. calendarViewDic[0]?.select(_today)
  35. }
  36. @IBOutlet weak var tableView: UITableView!
  37. @IBOutlet weak var calendarBtn: UIButton!
  38. @IBOutlet weak var todayBtn: UIButton!
  39. override func viewDidLoad() {
  40. super.viewDidLoad()
  41. navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeWindow))
  42. navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "add"), style: .plain, target: self, action: #selector(addEvent))
  43. // Do any additional setup after loading the view.
  44. self.tableView.delegate = self
  45. self.tableView.dataSource = self
  46. self.tableView.tableFooterView = UIView(frame: CGRect.zero)
  47. self.calendarBtn.theme_setTitleColor(ThemeColorPicker(keyPath: "Base.base_color"), forState: .normal)
  48. self.todayBtn.theme_setTitleColor(ThemeColorPicker(keyPath: "Base.base_color"), forState: .normal)
  49. //初始化
  50. let account = O2AuthSDK.shared.myInfo()
  51. _currentPerson = account?.distinguishedName
  52. _today = Date()
  53. _selectDay = _today
  54. _startTime = DateUtil.share.monthStartDate(date: _today!)
  55. _endTime = DateUtil.share.monthEndDate(startDate: _startTime!)
  56. setNavTitle(date: _today!)
  57. NotificationCenter.default.addObserver(self, selector: #selector(setTheCalendarIds(_:)), name: OONotification.calendarIds.notificationName, object: nil)
  58. }
  59. override func viewWillAppear(_ animated: Bool) {
  60. loadData()
  61. }
  62. override func didReceiveMemoryWarning() {
  63. super.didReceiveMemoryWarning()
  64. // Dispose of any resources that can be recreated.
  65. }
  66. //设置
  67. @objc private func setTheCalendarIds(_ notification:NSNotification) {
  68. DDLogDebug("接收到通知消息")
  69. if let ids = notification.object as? [String] {
  70. DDLogDebug("设置ids:\(ids)")
  71. self.calendarIds = ids
  72. }
  73. }
  74. /*
  75. // MARK: - Navigation
  76. // In a storyboard-based application, you will often want to do a little preparation before navigation
  77. */
  78. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  79. if segue.identifier == "showEventDetail" {
  80. let add = sender as? String
  81. if add != nil && add == "add" {
  82. DDLogInfo("新增日程!")
  83. }else {
  84. let row = tableView.indexPathForSelectedRow!.row
  85. let destination = segue.destination as! OOCalendarEventViewController
  86. destination.eventInfo = self.eventShowList[row]
  87. }
  88. }
  89. if segue.identifier == "showCalendarList" {
  90. if !self.calendarIds.isEmpty {
  91. if let dest = segue.destination as? OOCalendarLeftMenuController {
  92. dest.calendarIds = self.calendarIds
  93. }
  94. }
  95. }
  96. }
  97. //MARK: - private func
  98. @objc func closeWindow() {
  99. self.navigationController?.dismiss(animated: true, completion: nil)
  100. }
  101. @objc func addEvent() {
  102. self.performSegue(withIdentifier: "showEventDetail", sender: "add")
  103. }
  104. private func loadData() {
  105. self.showLoading()
  106. let filter = OOCalendarEventFilter()
  107. filter.startTime = self._startTime?.toString("yyyy-MM-dd HH:mm:ss")
  108. filter.endTime = self._endTime?.toString("yyyy-MM-dd HH:mm:ss")
  109. filter.calendarIds = self.calendarIds
  110. viewModel.filterCalendarEventList(filter: filter).then { (response) -> Promise<[String:[OOCalendarEventInfo]]> in
  111. return Promise<[String:[OOCalendarEventInfo]]> { fulfill, reject in
  112. var result: [String:[OOCalendarEventInfo]] = [:]
  113. if let one = response.inOneDayEvents {
  114. one.forEach({ (event) in
  115. if let date = event.eventDate {
  116. if var array = result[date] {
  117. event.inOneDayEvents?.forEach({ (info) in
  118. array.append(info)
  119. })
  120. result[date] = array
  121. }else {
  122. result[date] = event.inOneDayEvents ?? []
  123. }
  124. }
  125. })
  126. }
  127. if let all = response.wholeDayEvents {
  128. DDLogInfo("全天事件。。。。\(all.count)")
  129. all.forEach({ (event) in
  130. //处理连续多天的事件。。。。。
  131. let dateArray = self.splitDays(startDay: event.startTimeStr!, endDay: event.endTimeStr!)
  132. for date in dateArray {
  133. if var array = result[date] {
  134. array.append(event)
  135. result[date] = array
  136. }else {
  137. result[date] = [event]
  138. }
  139. }
  140. })
  141. }
  142. fulfill(result)
  143. }
  144. }.then { (dict) in
  145. DDLogInfo("filter 结果: \(dict.count)")
  146. self.eventsByDate = dict
  147. // 刷新页面
  148. self.calendarViewDic[0]?.reloadData()
  149. self.calendarViewDic[0]?.select(self._selectDay)
  150. self.selectCalendarDate(self._selectDay!)
  151. }.always {
  152. self.hideLoading()
  153. }.catch { (error) in
  154. DDLogError(error.localizedDescription)
  155. }
  156. }
  157. /**
  158. * 分割成多天
  159. * @param startDay yyyy-MM-dd HH:mm:ss
  160. * @param endDay yyyy-MM-dd HH:mm:ss
  161. * @return [yyyy-MM-dd]
  162. */
  163. private func splitDays(startDay: String, endDay: String) -> [String] {
  164. var ret:[String] = []
  165. guard let sDay = Date.date(startDay) else {
  166. return ret
  167. }
  168. guard let eDay = Date.date(endDay) else {
  169. return ret
  170. }
  171. if sDay.haveSameYearMonthAndDay(eDay) {
  172. ret.append(sDay.toString("yyyy-MM-dd"))
  173. }else {
  174. let gap = sDay.betweenDays(eDay)
  175. for index in 0...gap {
  176. let nDay = sDay.add(component: .day, value: index)
  177. ret.append(nDay.toString("yyyy-MM-dd"))
  178. }
  179. }
  180. return ret
  181. }
  182. private func haveEventForDay(_ date:Date) -> Bool{
  183. guard let dict = eventsByDate else {
  184. return false
  185. }
  186. let key = self.dateFormatter().string(from: date)
  187. if dict[key] != nil && (dict[key]?.count)! > 0 {
  188. return true
  189. }
  190. return false
  191. }
  192. private func dateFormatter() -> DateFormatter {
  193. var dateFormatter: DateFormatter?
  194. if dateFormatter == nil {
  195. dateFormatter = DateFormatter()
  196. dateFormatter?.dateFormat = "yyyy-MM-dd"
  197. }
  198. return dateFormatter!
  199. }
  200. private func setNavTitle(date: Date) {
  201. navigationItem.title = date.toString("yyyy年MM月")
  202. }
  203. // 选中日历上的日期 刷新日程列表
  204. private func selectCalendarDate(_ date: Date) {
  205. let clickDate = date.toString("yyyy-MM-dd")
  206. DDLogInfo("did select date \(clickDate) ")
  207. if let showList = eventsByDate?[clickDate] {
  208. eventShowList = showList
  209. }else {
  210. eventShowList.removeAll()
  211. }
  212. self.tableView.reloadData()
  213. }
  214. }
  215. //MARK: - extension
  216. extension OOCalendarMainMonthViewController: UITableViewDelegate, UITableViewDataSource {
  217. func numberOfSections(in tableView: UITableView) -> Int {
  218. // #warning Incomplete implementation, return the number of sections
  219. return 1
  220. }
  221. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  222. // #warning Incomplete implementation, return the number of rows
  223. let count = eventShowList.count
  224. DDLogInfo("row size \(count)")
  225. return count
  226. }
  227. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  228. let cell = tableView.dequeueReusableCell(withIdentifier: "CalendarEventCell") as! CalendarEventTableViewCell
  229. // Configure the cell...
  230. cell.renderCell(withItem: eventShowList[indexPath.row])
  231. return cell
  232. }
  233. func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  234. return CGFloat(300)
  235. }
  236. func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  237. if let view = self.calendarViewDic[section] {
  238. return view
  239. }
  240. let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 300))
  241. calendar.dataSource = self
  242. calendar.delegate = self
  243. calendar.firstWeekday = 1
  244. calendar.appearance.headerTitleColor = UIColor.darkGray//头部字体样色
  245. calendar.appearance.headerDateFormat = "yyyy年MM月" //头部样式
  246. calendar.appearance.weekdayTextColor = O2ThemeManager.color(for: "Base.base_color")! // 星期字体颜色
  247. calendar.locale = Locale.init(identifier: "zh_CN")
  248. calendar.headerHeight = CGFloat(0)
  249. calendarViewDic[section] = calendar
  250. return calendar
  251. }
  252. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  253. let row = indexPath.row
  254. DDLogInfo("click table row:\(row)")
  255. let event = self.eventShowList[row]
  256. DDLogInfo("点击了事件:\(event.title ?? "")")
  257. tableView.deselectRow(at: indexPath, animated: false)
  258. }
  259. }
  260. extension OOCalendarMainMonthViewController: FSCalendarDataSource, FSCalendarDelegate {
  261. func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
  262. calendar.frame = CGRect(origin: calendar.frame.origin, size: bounds.size)
  263. }
  264. func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
  265. if haveEventForDay(date) {
  266. return 1
  267. }
  268. return 0
  269. }
  270. func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
  271. _selectDay = date
  272. selectCalendarDate(date)
  273. }
  274. func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
  275. let monthStartDay = calendar.currentPage
  276. let monthEndDay = DateUtil.share.monthEndDate(startDate: monthStartDay)
  277. self._startTime = monthStartDay
  278. self._endTime = monthEndDay
  279. _selectDay = monthStartDay
  280. setNavTitle(date: monthStartDay)
  281. loadData()
  282. }
  283. }