RulesAddViewController.m 72 KB

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