RulesAddViewController.m 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  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. NSLog(@"section : %ld", section) ;
  440. if (section == 1) {
  441. _btnTriggerAdd = btnAdd;
  442. [btnAdd addTarget:self action:@selector(btnAddTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
  443. } else if (section == 2) {
  444. [btnAdd addTarget:self action:@selector(btnAddActionTouched:) forControlEvents:UIControlEventTouchUpInside];
  445. } else if (section == 3) {
  446. _btnPushAdd = btnAdd;
  447. [btnAdd addTarget:self action:@selector(btnAddPushMessageTouched:) forControlEvents:UIControlEventTouchUpInside];
  448. }
  449. }
  450. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  451. UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
  452. NSLog(@"view : %@, section : %ld", view, section) ;
  453. if (!view) {
  454. if (section == 0) {//title
  455. view = [[UIView alloc] init];
  456. } else if (section == 1 || section == 2 || section == 3) {//hide add button or not;
  457. RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
  458. hcell.width = IPHONE_WIDTH;
  459. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  460. [view addSubview:hcell];
  461. hcell.lblTitle.text = [self headerTitleForSection:section];
  462. if (![hcell.btnAdd actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  463. [self addTargetToHeaderAddButton:hcell.btnAdd section:section];
  464. }
  465. } else if (section == 4) {//conditions
  466. RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ConditionHeaderCellIdentifier"];
  467. hcell.width = IPHONE_WIDTH;
  468. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  469. [view addSubview:hcell];
  470. _chkConditions = hcell.chkConditions;
  471. if (!_isNotFirstLoading) {
  472. _chkConditions.checked = _hasCondition;
  473. _isNotFirstLoading = YES;
  474. }
  475. if (![_chkConditions actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  476. [_chkConditions addTarget:self action:@selector(chkConditionsTouched:) forControlEvents:UIControlEventTouchUpInside];
  477. }
  478. if (![hcell.btnConditions actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  479. [hcell.btnConditions addTarget:self action:@selector(btnConditionsTouched:) forControlEvents:UIControlEventTouchUpInside];
  480. }
  481. }
  482. if (_arrayForHeader.count == section) {
  483. [_arrayForHeader insertObject:view atIndex:section];
  484. }
  485. } else {
  486. if (section == 1 || section == 2 || section == 3) {
  487. RulesAddHeaderTableViewCell *hcell = (RulesAddHeaderTableViewCell *)view.subviews[0];
  488. hcell.lblTitle.text = hcell.lblTitle.text = [self headerTitleForSection:section];
  489. } else if (section == 4) {
  490. // RulesAddConditionHeaderTableViewCell *hcell = (RulesAddConditionHeaderTableViewCell *)view.subviews[0];
  491. }
  492. }
  493. [self checkHeaderButton:section];
  494. return view;
  495. }
  496. - (void)checkHeaderButton:(NSInteger)section {
  497. if (section == 1) {
  498. _btnTriggerAdd.hidden = self.triggers.count > 0;
  499. } else if (section == 3) {
  500. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  501. NSInteger pcount = pushItem.pushes && pushItem.pushes.count ? pushItem.pushes.count : 0;
  502. _btnPushAdd.hidden = pcount > 0;
  503. }
  504. }
  505. - (void)chkConditionsTouched:(id)sender {
  506. [_tableView reloadData];
  507. CustomCheckBox *chkCondition = (CustomCheckBox *)sender;
  508. if (chkCondition.checked) {
  509. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:4];
  510. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
  511. }
  512. }
  513. - (void)btnConditionsTouched:(id)sender {
  514. ConditionSelectPopupView *popup = [[ConditionSelectPopupView alloc] initFromNib];
  515. [popup show];
  516. };
  517. - (void)btnAddModeTouched:(id)sender {
  518. ItemModel *mode = (ItemModel *)[_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeHomeMode];
  519. BOOL isNewTrigger = mode == nil;
  520. mode = isNewTrigger ? [[ItemModel alloc] init] : mode;
  521. if (!_mpopup) {
  522. _mpopup = [[RulesConditionHomeModePopupView alloc] initFromNib];
  523. }
  524. _mpopup.condition = mode;
  525. [_mpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  526. if (buttonIndex == 0) {//OK
  527. if (isNewTrigger) {
  528. [_conditions addObject:mode];
  529. }
  530. [self.tableView reloadData];
  531. }
  532. }];
  533. }
  534. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  535. if (section == 0) {
  536. return 0.01f;
  537. } else if (section == 4) {
  538. return 56.0f;
  539. }
  540. return 56.0f;
  541. }
  542. - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
  543. UIView *view = _arrayForFooter.count > section ? _arrayForFooter[section] : nil;
  544. if (!view) {
  545. RulesAddFooterTableViewCell *hcell = (RulesAddFooterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FooterCellIdentifier"];
  546. hcell.width = IPHONE_WIDTH;
  547. view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
  548. [view addSubview:hcell];
  549. if (_arrayForHeader.count == section) {
  550. [_arrayForHeader insertObject:view atIndex:section];
  551. }
  552. }
  553. return view;
  554. }
  555. - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  556. // if (section == 0) {
  557. // return 0.01f;
  558. // }
  559. return 0.01f;
  560. }
  561. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  562. CGFloat height = 0.0f;
  563. NSInteger section = indexPath.section;
  564. if (section == 0) {//title
  565. height = 122;
  566. } else if (section == 1) {//triggers
  567. height = 80;
  568. } else if (section == 2) {//actions
  569. height = 80;
  570. } else if (section == 3) {//push-message
  571. // height = UITableViewAutomaticDimension;
  572. height = 123;
  573. } else if (section == 4) {//conditions
  574. if (!_rcv) {
  575. _rcv = [CommonUtil instantiateViewControllerWithIdentifier:@"RulesConditionViewController" storyboardName:@"Rules"];
  576. [self addChildViewController:_rcv];
  577. [_rcv didMoveToParentViewController:self];
  578. }
  579. height = _rcv.tableHeight;
  580. }
  581. return height;
  582. }
  583. + (BOOL)hasDeleteNode:(ItemModel *)deviceItem {
  584. NSArray *matchedArray = [deviceItem.subItems filteredArrayUsingPredicateFormat:@"deleteYn == %@", ksYES];
  585. return matchedArray.count;
  586. }
  587. - (void)configureTriggerCell:(RulesAddTableViewCell *)cell item:(ItemModel *)item {
  588. ItemSubModel *subItem = nil;
  589. NSString *deviceImageFileName = nil;
  590. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
  591. subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  592. cell.lblItem.text = subItem.sourceName;
  593. deviceImageFileName = subItem.imageFileName;
  594. if ([subItem.deleteYn boolValue]) {
  595. [cell.lblItem setStrikethrough:cell.lblItem.text];
  596. }
  597. cell.lblSubItem.text = subItem.sourceSubName;
  598. //노드의 액션 값을 세팅함.
  599. if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
  600. CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  601. cell.lblCondition.text = [DeviceModel contentValueMsgByCmdClsCode:subItem.cmdclsCode cmdclsTypeId:(NSString *)subItem.cmdclsTypeId contentValue:cmdclsValue.cmdclsValue];
  602. } else {
  603. if (subItem.cmdclsValueMsg) {
  604. cell.lblCondition.text = subItem.cmdclsValueMsg;
  605. } else {
  606. NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
  607. cell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
  608. }
  609. }
  610. [cell.lblCondition setUnderLine:cell.lblCondition.text];
  611. cell.lblCondition.hidden = NO;
  612. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {
  613. subItem = item.timers && item.timers.count ? item.timers[0] : nil;
  614. if (subItem) {
  615. NSInteger phour = [subItem.hour integerValue];
  616. NSString *period = phour < 12 ? @"AM" : @"PM";//NSLocalizedString(@"오전", @"오전") : NSLocalizedString(@"오후", @"오후");
  617. if ([period isEqualToString:NSLocalizedString(@"오후", @"오후")]) {
  618. if (phour > 12) {
  619. phour -= 12;
  620. }
  621. }
  622. NSString *title = [NSString stringWithFormat:@"%@ %zd:%@", period, phour, subItem.minute];
  623. // NSDictionary *titleColor = @{NSForegroundColorAttributeName : kUITextColor02};
  624. cell.lblItem.text = title;
  625. cell.lblSubItem.text = [self daysOfWeekAtSubItem];
  626. cell.lblCondition.hidden = YES;
  627. }
  628. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {
  629. subItem = item.daylights && item.daylights.count ? item.daylights[0] : nil;
  630. if (subItem) {
  631. NSString *title = [subItem.sourceSubId isEqualToString:@"sunriseUtcTime"] ? @"해뜰때" : @"해질때";
  632. cell.lblItem.text = title;
  633. cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@", subItem.sourceName, [self daysOfWeekAtSubItem]];
  634. cell.lblCondition.hidden = YES;
  635. }
  636. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {
  637. subItem = item.heats && item.heats.count ? item.heats[0] : nil;
  638. if (subItem) {
  639. NSString *title = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"더울때" : @"추울때";
  640. cell.lblItem.text = title;
  641. cell.lblSubItem.text = [NSString stringWithFormat:@"%@ / %@℃ / %@", subItem.sourceName, subItem.cmdclsValue, [self daysOfWeekAtSubItem]];
  642. cell.lblCondition.hidden = YES;
  643. }
  644. }
  645. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {
  646. if (item.imageFileName) {
  647. [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:item.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  648. } else {
  649. [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:deviceImageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  650. }
  651. } else {
  652. cell.imgvIcon.image = [self imageForTrigger:item];
  653. }
  654. }
  655. - (NSString *)daysOfWeekAtSubItem {
  656. NSString *daysOfWeek = ksEmptyString;
  657. ItemModel *daysCondition = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksConditionSubTypeCodeDaysOfWeek];
  658. if (daysCondition) {
  659. ItemSubModel *subCondition = daysCondition.subItems[0];
  660. daysOfWeek = subCondition.daysOfWeek;
  661. }
  662. return daysOfWeek;
  663. }
  664. - (UIImage *)imageForTrigger:(ItemModel *)item {
  665. UIImage *image = nil;
  666. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  667. image = [UIImage imageNamed:@"img_rule_trigger_icon_time"];
  668. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
  669. image = [UIImage imageNamed:@"img_rule_trigger_icon_sunset"];
  670. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
  671. image = [UIImage imageNamed:@"img_rule_trigger_icon_temperature"];
  672. }
  673. return image;
  674. }
  675. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  676. NSInteger section = indexPath.section;
  677. UITableViewCell *cell = nil;
  678. if (section == 0) {//title
  679. RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
  680. tcell.txtRuleTitle.text = [tcell.txtRuleTitle.text isEmptyString] && _refRuleDetail ? _refRuleDetail.ruleName : tcell.txtRuleTitle.text;
  681. if (!_txtRuleTitle) {
  682. _txtRuleTitle = tcell.txtRuleTitle;
  683. }
  684. tcell.btnDelete.hidden = YES;
  685. tcell.btnConfirm.hidden = YES;
  686. cell = tcell;
  687. } else if (section == 1) {//triggers
  688. ItemModel *item = _triggers[indexPath.row];
  689. RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
  690. [self configureTriggerCell:tcell item:item];
  691. tcell.lblItem.textColor = kUITextColor04;
  692. tcell.btnDelete.value = item;
  693. if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  694. [tcell.btnDelete addTarget:self action:@selector(btnDeleteTriggerTouched:) forControlEvents:UIControlEventTouchUpInside];
  695. }
  696. cell = tcell;
  697. } else if (section == 2) {//actions
  698. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  699. ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
  700. RulesAddTableViewCell *tcell = (RulesAddTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"RulesCellIdentifier"];
  701. tcell.lblItem.text = subItem.sourceName;
  702. if ([subItem.deleteYn boolValue]) {
  703. [tcell.lblItem setStrikethrough:tcell.lblItem.text];
  704. }
  705. tcell.lblSubItem.text = subItem.sourceSubName;
  706. tcell.lblItem.textColor = kUITextColor01;
  707. [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:subItem.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached];
  708. //노드의 액션 값을 세팅함.
  709. if (subItem.cmdclsValueList && subItem.cmdclsValueList.count) {//커맨드클래스 밸루 리스트가 있을 경우,
  710. CmdClsValueModel *cmdclsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  711. tcell.lblCondition.text = cmdclsValue.cmdclsValueMsg;
  712. } else {
  713. if (subItem.cmdclsValueMsg) {
  714. tcell.lblCondition.text = subItem.cmdclsValueMsg;
  715. } else {
  716. NSString *condition = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual] ? @"이상" : @"이하";
  717. tcell.lblCondition.text = [NSString stringWithFormat:@"%@%@ %@", subItem.cmdclsValue, subItem.unit, condition];
  718. }
  719. }
  720. [tcell.lblCondition setUnderLine:tcell.lblCondition.text];
  721. tcell.btnDelete.value = subItem;
  722. if (![tcell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
  723. [tcell.btnDelete addTarget:self action:@selector(btnDeleteDeviceActionTouched:) forControlEvents:UIControlEventTouchUpInside];
  724. }
  725. cell = tcell;
  726. } else if (section == 3) {//push-message
  727. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  728. ItemSubModel *subItem = pushItem.pushes[indexPath.row];
  729. RulesAddPushTableViewCell *tcell = (RulesAddPushTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"PushCellIdentifier"];
  730. if (!_txvMessage) {
  731. _txvMessage = tcell.txvMessage;
  732. }
  733. // [self textViewDidChange:tcell.txvMessage];
  734. _txvMessage.delegate = self;
  735. _txvMessage.text = [_txvMessage.text isEqualToString:_txvMessage.placeHolder] && _refRuleDetail ? subItem.cmdclsValue : _txvMessage.text;
  736. tcell.btnDelete.value = subItem;
  737. [tcell.btnDelete addTarget:self action:@selector(btnDeletePushActionTouched:) forControlEvents:UIControlEventTouchUpInside];
  738. tcell.btnConfirm.hidden = YES;
  739. cell = tcell;
  740. } else if (section == 4) {//conditions
  741. RulesAddConditionTableViewCell *tcell = (RulesAddConditionTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:@"ConditionCellIdentifier"];
  742. if (_chkConditions.checked) {
  743. if (!tcell.container.subviews.count) {
  744. if ([self isViewLoaded]) {
  745. [_rcv beginAppearanceTransition:YES animated:NO];
  746. [tcell.container addSubview:_rcv.view];
  747. [_rcv endAppearanceTransition];
  748. }
  749. }
  750. _rcv.conditions = _conditions;
  751. _rcv.refDevices = _conditionDevices;
  752. tcell.constraintContainerHeight.constant = _rcv.tableHeight;
  753. }
  754. cell = tcell;
  755. }
  756. return cell;
  757. }
  758. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  759. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  760. if (indexPath.section == 1) {//triggers
  761. ItemModel *item = _triggers[0];
  762. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
  763. ItemSubModel *subItem = item.subItems[indexPath.row];
  764. [RulesAddViewController modifyTrigger:item subItem:subItem refDevices:_triggerDevices tableView:_tableView];
  765. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
  766. [self modifyTriggerOfTimer:item];
  767. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//해뜰때/질때 경우,
  768. [self modifyTriggerOfDaylight:item];
  769. } else if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//더울때/추울때 경우,
  770. [self modifyTriggerOfHeat:item];
  771. }
  772. } else if (indexPath.section == 2) {//actions
  773. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  774. if (deviceItem) {
  775. ItemSubModel *subItem = deviceItem.subItems[indexPath.row];
  776. [RulesAddViewController modifyAction:subItem refDevices:_actionDevices tableView:_tableView];
  777. }
  778. }
  779. }
  780. - (void)modifyTriggerOfTimer:(ItemModel *)item {
  781. TimePickerPopupView *tpopup = [[TimePickerPopupView alloc] initFromNib];
  782. tpopup.timeTrigger = item;
  783. tpopup.refConditions = _conditions;
  784. [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  785. if (buttonIndex == 0) {//OK
  786. [_tableView reloadData];
  787. }
  788. }];
  789. }
  790. - (void)modifyTriggerOfDaylight:(ItemModel *)item {
  791. DaylightPopupView *dpopup = [[DaylightPopupView alloc] initFromNib];
  792. dpopup.daylightTrigger = item;
  793. dpopup.refConditions = _conditions;
  794. [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  795. if (buttonIndex == 0) {//OK
  796. [_tableView reloadData];
  797. }
  798. }];
  799. }
  800. - (void)modifyTriggerOfHeat:(ItemModel *)item {
  801. ExternHeatPopupView *epopup = [[ExternHeatPopupView alloc] initFromNib];
  802. epopup.externHeatTrigger = item;
  803. epopup.refConditions = _conditions;
  804. [epopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  805. if (buttonIndex == 0) {//OK
  806. [_tableView reloadData];
  807. }
  808. }];
  809. }
  810. + (void)modifyTrigger:(ItemModel *)trigger subItem:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
  811. if ([subItem.deleteYn boolValue]) {
  812. [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
  813. return;
  814. }
  815. ItemModel *deviceItem = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
  816. //노드 선택 팝럽.
  817. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  818. npopup.refDevice = deviceItem;
  819. npopup.typeCode = ksItemTypeCodeTrigger;
  820. npopup.isModifyMode = YES;
  821. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  822. if (buttonIndex == 0) {//OK
  823. [trigger.subItems removeAllObjects];
  824. ItemSubModel *fsubItem = [deviceItem.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  825. [trigger.subItems addObject:fsubItem];
  826. // subItem.cmdclsCode = matchedSubItem.cmdclsCode;
  827. // subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
  828. //
  829. // if (matchedSubItem.cmdclsValueList) {
  830. // subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
  831. //
  832. // CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  833. // subItem.cmdclsValue = pCmdClsValue.cmdclsValue; //CommandClassControlNodeView - 에서 선택됨.
  834. // }
  835. if (tableView) {
  836. [tableView reloadData];
  837. }
  838. }
  839. }];
  840. }
  841. + (void)modifyAction:(ItemSubModel *)subItem refDevices:(NSMutableArray<ItemModel> *)refDevices tableView:(CustomTableView *)tableView {
  842. if ([subItem.deleteYn boolValue]) {
  843. [[JDFacade facade] toast:@"삭제된 장치입니다\r목록에서 제거하세요"];
  844. return;
  845. }
  846. ItemModel *item = [refDevices objectKey:@"sourceId" eqaulToString:subItem.sourceId];
  847. ItemSubModel *matchedSubItem = [item.subItems objectKey:@"sourceSubId" eqaulToString:subItem.sourceSubId];
  848. //노드 선택 팝럽.
  849. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  850. npopup.refDevice = item;
  851. npopup.typeCode = ksItemTypeCodeTrigger;
  852. npopup.isModifyMode = YES;
  853. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  854. if (buttonIndex == 0) {//OK
  855. subItem.cmdclsCode = matchedSubItem.cmdclsCode;
  856. subItem.cmdclsTypeId = matchedSubItem.cmdclsTypeId;
  857. subItem.cmdclsValueList = matchedSubItem.cmdclsValueList;
  858. CmdClsValueModel *pCmdClsValue = [subItem.cmdclsValueList matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  859. subItem.cmdclsValue = pCmdClsValue.cmdclsValue; //CommandClassControlNodeView - 에서 선택됨.
  860. if (tableView) {
  861. [tableView reloadData];
  862. }
  863. }
  864. }];
  865. }
  866. #pragma mark - TableView UI Events
  867. - (void)btnAddTriggerTouched:(id)sender {
  868. TriggerSelectPopupView *tpopup = [[TriggerSelectPopupView alloc] initFromNib];
  869. tpopup.refTriggers = _triggers;
  870. tpopup.refDevices = _triggerDevices;
  871. tpopup.refConditions = _conditions;
  872. [tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  873. if (buttonIndex == 0) {
  874. [_tableView reloadData];
  875. }
  876. }];
  877. }
  878. - (void)btnAddActionTouched:(id)sender {
  879. DeviceSelectPopupView *dpopup = [[DeviceSelectPopupView alloc] initFromNib];
  880. dpopup.refDevices = _actionDevices;
  881. dpopup.typeCode = ksItemTypeCodeTrigger;
  882. [dpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  883. if (buttonIndex == 0) {//ok
  884. DeviceNodePopupView *npopup = [[DeviceNodePopupView alloc] initFromNib];
  885. npopup.refDevice = dpopup.selectedDevices[0];
  886. npopup.typeCode = ksItemTypeCodeTrigger;
  887. [npopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  888. //action add
  889. if (buttonIndex == 0) {//OK
  890. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  891. if (!deviceItem) {//디바이스 아이템이 없을 경우,
  892. deviceItem = [[ItemModel alloc] init];
  893. deviceItem.itemName = @"이 장치를 실행";
  894. deviceItem.itemSubTypeCode = ksItemSubTypeCodeDevice;
  895. deviceItem.subItems = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
  896. [_actions addObject:deviceItem];
  897. }
  898. ItemSubModel *snode = npopup.selectedNode;
  899. //존재 여부 확인
  900. if (![deviceItem.subItems objectByUsingPredicateFormat:@"sourceId == %@ && sourceSubId == %@", snode.sourceId, snode.sourceSubId]) {
  901. [deviceItem.subItems addObject: snode];
  902. }
  903. [_tableView reloadData];
  904. }
  905. }];
  906. }
  907. }];
  908. }
  909. - (void)btnAddPushMessageTouched:(id)sender {
  910. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  911. if (!pushItem) {//디바이스 아이템이 없을 경우,
  912. pushItem = [[ItemModel alloc] init];
  913. pushItem.itemName = [JDFacade facade].loginUser.memberId;
  914. pushItem.itemSubTypeCode = ksItemSubTypeCodeAppPush;
  915. pushItem.pushes = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];
  916. ItemSubModel *push = [[ItemSubModel alloc] init];
  917. push.conditionTypeCode = @"02";
  918. [pushItem.pushes addObject:push];
  919. [_actions addObject:pushItem];
  920. }
  921. [_tableView reloadData];
  922. }
  923. - (void)btnDeleteTriggerTouched:(id)sender {
  924. CustomButton *btnDelete = (CustomButton *)sender;
  925. ItemModel *item = btnDelete.value;
  926. if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//장치일 경우
  927. ItemSubModel *subItem = [item.subItems matchedObjectName:ksCustomRadioButtonStatus condition:YES];
  928. if (subItem) {
  929. [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
  930. for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
  931. [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
  932. cmdclsValue.isSelected = NO;
  933. }
  934. }
  935. }
  936. if (_triggers && _triggers.count) {
  937. [_triggers removeAllObjects];
  938. }
  939. [_tableView reloadData];
  940. }
  941. - (void)btnDeleteDeviceActionTouched:(id)sender {
  942. CustomButton *btnDelete = (CustomButton *)sender;
  943. ItemSubModel *subItem = (ItemSubModel *)btnDelete.value;
  944. //선택 설정을 초기화
  945. [[JDFacade facade] setRadioButtonStatus:@NO object:subItem];
  946. for (CmdClsValueModel *cmdclsValue in subItem.cmdclsValueList) {
  947. [[JDFacade facade] setRadioButtonStatus:@NO object:cmdclsValue];
  948. cmdclsValue.isSelected = NO;
  949. }
  950. ItemModel *deviceItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  951. [deviceItem.subItems removeObject:subItem];
  952. [_tableView reloadData];
  953. }
  954. - (void)btnDeletePushActionTouched:(id)sender {
  955. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  956. [_actions removeObject:pushItem];
  957. [_tableView reloadData];
  958. }
  959. #pragma mark - CustomTextView Delegate
  960. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  961. NSLog(@"%s\n %zd", __PRETTY_FUNCTION__, textView.text.length);
  962. return textView.text.length < 120;
  963. }
  964. #pragma mark - UI Events
  965. - (IBAction)btnConfirmTouched:(id)sender {
  966. [self.view endEditing:YES];
  967. //1.Validate Title
  968. RulesAddTitleTableViewCell *tcell = (RulesAddTitleTableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; //타이틀 섹션
  969. if (tcell && ![ValidateUtil validateTextfiled:tcell.txtRuleTitle type:ValidateTypeNull title:NSLocalizedString(@"규칙 이름", @"규칙 이름")]) {
  970. return;
  971. }
  972. if (tcell.txtRuleTitle.text.length > 40) {
  973. [[JDFacade facade] alert:@"규칙이름은 최대 40자까지 입력할 수 있습니다"];
  974. return;
  975. }
  976. ItemModel *pushItem = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeAppPush];
  977. if (pushItem) {
  978. if (_txvMessage && [_txvMessage.text isEmptyString]) {//푸시메시지 여부 확인
  979. [_actions removeObject:pushItem];
  980. } else if (_txvMessage) {
  981. ItemSubModel *subItem = pushItem.pushes[0];
  982. subItem.cmdclsValue = _txvMessage.text;
  983. if (_txvMessage.text.length > 120) {
  984. [[JDFacade facade] alert:@"알림메시지는 최대 120자까지 입력할 수 있습니다"];
  985. return;
  986. }
  987. }
  988. }
  989. if (!_refRuleDetail) {//생성
  990. [self requestRegisterRule];
  991. } else {//수정
  992. BOOL hasDeleteNode = NO;
  993. ItemModel *triggerDevice = [_triggers objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  994. ItemModel *actionDevice = [_actions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  995. ItemModel *conditionDevice = [_conditions objectKey:@"itemSubTypeCode" eqaulToString:ksItemSubTypeCodeDevice];
  996. hasDeleteNode = [RulesAddViewController hasDeleteNode:triggerDevice];
  997. hasDeleteNode = [RulesAddViewController hasDeleteNode:actionDevice] ? YES : hasDeleteNode;
  998. hasDeleteNode = [RulesAddViewController hasDeleteNode:conditionDevice] ? YES : hasDeleteNode;
  999. if (hasDeleteNode) {
  1000. [[JDFacade facade] confirm:@"삭제된 장치를 제외 후 저장합니다" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  1001. if (buttonIndex == 0) {//OK
  1002. [self getRidOfDeleteDevices:triggerDevice];
  1003. [self getRidOfDeleteDevices:actionDevice];
  1004. [self getRidOfDeleteDevices:conditionDevice];
  1005. [_tableView reloadData];
  1006. [self requestModifyRule];
  1007. }
  1008. }];
  1009. } else {
  1010. [self requestModifyRule];
  1011. }
  1012. }
  1013. }
  1014. //삭제된 장치를 제거함.
  1015. - (void)getRidOfDeleteDevices:(ItemModel *)deviceItem {
  1016. [deviceItem.subItems enumerateObjectsUsingBlock:^(ItemSubModel *subItem, NSUInteger idx, BOOL * _Nonnull stop) {
  1017. if (subItem.deleteYn) {
  1018. if ([_triggers containsObject:deviceItem]) {
  1019. [_triggers removeObject:deviceItem];
  1020. return;
  1021. }
  1022. [deviceItem.subItems removeObject:subItem];
  1023. }
  1024. }];
  1025. }
  1026. - (IBAction)btnCancelTouched:(id)sender {
  1027. [self dismissViewControllerAnimated:YES completion:nil];
  1028. }
  1029. #pragma mark - MemoryWarning
  1030. - (void)didReceiveMemoryWarning
  1031. {
  1032. [super didReceiveMemoryWarning];
  1033. // Dispose of any resources that can be recreated.
  1034. }
  1035. @end