RulesAddViewController.m 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. //
  2. // RulesAddViewController.m
  3. // kneet2
  4. //
  5. // Created by Jason Lee on 11/20/15.
  6. // Copyright © 2015 ntels. All rights reserved.
  7. //
  8. #import "JDObject.h"
  9. #import "RequestHandler.h"
  10. #import "ItemModel.h"
  11. #import "RuleModel.h"
  12. #import "DeviceModel.h"
  13. #import "CustomLabel.h"
  14. #import "CustomButton.h"
  15. #import "CustomImageView.h"
  16. #import "CustomTableView.h"
  17. #import "CustomCheckBox.h"
  18. #import "CustomTextView.h"
  19. #import "CustomTextField.h"
  20. #import "UIImageView+WebCache.h"
  21. #import "ValidateUtil.h"
  22. #import "DeviceSelectPopupView.h"
  23. #import "DeviceNodePopupView.h"
  24. #import "TriggerSelectPopupView.h"
  25. #import "ConditionSelectPopupView.h"
  26. #import "RulesConditionHomeModePopupView.h"
  27. #import "RulesConditionViewController.h"
  28. #import "RulesAddViewController.h"
  29. #import "RulesAddCompleteViewController.h"
  30. #import "RulesDetailViewController.h"
  31. #import "RulesViewController.h"
  32. #import "TimePickerPopupView.h"
  33. #import "DaylightPopupView.h"
  34. #import "ExternHeatPopupView.h"
  35. //규칙이름
  36. @implementation RulesAddTitleTableViewCell
  37. #pragma mark - textfield delegate
  38. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  39. return YES;
  40. }
  41. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  42. NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
  43. BOOL input = text.length == 0;
  44. _btnConfirm.hidden = input;
  45. _btnAdd.hidden = !input;
  46. return YES;
  47. }
  48. @end
  49. //알림 메시지
  50. @interface RulesAddTextTableViewCell() <UITextViewDelegate>
  51. @property (nonatomic, strong) void (^heightChangeBlock)(CGFloat height) ;
  52. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *constTxtHeight;
  53. @property CGRect previousRect;
  54. @end
  55. @implementation RulesAddTextTableViewCell
  56. - (void)awakeFromNib {
  57. [super awakeFromNib];
  58. _previousRect = CGRectZero;
  59. _previousRect.origin.y = 11.f;
  60. }
  61. - (void)registHeightChangeBlock:(void (^)(CGFloat height)) heightChangeBlock {
  62. _heightChangeBlock = heightChangeBlock ;
  63. }
  64. - (void)invokeChangeHeight:(CGFloat)height {
  65. if( _heightChangeBlock != nil )
  66. _heightChangeBlock(height) ;
  67. }
  68. #pragma mark - textView delegate
  69. - (void)textViewDidChange:(UITextView *)textView {
  70. UITextPosition* pos = _txtView.endOfDocument;
  71. CGRect currentRect = [_txtView caretRectForPosition:pos];
  72. CGFloat previousY = _previousRect.origin.y;
  73. if (previousY != currentRect.origin.y) {
  74. CGFloat height = currentRect.origin.y - previousY;
  75. _constTxtHeight.constant = _constTxtHeight.constant + height < 48.f ? 48.f : _constTxtHeight.constant + height;
  76. [self invokeChangeHeight:height];
  77. }
  78. _previousRect = currentRect;
  79. }
  80. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
  81. NSString *string = [textView.text stringByReplacingCharactersInRange:range withString:text];
  82. BOOL input = string.length == 0;
  83. _btnConfirm.hidden = input;
  84. _btnAdd.hidden = !input;
  85. return YES;
  86. }
  87. - (void)textViewDidBeginEditing:(UITextView *)textView {
  88. _imgTxtBg.highlighted = YES;
  89. }
  90. - (void)textViewDidEndEditing:(UITextView *)textView {
  91. _imgTxtBg.highlighted = NO;
  92. }
  93. @end
  94. @implementation RulesAddHeaderTableViewCell
  95. @end
  96. @implementation RulesAddTableViewCell
  97. @end
  98. @implementation RulesAddPushTableViewCell
  99. @end
  100. @implementation RulesAddConditionHeaderTableViewCell
  101. @end
  102. @implementation RulesAddConditionTableViewCell
  103. @end
  104. @implementation RulesAddFooterTableViewCell
  105. @end
  106. @interface RulesAddViewController () <KeyboardFrameChangedDelegate> {
  107. NSMutableArray<ItemModel> *_triggerDevices, *_actionDevices, *_conditionDevices;
  108. BOOL _isNotFirstLoading, _hasCondition;
  109. NSMutableArray *_arrayForHeader, *_arrayForFooter;
  110. CGFloat textCellChangeHeight; //알림 메세지 셀 사이즈 변동
  111. CustomTextField *_txtRuleTitle;
  112. CustomTextView *_txvMessage;
  113. CustomButton *_btnTriggerAdd, *_btnPushAdd;
  114. CustomCheckBox *_chkConditions;
  115. RulesConditionHomeModePopupView *_mpopup;
  116. RulesConditionViewController *_rcv;
  117. __weak IBOutlet NSLayoutConstraint *constTableBottom;
  118. }
  119. @property (strong, nonatomic) NSMutableArray<ItemModel> *triggers;
  120. @property (strong, nonatomic) NSMutableArray<ItemModel> *actions;
  121. @property (strong, nonatomic) NSMutableArray<ItemModel> *conditions;
  122. @end
  123. @implementation RulesAddViewController
  124. - (void)viewDidLoad {
  125. [super viewDidLoad];
  126. [self initProperties];
  127. [self initUI];
  128. [self prepareViewDidLoad];
  129. }
  130. - (void)viewWillAppear:(BOOL)animated {
  131. [super viewWillAppear:animated];
  132. [self addObserverKeyboardFrameChanged:self] ;
  133. }
  134. - (void)viewWillDisappear:(BOOL)animated {
  135. [super viewWillDisappear:animated];
  136. [self removeObserverKeyboard] ;
  137. }
  138. #pragma mark - Keyboard Frame Changed Delegate
  139. - (void)keyboardFrameChanged:(CGRect)frame duration:(CGFloat)duration display:(BOOL)display {
  140. NSLog(@"call keyboardFrameChanged!!");
  141. [UIView animateWithDuration:duration animations:^{
  142. if( display ) {
  143. constTableBottom.constant = frame.size.height;
  144. }
  145. else {
  146. constTableBottom.constant = 50.0f;
  147. }
  148. [self.view layoutIfNeeded];
  149. }] ;
  150. }
  151. #pragma mark - init
  152. - (void)initProperties {
  153. _arrayForHeader = [[NSMutableArray alloc] init];
  154. _arrayForFooter = [[NSMutableArray alloc] init];
  155. if (!_triggers) {
  156. _triggers = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
  157. }
  158. if (!_actions) {
  159. _actions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
  160. }
  161. if (!_conditions) {
  162. _conditions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] init];
  163. }
  164. }
  165. - (void)initUI {
  166. [self initTableViewAsDefaultStyle:_tableView];
  167. if (_refRuleDetail) {
  168. _lblTitle.text = @"규칙 편집";
  169. }
  170. }
  171. - (void)prepareViewDidLoad {
  172. [self requestDeviceListForAction:ksItemTypeCodeTrigger];
  173. [self requestDeviceListForAction:ksItemTypeCodeAction];
  174. }
  175. //말줄임표 conv
  176. - (NSString*)convMaxLengthName:(NSString*)name len:(NSInteger)len {
  177. if (name.length > len) {
  178. return [NSString stringWithFormat:@"%@..", [name substringToIndex:len]];
  179. }
  180. return name;
  181. }
  182. #pragma mark - Main Logic
  183. - (void)requestDeviceListForAction:(NSString *)typeCode {
  184. //parameters
  185. // NSDictionary *parameter = @{@"item_type_code": typeCode};
  186. NSArray *arr = @[typeCode];
  187. // NSString *path = [NSString stringWithFormat:API_GET_ITEM_DEVICES, ksItemTypeCodeAction];
  188. NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_ITEM_DEVICES arguments:arr];
  189. [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[ItemListModel class] completion:^(id responseObject) {
  190. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  191. return;
  192. }
  193. ItemListModel *fetchedItemList = (ItemListModel *)responseObject;
  194. if (fetchedItemList && fetchedItemList.list && fetchedItemList.list.count) {//API 성공 ,
  195. if ([typeCode isEqualToString:ksItemTypeCodeAction]) {
  196. _actionDevices = fetchedItemList.list;
  197. if (_refRuleDetail) {//편집일 경우,
  198. ItemModel *actionDevice = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  199. [self matchValueOfDevices:actionDevice devices:_actionDevices];
  200. }
  201. } else {
  202. _triggerDevices = fetchedItemList.list;
  203. _conditionDevices = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] initWithArray:_triggerDevices copyItems:YES];
  204. if (_refRuleDetail) {//편집일 경우,
  205. ItemModel *triggerDevice = [_triggers objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  206. ItemModel *conditionDevice = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  207. [self matchValueOfDevices:triggerDevice devices:_triggerDevices];
  208. [self matchValueOfDevices:conditionDevice devices:_conditionDevices];
  209. }
  210. [self requestDeviceListForAction:ksItemTypeCodeAction];
  211. }
  212. }
  213. } failure:^(id errorObject) {
  214. JDErrorModel *error = (JDErrorModel *)errorObject;
  215. [[JDFacade facade] alert:error.errorMessage];
  216. }];
  217. }
  218. - (void)matchValueOfDevices:(ItemModel *)deviceItem devices:(NSMutableArray<ItemModel> *)devices {
  219. for (ItemSubModel *subItem in deviceItem.subItems) {
  220. NSArray *matchedArray = [devices matchedArrayInSubArrays:@"subItems" predicateFormat:@"sourceId == %@ && sourceSubId == %@", subItem.sourceId, subItem.sourceSubId];
  221. if (matchedArray.count) {
  222. ItemSubModel *matchedSubItem = matchedArray.firstObject;
  223. [[JDFacade facade] setRadioButtonStatus:@YES object:matchedSubItem];
  224. CmdClsValueModel *pCmdClsValue = [matchedSubItem.cmdclsValueList objectKey:@"cmdclsValue" eqaulToString:subItem.cmdclsValue];
  225. [[JDFacade facade] setRadioButtonStatus:@YES object:pCmdClsValue];
  226. }
  227. }
  228. }
  229. - (void)requestRegisterRule {
  230. NSArray *triggers = [self items:_triggers];
  231. NSArray *actions = [self items:_actions];
  232. BOOL hasConditionForRegister = [_conditions matchedArrayInSubArrays:@"subItems" predicateFormat:@"conditionTypeCode == %@", @"09"].count || _chkConditions.checked;
  233. NSArray *conditions = hasConditionForRegister ? [self conditions:_conditions] : nil;
  234. //validate
  235. if (!triggers || !triggers.count) {
  236. [[JDFacade facade] alert:NSLocalizedString(@"실행할 때를 선택하세요", @"실행할 때를 선택하세요")];
  237. return;
  238. }
  239. if (!actions || !actions.count) {
  240. [[JDFacade facade] alert:NSLocalizedString(@"실행할 장치를 선택하세요", @"실행할 장치를 선택하세요")];
  241. return;
  242. }
  243. //parameters
  244. NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"rule_name" : _txtRuleTitle.text,
  245. @"use_yn" : ksYES,
  246. @"triggers": triggers ? triggers : [NSNull null],
  247. @"actions": actions ? actions : [NSNull null]}];
  248. if (conditions) {
  249. [parameter setObject:conditions forKey:@"conditions"];
  250. }
  251. NSString *path = [NSString stringWithFormat:API_POST_RULE];
  252. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[RuleModel class] completion:^(id responseObject) {
  253. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  254. return;
  255. }
  256. RuleModel *newRule = (RuleModel *) responseObject;
  257. if (newRule) {//API 성공 ,
  258. ItemModel *item = _triggers.firstObject;
  259. if (item) {
  260. newRule.ruleName = _txtRuleTitle.text;
  261. newRule.triggerItemSubTypeCode = item.itemSubTypeCode;
  262. }
  263. RulesAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesAddCompleteViewController" storyboardName:@"Rules"];
  264. vc.refRule = newRule;
  265. vc.providesPresentationContextTransitionStyle = YES;
  266. vc.definesPresentationContext = YES;
  267. [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
  268. [self presentViewController:vc animated:YES completion:nil];
  269. }
  270. } failure:^(id errorObject) {
  271. JDErrorModel *error = (JDErrorModel *)errorObject;
  272. [[JDFacade facade] alert:error.errorMessage];
  273. }];
  274. }
  275. - (void)requestModifyRule {
  276. NSArray *triggers = [self items:_triggers];
  277. NSArray *actions = [self items:_actions];
  278. BOOL hasConditionForRegister = [_conditions matchedArrayInSubArrays:@"subItems" predicateFormat:@"conditionTypeCode == %@", @"09"].count || _chkConditions.checked;
  279. NSArray *conditions = hasConditionForRegister ? [self conditions:_conditions] : nil;
  280. //validate
  281. if (!triggers || !triggers.count) {
  282. [[JDFacade facade] alert:NSLocalizedString(@"실행할 때를 선택하세요", @"실행할 때를 선택하세요")];
  283. return;
  284. }
  285. if (!actions || !actions.count) {
  286. [[JDFacade facade] alert:NSLocalizedString(@"실행할 장치를 선택하세요", @"실행할 장치를 선택하세요")];
  287. return;
  288. }
  289. //parameters
  290. NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"rule_name" : _txtRuleTitle.text,
  291. @"use_yn" : ksYES,
  292. @"triggers": triggers ? triggers : [NSNull null],
  293. @"actions": actions ? actions : [NSNull null]}];
  294. if (conditions) {
  295. [parameter setObject:conditions forKey:@"conditions"];
  296. }
  297. NSString *path = [NSString stringWithFormat:API_POST_RULE_MODIFY, _refRuleDetail.homegrpRuleId];
  298. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[RuleModel class] completion:^(id responseObject) {
  299. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  300. return;
  301. }
  302. RuleModel *rule = (RuleModel *) responseObject;
  303. if (rule) {//API 성공
  304. RulesDetailViewController *vc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[RulesDetailViewController class]];
  305. if (vc) {
  306. [vc requestRuleDetail];
  307. } else {
  308. RulesViewController *rvc = [[JDFacade facade] viewControllerOnPresentingViewController:self viewControllerClass:[RulesViewController class]];
  309. [rvc prepareViewDidLoad];
  310. }
  311. [self dismissViewControllerAnimated:YES completion:^{
  312. [[JDFacade facade] toast:@"편집을 완료합니다"];
  313. }];
  314. }
  315. } failure:^(id errorObject) {
  316. JDErrorModel *error = (JDErrorModel *)errorObject;
  317. [[JDFacade facade] alert:error.errorMessage];
  318. }];
  319. }
  320. //아이템 배열을 리턴함.
  321. - (NSArray *)items:(NSArray<ItemModel> *)items {
  322. //triggers, actions, conditions
  323. NSMutableArray *rItems = [[NSMutableArray alloc] init];
  324. for (ItemModel *item in items) {
  325. NSDictionary *dic = nil;
  326. NSMutableArray *subItems = [[NSMutableArray alloc] init];
  327. NSArray *pdevices = [self subItemsForType:item.subItems itemSubType:ksItemSubTypeCodeDevice];
  328. NSArray *pushes = [self subItemsForType:item.pushes itemSubType:ksItemSubTypeCodeAppPush];
  329. NSArray *timers = [self subItemsForType:item.timers itemSubType:ksItemSubTypeCodeTimer];
  330. NSArray *daylights = [self subItemsForType:item.daylights itemSubType:ksItemSubTypeCodeDaylight];
  331. NSArray *heats = [self subItemsForType:item.heats itemSubType:ksItemSubTypeCodeHeat];
  332. if (pdevices && pdevices.count) {//device
  333. [subItems addObjectsFromArray:pdevices];
  334. }
  335. if (pushes && pushes.count) {//push
  336. [subItems addObjectsFromArray:pushes];
  337. }
  338. if (timers && timers.count) {//timer
  339. [subItems addObjectsFromArray:timers];
  340. }
  341. if (daylights && daylights.count) {//해뜰때/질때
  342. [subItems addObjectsFromArray:daylights];
  343. }
  344. if (heats && heats.count) {//더울떄 / 추울때
  345. [subItems addObjectsFromArray:heats];
  346. }
  347. if (subItems.count) {
  348. dic = @{@"item_name": item.itemName,
  349. @"item_sub_type_code": item.itemSubTypeCode,
  350. @"item_sub": subItems};
  351. [rItems addObject:dic];
  352. }
  353. }
  354. return rItems;
  355. }
  356. //서브아이템 배열을 리턴함.
  357. - (NSArray *)subItemsForType:(NSArray *)subItems itemSubType:(NSString *)itemSubTypeCode {
  358. NSMutableArray *rSubItems = [[NSMutableArray alloc] init];
  359. if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
  360. NSArray<ItemSubModel> *pdevices = (NSArray<ItemSubModel> *)[subItems matchedArrayByObjectName:ksCustomRadioButtonStatus condition:YES];
  361. for (ItemSubModel *pdevice in pdevices) {
  362. NSDictionary *rSubItem = @{@"source_id": pdevice.sourceId,
  363. @"source_sub_id": pdevice.sourceSubId,
  364. @"cmdcls_value": pdevice.cmdclsValue,
  365. @"condition_type_code": pdevice.conditionTypeCode,
  366. @"data_type_code": pdevice.dataTypeCode};
  367. [rSubItems addObject:rSubItem];
  368. }
  369. } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
  370. //at once.
  371. for (ItemSubModel *subItem in subItems) {
  372. NSDictionary *rSubItem = @{@"condition_type_code": subItem.conditionTypeCode,
  373. @"cmdcls_value": subItem.cmdclsValue};
  374. [rSubItems addObject:rSubItem];
  375. }
  376. } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  377. for (ItemSubModel *subItem in subItems) {
  378. NSDictionary *rSubItem = @{@"hour": subItem.hour,
  379. @"minute": subItem.minute};
  380. [rSubItems addObject:rSubItem];
  381. }
  382. } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 일 경우,
  383. for (ItemSubModel *subItem in subItems) {
  384. NSDictionary *rSubItem = @{@"source_id": subItem.sourceId,
  385. @"source_sub_id": subItem.sourceSubId};
  386. [rSubItems addObject:rSubItem];
  387. }
  388. } else if ([itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//해뜰때/질때 일 경우,
  389. for (ItemSubModel *subItem in subItems) {
  390. NSDictionary *rSubItem = @{@"source_id": subItem.sourceId,
  391. @"condition_type_code": subItem.conditionTypeCode,
  392. @"cmdcls_value": subItem.cmdclsValue};
  393. [rSubItems addObject:rSubItem];
  394. }
  395. }
  396. return rSubItems;
  397. }
  398. - (NSArray *)conditions:(NSArray<ItemModel> *)items {//trigger만 해당됨.
  399. //conditions
  400. NSMutableArray *rConditions = [[NSMutableArray alloc] init];
  401. for (ItemModel *condition in items) {//item = condition
  402. NSMutableArray *rSubItems = [[NSMutableArray alloc] init];
  403. if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeHomeMode]) {
  404. for (ItemSubModel *mode in condition.subItems) {
  405. NSDictionary *rSubItem = @{@"source_id": mode.sourceId,
  406. @"cmdcls_value": mode.cmdclsValue,
  407. @"condition_type_code": mode.conditionTypeCode};
  408. [rSubItems addObject:rSubItem];
  409. }
  410. } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueDate]) {
  411. for (ItemSubModel *subItem in condition.subItems) {
  412. NSDictionary *rSubItem = @{@"cmdcls_value": subItem.cmdclsValue,
  413. @"condition_type_code": subItem.conditionTypeCode};
  414. [rSubItems addObject:rSubItem];
  415. }
  416. } else if ([condition.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
  417. for (ItemSubModel *pdevice in condition.subItems) {
  418. NSDictionary *rSubItem = @{@"source_id": pdevice.sourceId,
  419. @"source_sub_id": pdevice.sourceSubId,
  420. @"cmdcls_value": pdevice.cmdclsValue,
  421. @"data_type_code": pdevice.dataTypeCode,
  422. @"condition_type_code": pdevice.conditionTypeCode};
  423. [rSubItems addObject:rSubItem];
  424. }
  425. } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDaysOfWeek]) {
  426. for (ItemSubModel *subItem in condition.subItems) {
  427. NSDictionary *rSubItem = @{@"cmdcls_value": subItem.cmdclsValue,
  428. @"condition_type_code": subItem.conditionTypeCode};
  429. [rSubItems addObject:rSubItem];
  430. }
  431. }
  432. if (rSubItems.count) {
  433. NSDictionary *dic = @{@"item_name": condition.itemName,
  434. @"item_sub_type_code": condition.itemSubTypeCode,
  435. @"item_sub": rSubItems};
  436. [rConditions addObject:dic];
  437. }
  438. }
  439. return rConditions;
  440. }
  441. - (void)cloneSubItemsForItemSubType:(NSArray<ItemModel> *)items {
  442. for (ItemModel *item in items) {
  443. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
  444. //기존 아이템을 그대로 사용함.
  445. for (ItemSubModel *subItem in item.subItems) {
  446. [[JDFacade facade] setRadioButtonStatus:@YES object:subItem];
  447. [[JDFacade facade] setCheckBoxStatus:@YES object:subItem];
  448. }
  449. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeAppPush]) {//푸시일 경우,
  450. item.pushes = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
  451. item.subItems = nil;
  452. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  453. item.timers = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
  454. item.subItems = nil;
  455. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
  456. item.daylights = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
  457. item.subItems = nil;
  458. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
  459. item.heats = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:item.subItems copyItems:YES];
  460. item.subItems = nil;
  461. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//더울때/추울때 경우,
  462. //기존 아이템을 그대로 사용함.
  463. }
  464. }
  465. }
  466. - (void)setRefRuleDetail:(RuleDetailModel *)refRuleDetail {
  467. _refRuleDetail = refRuleDetail;
  468. _triggers = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.triggers copyItems:YES];
  469. _actions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.actions copyItems:YES];
  470. _conditions = (NSMutableArray<ItemModel> *)[[NSMutableArray alloc] initWithArray:_refRuleDetail.conditions copyItems:YES];
  471. [self cloneSubItemsForItemSubType:_triggers];
  472. [self cloneSubItemsForItemSubType:_actions];
  473. [self cloneSubItemsForItemSubType:_conditions];
  474. _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
  475. _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDueDate] ? YES : _hasCondition;
  476. _hasCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice] ? YES : _hasCondition;
  477. }
  478. #pragma mark - UITableView DataSource & Delegate
  479. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  480. return 5;
  481. }
  482. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  483. NSInteger count = 0;
  484. if (section == 0) {//title
  485. count = 1;
  486. } else if (section == 1) {//triggers
  487. count = _triggers && _triggers.count ? _triggers.count : 0;
  488. } else if (section == 2) {//actions
  489. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  490. count = deviceItem.subItems && deviceItem.subItems.count ? deviceItem.subItems.count : 0;
  491. } else if (section == 3) {//push-message
  492. count = 1;
  493. } else if (section == 4) {//conditions
  494. count = _chkConditions.checked || _hasCondition ? 1 : 0;
  495. }
  496. return count;
  497. }
  498. - (NSString *)headerTitleForSection:(NSInteger)section {
  499. NSString *title = nil;
  500. if (section == 1) {//trigger
  501. title = @"실행 조건";
  502. if (_triggers && _triggers.count) {
  503. ItemModel *item = _triggers[0];
  504. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
  505. title = @"장치 상태가 바뀔 때";
  506. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {
  507. title = @"이 시간마다";
  508. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {
  509. title = @"더울때 / 추울때";
  510. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {
  511. title = @"해뜰때 / 질때";
  512. }
  513. }
  514. } else if (section == 2) {//action
  515. title = @"동작할 장치";
  516. // title = _actions && _actions.count ? @"선택됨" : title;
  517. }
  518. // else if (section == 3) {//conditions
  519. // title = @"추가 조건";
  520. // title = _triggers && triggers.count ? @"선택됨" : title;
  521. // }
  522. return title;
  523. }
  524. - (void)addTargetToHeaderAddButton:(CustomButton *)btnAdd section:(NSInteger)section {
  525. NSLog(@"section : %ld", section) ;
  526. if (section == 1) {
  527. _btnTriggerAdd = btnAdd;
  528. [btnAdd addTarget:self action:@selector(btnAddTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
  529. } else if (section == 2) {
  530. [btnAdd addTarget:self action:@selector(btnAddActionTouched:) forControlEvents:UIControlEventTouchUpInside];
  531. }
  532. }
  533. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  534. UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
  535. if (!view) {
  536. if (section == 0 || section == 3) {//title
  537. view = [[UIView alloc] init];
  538. } else if (section == 1 || section == 2) {//hide add button or not;
  539. RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
  540. hcell.width = IPHONE_WIDTH;
  541. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  542. [view addSubview:hcell];
  543. hcell.lblTitle.text = [self headerTitleForSection:section];
  544. hcell.imgBg.hidden = section % 2 == 0;
  545. if (![hcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  546. [self addTargetToHeaderAddButton:hcell.btnAdd section:section];
  547. }
  548. } else if (section == 4) {//conditions
  549. RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ConditionHeaderCellIdentifier"];
  550. hcell.width = IPHONE_WIDTH;
  551. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  552. [view addSubview:hcell];
  553. _chkConditions = hcell.chkConditions;
  554. if (!_isNotFirstLoading) {
  555. _chkConditions.checked = _hasCondition;
  556. _isNotFirstLoading = YES;
  557. }
  558. if (![_chkConditions actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  559. [_chkConditions addTarget:self action:@selector(chkConditionsTouched:) forControlEvents:UIControlEventTouchUpInside];
  560. }
  561. if (![hcell.btnConditions actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  562. [hcell.btnConditions addTarget:self action:@selector(btnConditionsTouched:) forControlEvents:UIControlEventTouchUpInside];
  563. }
  564. }
  565. if (_arrayForHeader.count == section) {
  566. [_arrayForHeader insertObject:view atIndex:section];
  567. }
  568. } else {
  569. if (section == 1 || section == 2) {
  570. RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)view.subviews[0];
  571. hcell.lblTitle.text = hcell.lblTitle.text = [self headerTitleForSection:section];
  572. } else if (section == 4) {
  573. // RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)view.subviews[0];
  574. }
  575. }
  576. [self checkHeaderButton:section];
  577. return view;
  578. }
  579. - (void)checkHeaderButton:(NSInteger)section {
  580. if (section == 1) {
  581. _btnTriggerAdd.hidden = self.triggers.count > 0;
  582. }
  583. }
  584. - (void)chkConditionsTouched:(id)sender {
  585. [_tableView reloadData];
  586. CustomCheckBox *chkCondition = (CustomCheckBox *)sender;
  587. if (chkCondition.checked) {
  588. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:4];
  589. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
  590. }
  591. }
  592. - (void)btnConditionsTouched:(id)sender {
  593. ConditionSelectPopupView *popup = [[ConditionSelectPopupView alloc] initFromNib];
  594. [popup show];
  595. };
  596. - (void)btnAddModeTouched:(id)sender {
  597. ItemModel *mode = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
  598. BOOL isNewTrigger = mode == nil;
  599. mode = isNewTrigger ? [[ItemModel alloc] init] : mode;
  600. if (!_mpopup) {
  601. _mpopup = [[RulesConditionHomeModePopupView alloc] initFromNib];
  602. }
  603. _mpopup.condition = mode;
  604. [_mpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  605. if (buttonIndex == 0) {//OK
  606. if (isNewTrigger) {
  607. [_conditions addObject:mode];
  608. }
  609. [self.tableView reloadData];
  610. }
  611. }];
  612. }
  613. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  614. if (section == 0 || section == 3) {
  615. return 0.01f;
  616. }
  617. else if (section == 4) {
  618. return 56.0f;
  619. }
  620. return 56.0f;
  621. }
  622. - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
  623. UIView *view = _arrayForFooter.count > section ? _arrayForFooter[section] : nil;
  624. if (!view) {
  625. RulesAddFooterTableViewCell *hcell = (RulesAddFooterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FooterCellIdentifier"];
  626. hcell.width = IPHONE_WIDTH;
  627. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  628. [view addSubview:hcell];
  629. if (_arrayForHeader.count == section) {
  630. [_arrayForHeader insertObject:view atIndex:section];
  631. }
  632. }
  633. return view;
  634. }
  635. - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  636. // if (section == 0) {
  637. // return 0.01f;
  638. // }
  639. return 0.01f;
  640. }
  641. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  642. CGFloat height = 0.0f;
  643. NSInteger section = indexPath.section;
  644. if (section == 0) {//title
  645. height = 122;
  646. } else if (section == 1) {//triggers
  647. height = 80;
  648. } else if (section == 2) {//actions
  649. height = 80;
  650. } else if (section == 3) {//push-message
  651. // height = UITableViewAutomaticDimension;
  652. height = 122 + textCellChangeHeight;
  653. } else if (section == 4) {//conditions
  654. if (!_rcv) {
  655. _rcv = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesConditionViewController" storyboardName:@"Rules"];
  656. [self addChildViewController:_rcv];
  657. [_rcv didMoveToParentViewController:self];
  658. }
  659. height = _rcv.tableHeight;
  660. }
  661. return height;
  662. }
  663. + (BOOL)hasDeleteNode:(ItemModel *)deviceItem {
  664. NSArray *matchedArray = [deviceItem.subItems filteredArrayUsingPredicateFormat:@"deleteYn == %@", ksYES];
  665. return matchedArray.count;
  666. }
  667. - (void)configureTriggerCell:(RulesAddTableViewCell *)cell item:(ItemModel *)item {
  668. ItemSubModel *subItem = nil;
  669. NSString *deviceImageFileName = nil;
  670. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
  671. subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  672. cell.lblItem.text = subItem.sourceName;
  673. deviceImageFileName = subItem.imageFileName;
  674. if ([subItem.deleteYn boolValue]) {
  675. [cell.lblItem setStrikethrough:cell.lblItem.text];
  676. }
  677. cell.lblSubItem.text = subItem.sourceSubName;
  678. //노드의 액션 값을 세팅함.
  679. if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
  680. CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  681. cell.lblCondition.text = [DeviceModel contentValueMsgByCmdClsCode:subItem.cmdclsCode cmdclsTypeId:(NSString *)subItem.cmdclsTypeId contentValue:cmdclsValue.cmdclsValue];
  682. } else {
  683. if (subItem.cmdclsValueMsg) {
  684. cell.lblCondition.text = subItem.cmdclsValueMsg;
  685. } else {
  686. NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
  687. cell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
  688. }
  689. }
  690. //[cell.lblCondition setUnderLine:cell.lblCondition.text];
  691. cell.lblCondition.hidden = NO;
  692. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {
  693. subItem = item.timers && item.timers.count ? item.timers[0] : nil;
  694. if (subItem) {
  695. NSInteger phour = [subItem.hour integerValue];
  696. NSString *period = phour < 12 ? @"AM" : @"PM";//NSLocalizedString(@"오전", @"오전") : NSLocalizedString(@"오후", @"오후");
  697. if ([period isEqualToString:NSLocalizedString(@"오후", @"오후")]) {
  698. if (phour > 12) {
  699. phour -= 12;
  700. }
  701. }
  702. NSString *title = [NSString stringWithFormat:@"%@ %zd:%@", period, phour, subItem.minute];
  703. // NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
  704. cell.lblItem.text = title;
  705. cell.lblSubItem.text = [self daysOfWeekAtSubItem];
  706. cell.lblCondition.hidden = YES;
  707. }
  708. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {
  709. subItem = item.daylights && item.daylights.count ? item.daylights[0] : nil;
  710. if (subItem) {
  711. NSString *title = [subItem.sourceSubId isEqualToString:@"sunriseUtcTime"] ? @"해뜰때" : @"해질때";
  712. cell.lblItem.text = title;
  713. cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@", subItem.sourceName, [self daysOfWeekAtSubItem]];
  714. cell.lblCondition.hidden = YES;
  715. }
  716. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {
  717. subItem = item.heats && item.heats.count ? item.heats[0] : nil;
  718. if (subItem) {
  719. NSString *title = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"더울때" : @"추울때";
  720. cell.lblItem.text = title;
  721. cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@℃ / %@", subItem.sourceName, subItem.cmdclsValue, [self daysOfWeekAtSubItem]];
  722. cell.lblCondition.hidden = YES;
  723. }
  724. }
  725. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
  726. if (item.imageFileName) {
  727. [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:item.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  728. } else {
  729. [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:deviceImageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  730. }
  731. } else {
  732. cell.imgvIcon.image = [self imageForTrigger:item];
  733. }
  734. }
  735. - (NSString *)daysOfWeekAtSubItem {
  736. NSString *daysOfWeek = ksEmptyString;
  737. ItemModel *daysCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDaysOfWeek];
  738. if (daysCondition) {
  739. ItemSubModel *subCondition = daysCondition.subItems[0];
  740. daysOfWeek = subCondition.daysOfWeek;
  741. }
  742. return daysOfWeek;
  743. }
  744. - (UIImage *)imageForTrigger:(ItemModel *)item {
  745. UIImage *image = nil;
  746. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  747. image = [UIImage imageNamed:@"img_rule_trigger_icon_time"];
  748. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
  749. image = [UIImage imageNamed:@"img_rule_trigger_icon_sunset"];
  750. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
  751. image = [UIImage imageNamed:@"img_rule_trigger_icon_temperature"];
  752. }
  753. return image;
  754. }
  755. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  756. NSInteger section = indexPath.section;
  757. UITableViewCell *cell = nil;
  758. if (section == 0) {//title
  759. RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
  760. tcell.txtRuleTitle.text = [tcell.txtRuleTitle.text isEmptyString] && _refRuleDetail ? _refRuleDetail.ruleName : tcell.txtRuleTitle.text;
  761. if (!_txtRuleTitle) {
  762. _txtRuleTitle = tcell.txtRuleTitle;
  763. }
  764. [self insertActionAddButton:tcell.btnAdd];
  765. cell = tcell;
  766. } else if (section == 1) {//triggers
  767. ItemModel *item = _triggers[indexPath.row];
  768. RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
  769. [self configureTriggerCell:tcell item:item];
  770. tcell.lblItem.textColor = kUITextColor04;
  771. tcell.btnDelete.value = item;
  772. if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  773. [tcell.btnDelete addTarget:self action:@selector(btnDeleteTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
  774. }
  775. cell = tcell;
  776. } else if (section == 2) {//actions
  777. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  778. ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
  779. RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
  780. //title
  781. BOOL multiHub = [JDFacade facade].loginUser.isMultiHomeHub;
  782. NSArray *ids = [subItem.sourceId componentsSeparatedByString:@"-"];
  783. DeviceModel *hub = nil;
  784. if (ids.count > 1) hub = [[JDFacade facade].loginUser getHomeHub:[ids objectAtIndex:0]];
  785. NSString *name = hub == nil ? @"전체" : (hub.prdUserName != nil ? hub.prdUserName : hub.prdName);
  786. NSString *hubName = multiHub ? [self convMaxLengthName:name len:4] : @"";
  787. NSString *deviceName = [self convMaxLengthName:subItem.sourceName len:6];
  788. tcell.lblItem.text = multiHub ? [NSString stringWithFormat:@"[%@]%@", hubName,deviceName] : deviceName ;
  789. if ([subItem.deleteYn boolValue]) {
  790. [tcell.lblItem setStrikethrough:tcell.lblItem.text];
  791. }
  792. tcell.lblSubItem.text = subItem.sourceSubName;
  793. // tcell.lblItem.textColor = kUITextColor01;
  794. [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:subItem.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  795. //노드의 액션 값을 세팅함.
  796. if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
  797. CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  798. tcell.lblCondition.text = cmdclsValue.cmdclsValueMsg;
  799. }
  800. else {
  801. if (subItem.cmdclsValueMsg) {
  802. tcell.lblCondition.text = subItem.cmdclsValueMsg;
  803. }
  804. else {
  805. NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
  806. tcell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
  807. }
  808. }
  809. NSLog(@"tcell.lblCondition.text : %@", tcell.lblCondition.text);
  810. //[tcell.lblCondition setUnderLine:tcell.lblCondition.text];
  811. tcell.btnDelete.value = subItem;
  812. if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  813. [tcell.btnDelete addTarget:self action:@selector(btnDeleteDeviceActionTouched:) forControlEvents:UIControlEventTouchUpInside];
  814. }
  815. cell = tcell;
  816. } else if (section == 3) {//push-message
  817. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  818. ItemSubModel *subItem = pushItem.pushes[indexPath.row];
  819. RulesAddTextTableViewCell *tcell = (RulesAddTextTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"TextCellIdentifier"];
  820. //높이변경
  821. [tcell registHeightChangeBlock:^(CGFloat height) {
  822. textCellChangeHeight += height;
  823. [self tableView:_tableView reloadRowWhileShowingKeyboard:indexPath];
  824. }];
  825. if (!_txvMessage) {
  826. _txvMessage = tcell.txtView;
  827. }
  828. _txvMessage.text = [_txvMessage.text isEqualToString:_txvMessage.placeHolder] && _refRuleDetail ? subItem.cmdclsValue : _txvMessage.text;
  829. [self insertActionAddButton:tcell.btnAdd];
  830. cell = tcell;
  831. } else if (section == 4) {//conditions
  832. RulesAddConditionTableViewCell *tcell = (RulesAddConditionTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];
  833. if (_chkConditions.checked) {
  834. if (!tcell.container.subviews.count) {
  835. if ([self isViewLoaded]) {
  836. [_rcv beginAppearanceTransition:YES animated:NO];
  837. [tcell.container addSubview:_rcv.view];
  838. [_rcv endAppearanceTransition];
  839. }
  840. }
  841. _rcv.conditions = _conditions;
  842. _rcv.refDevices = _conditionDevices;
  843. tcell.constraintContainerHeight.constant = _rcv.tableHeight;
  844. }
  845. cell = tcell;
  846. }
  847. return cell;
  848. }
  849. //키보드 유지 셀 높이 변경
  850. - (void)tableView:(UITableView *)tableView reloadRowWhileShowingKeyboard:(NSIndexPath *)indexPath {
  851. [tableView beginUpdates];
  852. [tableView endUpdates];
  853. [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  854. }
  855. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  856. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  857. if (indexPath.section == 1) {//triggers
  858. ItemModel *item = _triggers[0];
  859. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
  860. ItemSubModel *subItem = item.subItems[indexPath.row];
  861. [RulesAddViewController modifyTrigger:item subItem:subItem refDevices:_triggerDevices tableView:_tableView];
  862. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  863. [self modifyTriggerOfTimer:item];
  864. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
  865. [self modifyTriggerOfDaylight:item];
  866. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
  867. [self modifyTriggerOfHeat:item];
  868. }
  869. } else if (indexPath.section == 2) {//actions
  870. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  871. if (deviceItem) {
  872. ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
  873. [RulesAddViewController modifyAction:subItem refDevices:_actionDevices tableView:_tableView];
  874. }
  875. }
  876. }
  877. #pragma mark
  878. - (void)modifyTriggerOfTimer:(ItemModel *)item {
  879. TimePickerPopupView *tpopup = [[TimePickerPopupView alloc] initFromNib];
  880. tpopup.timeTrigger = item;
  881. tpopup.refConditions = _conditions;
  882. [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  883. if (buttonIndex == 0) {//OK
  884. [_tableView reloadData];
  885. }
  886. }];
  887. }
  888. - (void)modifyTriggerOfDaylight:(ItemModel *)item {
  889. DaylightPopupView *dpopup = [[DaylightPopupView alloc] initFromNib];
  890. dpopup.daylightTrigger = item;
  891. dpopup.refConditions = _conditions;
  892. [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  893. if (buttonIndex == 0) {//OK
  894. [_tableView reloadData];
  895. }
  896. }];
  897. }
  898. - (void)modifyTriggerOfHeat:(ItemModel *)item {
  899. ExternHeatPopupView *epopup = [[ExternHeatPopupView alloc] initFromNib];
  900. epopup.externHeatTrigger = item;
  901. epopup.refConditions = _conditions;
  902. [epopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  903. if (buttonIndex == 0) {//OK
  904. [_tableView reloadData];
  905. }
  906. }];
  907. }
  908. + (void)modifyTrigger:(ItemModel *)trigger subItem:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
  909. if ([subItem.deleteYn boolValue]) {
  910. [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
  911. return;
  912. }
  913. ItemModel *deviceItem = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
  914. //노드 선택 팝럽.
  915. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  916. npopup.refDevice = deviceItem;
  917. npopup.typeCode = ksItemTypeCodeTrigger;
  918. npopup.isModifyMode = YES;
  919. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  920. if (buttonIndex == 0) {//OK
  921. [trigger.subItems removeAllObjects];
  922. ItemSubModel *fsubItem = [deviceItem.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  923. [trigger.subItems addObject:fsubItem];
  924. // subItem.cmdclsCode = matchedSubItem.cmdclsCode;
  925. // subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
  926. //
  927. // if (matchedSubItem.cmdclsValueList) {
  928. // subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
  929. //
  930. // CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  931. // subItem.cmdclsValue = pCmdClsValue.cmdclsValue; //CommandClassControlNodeView - 에서 선택됨.
  932. // }
  933. if (tableView) {
  934. [tableView reloadData];
  935. }
  936. }
  937. }];
  938. }
  939. + (void)modifyAction:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
  940. if ([subItem.deleteYn boolValue]) {
  941. [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
  942. return;
  943. }
  944. ItemModel *item = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
  945. ItemSubModel *matchedSubItem = [item.subItems objectKey:@"sourceSubId" eqaulToString:subItem.sourceSubId];
  946. //노드 선택 팝럽.
  947. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  948. npopup.refDevice = item;
  949. npopup.typeCode = ksItemTypeCodeTrigger;
  950. npopup.isModifyMode = YES;
  951. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  952. if (buttonIndex == 0) {//OK
  953. subItem.cmdclsCode = matchedSubItem.cmdclsCode;
  954. subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
  955. subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
  956. CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  957. subItem.cmdclsValue = pCmdClsValue.cmdclsValue; //CommandClassControlNodeView - 에서 선택됨.
  958. if (tableView) {
  959. [tableView reloadData];
  960. }
  961. }
  962. }];
  963. }
  964. #pragma mark - TableView UI Events
  965. - (void)btnAddTriggerTouched:(id)sender {
  966. TriggerSelectPopupView *tpopup = [[TriggerSelectPopupView alloc] initFromNib];
  967. tpopup.refTriggers = _triggers;
  968. tpopup.refDevices = _triggerDevices;
  969. tpopup.refConditions = _conditions;
  970. [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  971. if (buttonIndex == 0) {
  972. [_tableView reloadData];
  973. }
  974. }];
  975. }
  976. - (void)btnAddActionTouched:(id)sender {
  977. NSLog(@"_actionDevices : %@", _actionDevices);
  978. DeviceSelectPopupView *dpopup = [[DeviceSelectPopupView alloc] initFromNib];
  979. dpopup.refDevices = _actionDevices;
  980. dpopup.typeCode = ksItemTypeCodeTrigger;
  981. [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  982. if (buttonIndex == 0) {//ok
  983. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  984. npopup.refDevice = dpopup.selectedDevices[0];
  985. npopup.typeCode = ksItemTypeCodeTrigger;
  986. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  987. //action add
  988. if (buttonIndex == 0) {//OK
  989. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  990. if (!deviceItem) {//디바이스 아이템이 없을 경우,
  991. deviceItem = [[ItemModel alloc] init];
  992. deviceItem.itemName = @"이 장치를 실행";
  993. deviceItem.itemSubTypeCode = ksItemSubTypeCodeDevice;
  994. deviceItem.subItems = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
  995. [_actions addObject:deviceItem];
  996. }
  997. ItemSubModel *snode = npopup.selectedNode;
  998. //존재 여부 확인
  999. if (![deviceItem.subItems objectByUsingPredicateFormat:@"sourceId == %@ && sourceSubId == %@", snode.sourceId, snode.sourceSubId]) {
  1000. [deviceItem.subItems addObject: snode];
  1001. }
  1002. [_tableView reloadData];
  1003. }
  1004. }];
  1005. }
  1006. }];
  1007. }
  1008. - (void)btnAddPushMessageTouched:(id)sender {
  1009. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  1010. if (!pushItem) {//디바이스 아이템이 없을 경우,
  1011. pushItem = [[ItemModel alloc] init];
  1012. pushItem.itemName = [JDFacade facade].loginUser.memberId;
  1013. pushItem.itemSubTypeCode = ksItemSubTypeCodeAppPush;
  1014. pushItem.pushes = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
  1015. ItemSubModel *push = [[ItemSubModel alloc] init];
  1016. push.conditionTypeCode = @"02";
  1017. [pushItem.pushes addObject:push];
  1018. [_actions addObject:pushItem];
  1019. }
  1020. [_tableView reloadData];
  1021. }
  1022. - (void)btnDeleteTriggerTouched:(id)sender {
  1023. CustomButton *btnDelete = (CustomButton *)sender;
  1024. ItemModel *item = btnDelete.value;
  1025. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
  1026. ItemSubModel *subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  1027. if (subItem) {
  1028. [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
  1029. for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
  1030. [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
  1031. cmdclsValue.isSelected = NO;
  1032. }
  1033. }
  1034. }
  1035. if (_triggers && _triggers.count) {
  1036. [_triggers removeAllObjects];
  1037. }
  1038. [_tableView reloadData];
  1039. }
  1040. - (void)btnDeleteDeviceActionTouched:(id)sender {
  1041. CustomButton *btnDelete = (CustomButton *)sender;
  1042. ItemSubModel *subItem = (ItemSubModel *)btnDelete.value;
  1043. //선택 설정을 초기화
  1044. [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
  1045. for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
  1046. [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
  1047. cmdclsValue.isSelected = NO;
  1048. }
  1049. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  1050. [deviceItem.subItems removeObject:subItem];
  1051. [_tableView reloadData];
  1052. }
  1053. - (void)btnDeletePushActionTouched:(id)sender {
  1054. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  1055. [_actions removeObject:pushItem];
  1056. [_tableView reloadData];
  1057. }
  1058. - (void)btnAddTouched:(id)sender {
  1059. UIButton *btn = sender;
  1060. //1001:규칙add, 2001:알림add
  1061. UIControl *control;
  1062. if ([btn tag] > 2000) {
  1063. control = [self.view viewWithTag:2000];
  1064. }
  1065. else {
  1066. control = [self.view viewWithTag:1000];
  1067. }
  1068. [control becomeFirstResponder];
  1069. }
  1070. //- (void)btnInputConfirmTouched:(id)sender {
  1071. //
  1072. // UIButton *btn = sender;
  1073. //
  1074. // //1002:규칙add, 2002:알림add
  1075. // if ([btn tag] > 2000) {
  1076. //
  1077. //
  1078. // }
  1079. // else {
  1080. //
  1081. // }
  1082. //
  1083. //}
  1084. - (void)insertActionAddButton:(UIButton*)button {
  1085. if (![button actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  1086. [button addTarget:self action:@selector(btnAddTouched:) forControlEvents:UIControlEventTouchUpInside];
  1087. }
  1088. }
  1089. //- (void)insertActionInputConfirmButton:(UIButton*)button {
  1090. //
  1091. // if (![button actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  1092. // [button addTarget:self action:@selector(btnInputConfirmTouched:) forControlEvents:UIControlEventTouchUpInside];
  1093. // }
  1094. //}
  1095. - (IBAction)btnCancelTouched:(id)sender {
  1096. [self dismissViewControllerAnimated:YES completion:nil];
  1097. }
  1098. #pragma mark - UI Events
  1099. - (IBAction)btnConfirmTouched:(id)sender {
  1100. [self.view endEditing:YES];
  1101. //1.Validate Title
  1102. RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; //타이틀 섹션
  1103. if (tcell && ![ValidateUtil validateTextfiled:tcell.txtRuleTitle type:ValidateTypeNull title:NSLocalizedString(@"규칙 이름", @"규칙 이름")]) {
  1104. return;
  1105. }
  1106. if (tcell.txtRuleTitle.text.length > 40) {
  1107. [[JDFacade facade] alert:@"규칙이름은 최대 40자까지 입력할 수 있습니다"];
  1108. return;
  1109. }
  1110. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  1111. if (pushItem) {
  1112. if (_txvMessage && [_txvMessage.text isEmptyString]) {//푸시메시지 여부 확인
  1113. [_actions removeObject:pushItem];
  1114. } else if (_txvMessage) {
  1115. ItemSubModel *subItem = pushItem.pushes[0];
  1116. subItem.cmdclsValue = _txvMessage.text;
  1117. if (_txvMessage.text.length > 120) {
  1118. [[JDFacade facade] alert:@"알림메시지는 최대 120자까지 입력할 수 있습니다"];
  1119. return;
  1120. }
  1121. }
  1122. }
  1123. if (!_refRuleDetail) {//생성
  1124. [self requestRegisterRule];
  1125. } else {//수정
  1126. BOOL hasDeleteNode = NO;
  1127. ItemModel *triggerDevice = [_triggers objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  1128. ItemModel *actionDevice = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  1129. ItemModel *conditionDevice = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  1130. hasDeleteNode = [RulesAddViewController hasDeleteNode:triggerDevice];
  1131. hasDeleteNode = [RulesAddViewController hasDeleteNode:actionDevice] ? YES : hasDeleteNode;
  1132. hasDeleteNode = [RulesAddViewController hasDeleteNode:conditionDevice] ? YES : hasDeleteNode;
  1133. if (hasDeleteNode) {
  1134. [[JDFacade facade] confirm:@"삭제된 장치를 제외 후 저장합니다" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  1135. if (buttonIndex == 0) {//OK
  1136. [self getRidOfDeleteDevices:triggerDevice];
  1137. [self getRidOfDeleteDevices:actionDevice];
  1138. [self getRidOfDeleteDevices:conditionDevice];
  1139. [_tableView reloadData];
  1140. [self requestModifyRule];
  1141. }
  1142. }];
  1143. } else {
  1144. [self requestModifyRule];
  1145. }
  1146. }
  1147. }
  1148. //삭제된 장치를 제거함.
  1149. - (void)getRidOfDeleteDevices:(ItemModel *)deviceItem {
  1150. [deviceItem.subItems enumerateObjectsUsingBlock:^(ItemSubModel *subItem, NSUInteger idx, BOOL * _Nonnull stop) {
  1151. if (subItem.deleteYn) {
  1152. if ([_triggers containsObject:deviceItem]) {
  1153. [_triggers removeObject:deviceItem];
  1154. return;
  1155. }
  1156. [deviceItem.subItems removeObject:subItem];
  1157. }
  1158. }];
  1159. }
  1160. #pragma mark - MemoryWarning
  1161. - (void)didReceiveMemoryWarning
  1162. {
  1163. [super didReceiveMemoryWarning];
  1164. // Dispose of any resources that can be recreated.
  1165. }
  1166. @end