RulesViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. #import "CustomLabelButton.h"
  22. #import "HomeMemberViewController.h"
  23. #import "CustomSwitch.h"
  24. #define kfRulesTableViewCellHeight 101.0f
  25. @implementation RulesTableViewCell
  26. @end
  27. @implementation RulesCreateTableViewCell
  28. @end
  29. @interface RulesViewController () <UITableViewDataSource, UITableViewDelegate> {
  30. NSMutableArray<RuleModel> *_ruleList;
  31. NSString *_pagingType, *_pagingId;
  32. UIImage *_stateImageRun, *_stateImageStop;
  33. UIImage *_btnImageRun, *_btnImageStop;
  34. BOOL _isNotFirstLoading, _isDeleteMode;
  35. }
  36. @property (strong, nonatomic) JYPullToRefreshController *refreshController;
  37. @end
  38. #pragma mark - Class Definition
  39. @implementation RulesViewController
  40. - (void)viewDidLoad {
  41. [super viewDidLoad];
  42. // _ruleList = (NSMutableArray<RuleModel> *)[[NSMutableArray alloc] init];
  43. [self initUI];
  44. [self prepareViewDidLoad];
  45. }
  46. - (void)viewWillAppear:(BOOL)animated {
  47. [super viewWillAppear:animated];
  48. if (_isNotFirstLoading) {
  49. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  50. }
  51. }
  52. - (void)initUI {
  53. //initialize tableview
  54. [self initTableViewAsDefaultStyle:_tableView];
  55. _btnImageRun = [UIImage imageNamed:@"img_rule_list_playbtn_active"];
  56. _btnImageStop = [UIImage imageNamed:@"img_rule_list_playbtn_disable"];
  57. _stateImageRun = [UIImage imageNamed:@"common_bullet_circle_red"];
  58. _stateImageStop = [UIImage imageNamed:@"common_bullet_circle_gray"];
  59. _tableView.backgroundColor = [UIColor clearColor];
  60. [self setThingsPopoverOptions];
  61. [self initRefreshController];
  62. }
  63. - (void)initRefreshController {
  64. //set refresh controls
  65. __weak typeof(self) weakSelf = self;
  66. self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
  67. self.refreshController.pullToRefreshHandleAction = ^{
  68. [weakSelf requestRules];
  69. };
  70. }
  71. - (void)setThingsPopoverOptions {
  72. //set Popover Contents
  73. __weak typeof(self) weakSelf = self;
  74. _popooverOptionArray = [[NSMutableArray alloc] init];
  75. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로고침",nil),
  76. @"iconName": @"img_bg_morepopup_icon_refresh",
  77. @"target": weakSelf,
  78. @"selector": [NSValue valueWithPointer:@selector(refreshRuleList)]}];
  79. if ([JDFacade facade].loginUser.level > 10) {//파워유저 이상일 경우,
  80. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"만들기", @"만들기"),
  81. @"iconName": @"img_bg_morepopup_icon_edit",
  82. @"target": weakSelf,
  83. @"selector": [NSValue valueWithPointer:@selector(addNewRule)]}];
  84. [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"삭제", @"삭제"),
  85. @"iconName": @"img_bg_morepopup_icon_del",
  86. @"target": weakSelf,
  87. @"selector": [NSValue valueWithPointer:@selector(toggleEditMode)]}];
  88. }
  89. }
  90. - (void)prepareViewDidLoad {
  91. [self updateTitle];
  92. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  93. }
  94. - (void)updateHomeHubStatusToRules {
  95. [self updateTitle];
  96. }
  97. - (void)refreshRuleList {
  98. _pagingId = nil;
  99. _pagingType = nil;
  100. if (_ruleList && _ruleList.count) {
  101. [_ruleList removeAllObjects];
  102. }
  103. [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  104. }
  105. - (void)addNewRule {
  106. UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"];
  107. [self presentViewController:vc animated:YES completion:nil];
  108. }
  109. - (void)toggleEditMode {
  110. _isDeleteMode = !_isDeleteMode;
  111. if (_isDeleteMode) {
  112. _lblTitle.text = @"규칙 삭제";
  113. _imgvHubAlert.hidden = YES;
  114. } else {
  115. [self updateTitle];
  116. }
  117. [_tableView reloadData];
  118. _constraintEditModeRight.constant = _isDeleteMode ? 0 : -_editModeView.width;
  119. [UIView animateWithDuration:kfAnimationDur animations:^{
  120. [self.view layoutIfNeeded];
  121. }];
  122. }
  123. #pragma mark - Main Logic
  124. //- (void)requestRuleListRecently {
  125. //
  126. // RuleModel *firstRule = [_ruleList firstObject];
  127. // _pagingType = ksListPagingTypeUpward;
  128. // _pagingId = firstRule.ruleId;
  129. //
  130. // [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  131. //}
  132. //
  133. //- (void)requestRuleListOlder {
  134. //
  135. // RuleModel *lastRule = [_ruleList lastObject];
  136. // _pagingType = ksListPagingTypeDownward;
  137. // _pagingId = lastRule.ruleId;
  138. //
  139. // [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
  140. //}
  141. - (void)requestRules {
  142. if (![JDFacade facade].loginUser.hasHomeHub) {
  143. return;
  144. }
  145. // NSDictionary *parameter = @{@"rule_id": _pagingId ? _pagingId : ksEmptyString,
  146. // @"paging_type": _pagingType ? _pagingType : ksEmptyString};
  147. // NSString *path = [NSString stringWithFormat:API_GET_RULE];
  148. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_RULE aditional:@""];
  149. [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[RuleListModel class] completion:^(id responseObject) {
  150. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  151. return;
  152. }
  153. RuleListModel *fetchedRuleList = (RuleListModel *)responseObject;
  154. if (fetchedRuleList && fetchedRuleList.rules && fetchedRuleList.rules.count) {//API 성공,
  155. _ruleList = [fetchedRuleList.rules mutableCopy];
  156. } else {
  157. if (!_ruleList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
  158. _lblConnectHub.text = @"등록된 규칙이 없습니다";
  159. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_nodevice"];
  160. }
  161. }
  162. [self updateTitle];
  163. [_tableView reloadData];
  164. //refresh controller
  165. if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
  166. [self.refreshController stopRefreshWithAnimated:YES completion:nil];
  167. }
  168. if (!_isNotFirstLoading) {
  169. _isNotFirstLoading = YES;
  170. }
  171. } failure:^(id errorObject) {
  172. JDErrorModel *error = (JDErrorModel *)errorObject;
  173. [[JDFacade facade] alert:error.errorMessage];
  174. }];
  175. }
  176. - (void)requestChangeRuleStatus:(RuleModel *)rule {
  177. //parameters
  178. NSDictionary *parameter = @{@"status_code" : [rule.useYn isEqualToString:@"Y"] ? @"03" : @"02"};
  179. NSString *path = [NSString stringWithFormat:API_POST_RULE_STATUS, rule.homegrpRuleId];
  180. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
  181. rule.useYn = [rule.useYn boolValue] ? ksNO : ksYES; //toggle
  182. if ([rule.useYn boolValue]) {
  183. [[JDFacade facade] toast:@"규칙을 다시 시작합니다"];
  184. } else {
  185. [[JDFacade facade] toast:@"규칙을 중단합니다"];
  186. }
  187. // [self changeBtnRunStatus:[rule.useYn boolValue]];
  188. [self updateTitle];
  189. [_tableView reloadData];
  190. } failure:^(id errorObject) {
  191. JDErrorModel *error = (JDErrorModel *)errorObject;
  192. [[JDFacade facade] alert:error.errorMessage];
  193. }];
  194. }
  195. - (void)requestDeleteRule:(RuleModel *)rule {
  196. NSString *path = [NSString stringWithFormat:API_DELETE_RULE, rule.homegrpRuleId];
  197. [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {
  198. [[JDFacade facade] toast:@"규칙을 삭제했습니다"];
  199. [_ruleList removeObject:rule];
  200. [self toggleEditMode];
  201. [self updateTitle];
  202. [_tableView reloadData];
  203. } failure:^(id errorObject) {
  204. JDErrorModel *error = (JDErrorModel *)errorObject;
  205. [[JDFacade facade] alert:error.errorMessage];
  206. }];
  207. }
  208. - (void)updateRule:(RuleModel *)rule {
  209. for (RuleModel *tmpRule in _ruleList) {
  210. if ([rule.homegrpRuleId isEqualToString:tmpRule.homegrpRuleId]) {
  211. tmpRule.ruleName = rule.ruleName;
  212. tmpRule.useYn = rule.useYn;
  213. break;
  214. }
  215. }
  216. [_tableView reloadData];
  217. }
  218. - (void)updateTitle {
  219. if (_isDeleteMode) {
  220. return;
  221. }
  222. NSInteger inactiveCount = [_ruleList filteredArrayUsingPredicateFormat:@"SELF.useYn != %@", ksYES].count;
  223. NSInteger activeCount = _ruleList.count > inactiveCount ? _ruleList.count - inactiveCount : inactiveCount - _ruleList.count;
  224. _lblTitle.text = [NSString stringWithFormat:@"적용 %zd / 미적용 %zd", activeCount, inactiveCount];
  225. if (![JDFacade facade].loginUser.hasHomeHub) {//홈허브 아이디가 없는 경우,
  226. [_mainView bringSubviewToFront:_addHubContainerView];
  227. _addHubContainerView.hidden = NO;
  228. _tableView.hidden = YES;
  229. _btnOption.hidden = YES;
  230. if (![JDFacade facade].loginUser.homegrpId) {//연결한 적이 없음
  231. _lblConnectHub.text = @"초대를 받아서\n시작해 보세요";
  232. _imgvHubAlert.hidden = YES;
  233. _imgvConnectHub.image = [UIImage imageNamed:@"img_1depth_invitation"];
  234. _lblLeaveAccount.hidden = YES;
  235. _lblSimpleMemberInfo.hidden = YES;
  236. } else {//홈허브가 삭제됨.
  237. _lblTitle.text = @"홈허브 삭제됨";
  238. _imgvHubAlert.hidden = NO;
  239. _lblConnectHub.text = @"홈허브를 다시 연결하려면\n고객센터에 문의해주세요";
  240. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_cscenter"];
  241. if ([JDFacade facade].loginUser.level < 90) {//일반 유저일 경우,
  242. _imgvConnectHub.image = [UIImage imageNamed:@"img_things_homehub_img_hubdelete_wait"];
  243. _lblLeaveAccount.hidden = NO;
  244. _lblSimpleMemberInfo.hidden = NO;
  245. [_lblLeaveAccount setUnderLine:_lblLeaveAccount.text];
  246. if (!_lblLeaveAccount.touchHandler) {
  247. [_lblLeaveAccount addTouchEventHandler:^(id label) {
  248. [self leaveHomegroup];
  249. }];
  250. }
  251. }
  252. }
  253. } else {
  254. if (![JDFacade facade].loginUser.isHomehubOnline) {
  255. _imgvHubAlert.hidden = NO;
  256. _lblTitle.text = @"홈허브 오프라인";
  257. [_lblTitle setColor:kUITextColor01 text:_lblTitle.text];
  258. } else {
  259. _imgvHubAlert.hidden = YES;
  260. }
  261. [_mainView bringSubviewToFront:_tableView];
  262. _addHubContainerView.hidden = YES;
  263. _tableView.hidden = NO;
  264. _btnOption.hidden = NO;
  265. }
  266. //활성/비활성 업데이트
  267. if ([_lblTitle.text rangeOfString:@"활성"].location != NSNotFound) {
  268. [_lblTitle setColor:kUITextColor02 text:[NSString stringWithFormat:@"%zd", activeCount]];
  269. [_lblTitle setColor:kUITextColor03 text:[NSString stringWithFormat:@"비활성 %zd", inactiveCount]];
  270. }
  271. }
  272. - (void)leaveHomegroup {
  273. HomeMemberViewController *vc = [[HomeMemberViewController alloc] init];
  274. [vc leaveHomegroup];
  275. }
  276. #pragma mark - UITableView DataSource & Delegate
  277. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  278. NSInteger auth = [JDFacade facade].loginUser.level == 90 && !_isDeleteMode;
  279. NSInteger count = _ruleList.count > 0 ? 1 + auth : 1;
  280. return count;
  281. }
  282. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  283. NSInteger count = 1;
  284. if (_ruleList.count > 0 && section == 0) {//규칙이 있을 경우,
  285. count = _ruleList.count;
  286. }
  287. return count;
  288. }
  289. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  290. CGFloat height = kfRulesTableViewCellHeight;
  291. NSInteger section = indexPath.section;
  292. if (_ruleList.count > 0 && section == 0) {//규칙이 있을 경우,
  293. height = 77.0f;
  294. } else if (_ruleList.count > 0 && section == 1) {
  295. height = 135.0f;
  296. } else {
  297. height = IPHONE_HEIGHT - kfNavigationBarHeight - 55.0f; //header, tabbar
  298. }
  299. // if (indexPath.row == _ruleList.count) {
  300. // height = _ruleList.count ? 190.0f : IPHONE_HEIGHT - kfNavigationBarHeight;
  301. // _tableView.scrollEnabled = _ruleList.count;
  302. // }
  303. return height;
  304. }
  305. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  306. NSInteger section = indexPath.section;
  307. UITableViewCell *rcell = nil;
  308. if (_ruleList.count > 0 && section == 0) {//규칙이 있을 경우,
  309. RulesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
  310. RuleModel *rule = _ruleList[indexPath.row];
  311. [cell.imgvTrigger sd_setImageWithURL:[NSURL URLWithString:rule.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  312. cell.lblRuleName.text = rule.ruleName;
  313. cell.btnRulePlay.hidden = _isDeleteMode;
  314. if (!cell.btnRulePlay.hidden) {//삭제 모드일 경우,
  315. cell.btnRulePlay.hidden = [JDFacade facade].loginUser.level < 90;
  316. cell.btnDelete.hidden = YES;
  317. cell.imgvStatus.image = [rule.useYn boolValue] ? _stateImageRun : _stateImageStop;
  318. UIImage *btnImage = [rule.useYn boolValue] ? _btnImageRun : _btnImageStop;
  319. [cell.btnRulePlay setImage:btnImage forState:UIControlStateNormal];
  320. cell.btnRulePlay.value = rule;
  321. if (![cell.btnRulePlay actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  322. [cell.btnRulePlay addTarget:self action:@selector(btnRulePlayTouched:) forControlEvents:UIControlEventTouchUpInside];
  323. }
  324. } else {
  325. cell.btnDelete.hidden = NO;
  326. cell.btnDelete.value = rule;
  327. if (![cell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  328. [cell.btnDelete addTarget:self action:@selector(btnDeleteTouched:) forControlEvents:UIControlEventTouchUpInside];
  329. }
  330. }
  331. rcell = cell;
  332. } else {
  333. RulesCreateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];
  334. if (![cell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  335. [cell.btnAdd addTarget:self action:@selector(addNewRule) forControlEvents:UIControlEventTouchUpInside];
  336. }
  337. rcell = cell;
  338. }
  339. return rcell;
  340. }
  341. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  342. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  343. if (indexPath.row == _ruleList.count) {
  344. return;
  345. }
  346. if (!_isDeleteMode) {//go to detail
  347. //goto rule details
  348. RulesDetailViewController *vc = (RulesDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesDetailViewController" storyboardName:@"Rules"];
  349. vc.refRule = _ruleList[indexPath.row];
  350. [self presentViewController:vc animated:YES completion:nil];
  351. }
  352. }
  353. #pragma mark - TableView UI Events
  354. - (void)btnRulePlayTouched:(id)sender {
  355. CustomButton *btnRulePlay = (CustomButton *)sender;
  356. RuleModel *rule = btnRulePlay.value;
  357. if ([rule.useYn isEqualToString:ksKneetRulesDisable]) {//규칙 비활성화 일 경우,
  358. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:@"일부 장치가 삭제되었습니다.\n편집 후 실행하세요." delegate:nil OKButtonTitle:@"편집" cancelButtonTitle:@"취소"];
  359. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  360. if (buttonIndex == 0) {//OK
  361. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
  362. NSString *path = [NSString stringWithFormat:API_GET_RULE_DETAIL, rule.homegrpRuleId];
  363. RuleDetailModel *ruleDetail = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil modelClass:[RuleDetailModel class] showLoadingView:YES];
  364. RulesAddViewController *vc = (RulesAddViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddViewController" storyboardName:@"Rules"];
  365. vc.refRuleDetail = ruleDetail;
  366. dispatch_async(dispatch_get_main_queue(), ^{
  367. [self presentViewController:vc animated:YES completion:nil];
  368. });
  369. });
  370. }
  371. }];
  372. } else {
  373. [self requestChangeRuleStatus:rule];
  374. }
  375. }
  376. - (void)btnDeleteTouched:(id)sender {
  377. [[JDFacade facade] confirmTitle:@"규칙 삭제" message:@"규칙을 삭제하시겠습니까?" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  378. if (buttonIndex == 0) {//OK
  379. CustomButton *btnDelete = (CustomButton *)sender;
  380. RuleModel *rule = btnDelete.value;
  381. [self requestDeleteRule:rule];
  382. }
  383. }];
  384. }
  385. #pragma mark - UI Events
  386. - (IBAction)btnOptionTouched:(id)sender {
  387. [self toggleOptions:sender];
  388. }
  389. - (IBAction)btnCloseTouched:(id)sender {
  390. }
  391. - (IBAction)btnCloseOnEditModeTouched:(id)sender {
  392. [self toggleEditMode];
  393. }
  394. #pragma mark - MemoryWarning
  395. - (void)didReceiveMemoryWarning
  396. {
  397. [super didReceiveMemoryWarning];
  398. // Dispose of any resources that can be recreated.
  399. }
  400. @end