RulesAddViewController.m 54 KB

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