RulesAddViewController.m 58 KB

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