RulesAddViewController.m 60 KB

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