RulesViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //
  2. // RulesViewController.m
  3. // kneet
  4. //
  5. // Created by Jason Lee on 3/18/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "RequestHandler.h"
  10. #import "RuleModel.h"
  11. #import "CustomTableView.h"
  12. #import "CustomLabel.h"
  13. #import "CustomImageView.h"
  14. #import "JYRefreshController.h"
  15. #import "UIImageView+WebCache.h"
  16. #import "ImageUtil.h"
  17. #import "RulesViewController.h"
  18. #import "CustomCheckBox.h"
  19. #import "RulesDetailViewController.h"
  20. #import "RulesAddViewController.h"
  21. #define kfRulesTableViewCellHeight 100.0f
  22. @implementation RulesTableViewCell
  23. @end
  24. @interface RulesViewController () <UITableViewDataSource, UITableViewDelegate> {
  25. NSMutableArray<RuleModel> *_ruleList;
  26. NSString *_pagingType, *_pagingId;
  27. UIImage *_stateImageRun, *_stateImageStop, *_stateImageDisable;
  28. BOOL _isNotFirstLoading, _isDeleteMode;
  29. }
  30. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  31. @property (strong, nonatomic) JYPullToLoadMoreController *loadMoreController;
  32. @end
  33. #pragma mark - Class Definition
  34. @implementation RulesViewController
  35. - (void)viewDidLoad {
  36. [super viewDidLoad];
  37. _ruleList = (NSMutableArray<RuleModel> *)[[NSMutableArray alloc] init];
  38. [self initUI];
  39. [self prepareViewDidLoad];
  40. }
  41. - (void)viewWillAppear:(BOOL)animated {
  42. [super viewWillAppear:animated];
  43. }
  44. - (void)initUI {
  45. //initialize tableview
  46. [self initTableViewAsDefaultStyle:_tableView];
  47. //set refresh controls
  48. // __weak typeof(self) weakSelf = self;
  49. // self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
  50. // self.refreshController.pullToRefreshHandleAction = ^{
  51. // [weakSelf requestRuleListRecently];
  52. // };
  53. //
  54. // self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
  55. // self.loadMoreController.pullToLoadMoreHandleAction = ^{
  56. // [weakSelf requestRuleListOlder];
  57. // };
  58. //FIXME : delete?
  59. _stateImageRun = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_play"];
  60. _stateImageStop = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_stop"];
  61. _stateImageDisable = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_disable"];
  62. [self setThingsPopoverOptions];
  63. }
  64. - (void)setThingsPopoverOptions {
  65. //set Popover Contents
  66. __weak typeof(self) weakSelf = self;
  67. _popooverOptionArray = [[NSMutableArray alloc] init];
  68. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil),
  69. @"iconName": @"tp_01_img_bg_morepopup_icon_refresh",
  70. @"target": weakSelf,
  71. @"selector": [NSValue valueWithPointer:@selector(refreshRuleList)]}];
  72. if ([JDFacade facade].loginUser.level > 10) {//파워유저 이상일 경우,
  73. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"만들기", @"만들기"),
  74. @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  75. @"target": weakSelf,
  76. @"selector": [NSValue valueWithPointer:@selector(addNewRule)]}];
  77. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
  78. @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
  79. @"target": weakSelf,
  80. @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
  81. }
  82. }
  83. - (void)prepareViewDidLoad {
  84. if (_ruleList && _ruleList.count) {
  85. [_ruleList removeAllObjects];
  86. }
  87. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  88. }
  89. - (void)updateHomeHubStatusToRules {
  90. }
  91. - (void)refreshRuleList {
  92. _pagingId = nil;
  93. _pagingType = nil;
  94. if (_ruleList && _ruleList.count) {
  95. [_ruleList removeAllObjects];
  96. }
  97. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  98. }
  99. - (void)addNewRule {
  100. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"];
  101. [self presentViewController:vc animated:YES completion:nil];
  102. }
  103. - (void)toggleEditMode {
  104. _isDeleteMode = !_isDeleteMode;
  105. [_tableView reloadData];
  106. _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width;
  107. [UIView animateWithDuration:kfAnimationDur animations:^{
  108. [self.view layoutIfNeeded];
  109. }];
  110. }
  111. #pragma mark - Main Logic
  112. - (void)requestRuleListRecently {
  113. RuleModel *firstRule = [_ruleList firstObject];
  114. _pagingType = ksListPagingTypeUpward;
  115. _pagingId = firstRule.ruleId;
  116. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  117. }
  118. - (void)requestRuleListOlder {
  119. RuleModel *lastRule = [_ruleList lastObject];
  120. _pagingType = ksListPagingTypeDownward;
  121. _pagingId = lastRule.ruleId;
  122. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  123. }
  124. - (void)requestRules {
  125. NSDictionary *parameter = @{@"rule_id": _pagingId ? _pagingId : ksEmptyString,
  126. @"paging_type": _pagingType ? _pagingType : ksEmptyString};
  127. NSString *path = [NSString stringWithFormat:API_GET_RULE];
  128. [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[RuleListModel class] completion:^(id responseObject) {
  129. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  130. return;
  131. }
  132. RuleListModel *fetchedRuleList = (RuleListModel *)responseObject;
  133. if (fetchedRuleList && fetchedRuleList.rules && fetchedRuleList.rules.count) {//API 성공,
  134. if (_pagingType && [_pagingType isEqualToString:ksListPagingTypeUpward]) {
  135. if (_ruleList.count) {
  136. NSRange range = NSMakeRange(0, fetchedRuleList.rules.count);
  137. NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
  138. [_ruleList insertObjects:fetchedRuleList.rules atIndexes:indexSet];
  139. } else {
  140. [_ruleList addObjectsFromArray:fetchedRuleList.rules];
  141. }
  142. } else {
  143. [_ruleList addObjectsFromArray:fetchedRuleList.rules];
  144. }
  145. [self updateTitle];
  146. } else {//실패 시,
  147. if (!_ruleList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  148. // NoContentView *noContentView = [NoContentView viewFromNib];
  149. // _tableView.tableFooterView = noContentView;
  150. }
  151. }
  152. // [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  153. // [self.loadMoreController stopLoadMoreCompletion:nil];
  154. // self.loadMoreController.enable = _ruleList.count % kdListPagginSize == 0;
  155. [_tableView reloadData];
  156. } failure:^(id errorObject) {
  157. JDErrorModel *error = (JDErrorModel *)errorObject;
  158. [[JDFacade facade] alert:error.errorMessage];
  159. }];
  160. }
  161. - (void)requestChangeRuleStatus:(RuleModel *)rule {
  162. //parameters
  163. NSDictionary *parameter = @{@"status_code" : [rule.useYn isEqualToString:@"Y"] ? @"03" : @"02"};
  164. NSString *path = [NSString stringWithFormat:API_POST_RULE_STATUS, rule.homegrpRuleId];
  165. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  166. rule.useYn = [rule.useYn boolValue] ? ksNO : ksYES; //toggle
  167. if ([rule.useYn boolValue]) {
  168. [[JDFacade facade] toast:@"규칙을 다시 시작합니다"];
  169. } else {
  170. [[JDFacade facade] toast:@"규칙을 중단합니다"];
  171. }
  172. // [self changeBtnRunStatus:[rule.useYn boolValue]];
  173. [self updateTitle];
  174. [_tableView reloadData];
  175. } failure:^(id errorObject) {
  176. JDErrorModel *error = (JDErrorModel *)errorObject;
  177. [[JDFacade facade] alert:error.errorMessage];
  178. }];
  179. }
  180. - (void)requestDeleteRule:(RuleModel *)rule {
  181. NSString *path = [NSString stringWithFormat:API_DELETE_RULE, rule.homegrpRuleId];
  182. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {
  183. [[JDFacade facade] toast:@"규칙을 삭제했습니다"];
  184. [_ruleList removeObject:rule];
  185. [self toggleEditMode];
  186. [self updateTitle];
  187. [_tableView reloadData];
  188. } failure:^(id errorObject) {
  189. JDErrorModel *error = (JDErrorModel *)errorObject;
  190. [[JDFacade facade] alert:error.errorMessage];
  191. }];
  192. }
  193. - (void)updateRule:(RuleModel *)rule {
  194. for (RuleModel *tmpRule in _ruleList) {
  195. if ([rule.homegrpRuleId isEqualToString:tmpRule.homegrpRuleId]) {
  196. tmpRule.ruleName = rule.ruleName;
  197. tmpRule.useYn = rule.useYn;
  198. break;
  199. }
  200. }
  201. [_tableView reloadData];
  202. }
  203. - (void)updateTitle {
  204. if (![JDFacade facade].loginUser.isHomehubOnline) {
  205. _lblTitle.text = @"홈허브 오프라인";
  206. [_lblTitle setColor:kUITextColor02 text:_lblTitle.text];
  207. return;
  208. }
  209. //활성/비활성 업데이트
  210. NSInteger inactiveCount = [_ruleList filteredArrayUsingPredicateFormat:@"SELF.useYn == %@", ksNO].count;
  211. NSInteger activeCount = _ruleList.count > inactiveCount ? _ruleList.count - inactiveCount : inactiveCount - _ruleList.count;
  212. _lblTitle.text = [NSString stringWithFormat:@"활성 %zd / 비활성 %zd", activeCount, inactiveCount];
  213. [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", activeCount]];
  214. [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", inactiveCount]];
  215. }
  216. #pragma mark - UITableView DataSource & Delegate
  217. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  218. return 1;
  219. }
  220. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  221. return _ruleList.count;
  222. }
  223. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  224. CGFloat height = kfRulesTableViewCellHeight;
  225. if (indexPath.row == _ruleList.count) {
  226. height = _ruleList.count ? 190.0f : IPHONE_HEIGHT - kfNavigationBarHeight;
  227. _tableView.scrollEnabled = _ruleList.count;
  228. }
  229. return height;
  230. }
  231. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  232. RulesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
  233. RuleModel *rule = _ruleList[indexPath.row];
  234. [cell.imgvTrigger sd_setImageWithURL:[NSURL URLWithString:rule.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  235. cell.lblRuleName.text = rule.ruleName;
  236. cell.btnRulePlay.hidden = _isDeleteMode;
  237. if (!cell.btnRulePlay.hidden) {
  238. cell.btnRulePlay.hidden = [JDFacade facade].loginUser.level < 90;
  239. cell.btnDelete.hidden = YES;
  240. cell.btnRulePlay.value = rule;
  241. if (![cell.btnRulePlay actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  242. [cell.btnRulePlay addTarget:self action:@selector(btnRulePlayTouched:) forControlEvents:UIControlEventTouchUpInside];
  243. }
  244. } else {
  245. cell.btnDelete.hidden = NO;
  246. cell.btnDelete.value = rule;
  247. if (![cell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  248. [cell.btnDelete addTarget:self action:@selector(btnDeleteTouched:) forControlEvents:UIControlEventTouchUpInside];
  249. }
  250. }
  251. return cell;
  252. }
  253. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  254. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  255. if (indexPath.row == _ruleList.count) {
  256. return;
  257. }
  258. if (!_isDeleteMode) {//go to detail
  259. //goto rule details
  260. RulesDetailViewController *vc = (RulesDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesDetailViewController" storyboardName:@"Rules"];
  261. vc.refRule = _ruleList[indexPath.row];
  262. [self presentViewController:vc animated:YES completion:nil];
  263. }
  264. }
  265. #pragma mark - TableView UI Events
  266. - (void)btnRulePlayTouched:(id)sender {
  267. CustomButton *btnRulePlay = (CustomButton *)sender;
  268. RuleModel *rule = btnRulePlay.value;
  269. if ([rule.useYn isEqualToString:ksKneetRulesDisable]) {
  270. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:@"일부 장치가 삭제되었습니다.\n편집 후 실행하세요." delegate:nil OKButtonTitle:@"편집" cancelButtonTitle:@"취소"];
  271. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  272. if (buttonIndex == 0) {//OK
  273. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  274. NSString *path = [NSString stringWithFormat:API_GET_RULE_DETAIL, rule.homegrpRuleId];
  275. RuleDetailModel *ruleDetail = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil modelClass:[RuleDetailModel class] showLoadingView:YES];
  276. RulesAddViewController *vc = (RulesAddViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"];
  277. vc.refRuleDetail = ruleDetail;
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. [self presentViewController:vc animated:YES completion:nil];
  280. });
  281. });
  282. }
  283. }];
  284. return;
  285. }
  286. [self requestChangeRuleStatus:rule];
  287. }
  288. - (void)btnDeleteTouched:(id)sender {
  289. [[JDFacade facade] confirmTitle:@"규칙 삭제" message:@"규칙을 삭제하시겠습니까?" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  290. if (buttonIndex == 0) {//OK
  291. CustomButton *btnDelete = (CustomButton *)sender;
  292. RuleModel *rule = btnDelete.value;
  293. [self requestDeleteRule:rule];
  294. }
  295. }];
  296. }
  297. #pragma mark - UI Events
  298. - (IBAction)btnOptionTouched:(id)sender {
  299. [self toggleOptions:sender];
  300. }
  301. - (IBAction)btnCloseOnEditModeTouched:(id)sender {
  302. [self toggleEditMode];
  303. }
  304. #pragma mark - MemoryWarning
  305. - (void)didReceiveMemoryWarning
  306. {
  307. [super didReceiveMemoryWarning];
  308. // Dispose of any resources that can be recreated.
  309. }
  310. @end