RulesAddViewController.m 53 KB

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