RulesAddViewController.m 54 KB

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