RulesAddViewController.m 55 KB

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