RulesAddViewController.m 55 KB

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