// // ICRTaskCreateViewController.m // XFFruit // // Created by Xummer on 4/9/15. // Copyright (c) 2015 Xummer. All rights reserved. // #import "ICRTaskEditViewController.h" #import "ICRCheckBox.h" #import "ICRPlaceholderTextView.h" #import "ICRAttachmentView.h" #import "ICRAttachmentUnit.h" #import "IBTImagePicker.h" #import "JTImagePreviewer.h" #import "IBTDatePickerViewController.h" #import "JTOptionsViewController.h" #import "ICRTaskDetailViewController.h" #import "ICRPostTask.h" #import "ICRTask.h" #import "ICRStore.h" #import "ICRPost.h" #import "ICRPostAttachment.h" #import "ICRPerson.h" typedef NS_ENUM(NSUInteger, TaskTableCellInfo) { kTaskCellStore = 0, kTaskCellTitle, kTaskCellType, kTaskCellContent, kTaskCellDuedate, }; @interface ICRTaskEditViewController () < IBTDatePickerDelegate, JTOptionsDelegate, IBTImagePickerDelegate > { BOOL bIsLoaded; } @property (strong, nonatomic) IBTTableViewInfo *m_tableViewInfo; @property (strong, nonatomic) UIView *m_checkBoxView; @property (strong, nonatomic) ICRTask *m_task; @property (strong, nonatomic) ICRStore *m_store; @property (strong, nonatomic) ICRPerson *m_person; @property (strong, nonatomic) ICRCheckBox *m_handleCheckBox; @property (strong, nonatomic) ICRPlaceholderTextView *m_textView; @property (strong, nonatomic) ICRAttachmentView *m_photoView; @property (strong, nonatomic) IBTImagePicker *m_imagePicker; @property (strong, nonatomic) JTOptionsEntity *m_options; @end @implementation ICRTaskEditViewController #pragma mark - Life Cycle - (instancetype)initWithTask:(id)task store:(id)store { self = [super init]; if (!self) { return nil; } if ([task isKindOfClass:[ICRTask class]]) { self.m_task = task; } if ([store isKindOfClass:[ICRStore class]]) { self.m_store = store; } else if ([store isKindOfClass:[NSNumber class]]) { ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) { NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@ == ?", [ICRStore TableName], @"uuid"]; return [db executeQuery:sql, store]; }; __weak typeof(self)weakSelf = self; ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) { __strong __typeof(weakSelf)strongSelf = weakSelf; strongSelf.m_store = [fetchedObjects firstObject]; [strongSelf initTableViewInfo]; }; ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController]; [dbCtrl runFetchForClass:[ICRStore class] fetchBlock:fetchBlk fetchResultsBlock:fetchResultsBlk]; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ICRHTTPController *httpCtrl = [ICRHTTPController sharedController]; [httpCtrl doGetPersonListFromUpdateTime:0 position:0 size:20 success:nil failure:nil]; self.title = [IBTCommon localizableString:_m_task ? @"Edit Task" : @"Create New Task" ]; [self initTableViewInfo]; [self fetchTypeList]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; // if (!bIsLoaded) { // if (_m_task.photo) { // ICRPostAttachment *pPic = [ICRPostAttachment DBObject]; // [pPic praseFromJsonDict:_m_task.photo]; // // NSData *imageData = [NSData dataFromBase64String:pPic.content]; // UIImage *image = [UIImage imageWithData:imageData]; // // [self addAttachment:image]; // } // } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Setter - (void)setM_options:(JTOptionsEntity *)options { _m_options = options; if(_m_options) { IBTTableViewCellInfo *cellInfo = [_m_tableViewInfo getCellAtSection:0 row:kTaskCellType]; ICRPerson *person = [_m_options getSelectedOption]; [cellInfo addUserInfoValue:person.login forKey:CInfoRightValueKey]; [[_m_tableViewInfo getTableView] reloadData]; } } #pragma mark - Private Method - (void)initTableViewInfo { if (!_m_store) { return; } self.m_tableViewInfo = [[IBTTableViewInfo alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; IBTTableView *tableV = [_m_tableViewInfo getTableView]; [self.view addSubview:tableV]; // Footer [self initCheckBox]; self.m_checkBoxView.frame = (CGRect){ .origin.x = 15, .origin.y = 5, .size.width = tableV.width - 30, .size.height = 30 }; UIButton *btn = nil; UIView *tableFooter = [tableV buttonViewWithTitle:[IBTCommon localizableString:@"Submit"] color:ICR_ORANGE_BTN_COLOR topGap:10 + _m_checkBoxView.bottom pointer:&btn target:self action:@selector(onSubmit:)]; [tableFooter addSubview:_m_checkBoxView]; IBTUIView *greyLine = [[IBTUIView alloc] initWithFrame:(CGRect){ .origin.x = 15, .origin.y = 0, .size.width = tableV.width - 15, .size.height = 1 }]; greyLine.backgroundColor = [UIColor colorWithW:227 a:1]; greyLine.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth; [tableFooter addSubview:greyLine]; tableV.tableFooterView = tableFooter; IBTTableViewSectionInfo *secInfo; IBTTableViewCellInfo *cellInfo; UIColor *titleColor = [UIColor colorWithW:145 a:1]; CGFloat fCellHeight = IBT_DEFAULT_CELL_HEIGHT; secInfo = [IBTTableViewSectionInfo sectionInfoDefaut]; // Store cellInfo = [IBTTableViewCellInfo normalCellForSel:nil target:nil title:[IBTCommon localizableString:@"Store:"] rightValue:_m_store.name accessoryType:UITableViewCellAccessoryNone]; cellInfo.selectionStyle = UITableViewCellSelectionStyleNone; [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey]; cellInfo.fCellHeight = fCellHeight; [secInfo addCell:cellInfo]; // Title cellInfo = [IBTTableViewCellInfo editorCellForSel:nil target:nil title:[IBTCommon localizableString:@"Title:"] margin:0 tip:nil autoCorrect:NO focus:NO text:nil]; [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey]; [cellInfo addUserInfoValue:_m_task.title forKey:CInfoEditorTextKey]; cellInfo.fCellHeight = fCellHeight; [secInfo addCell:cellInfo]; // type cellInfo = [IBTTableViewCellInfo normalCellForSel:@selector(onShowTypesList:) target:self title:[IBTCommon localizableString:@"Task Charger"] rightValue:[_m_options getSelectedOption] accessoryType:UITableViewCellAccessoryDisclosureIndicator]; [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey]; cellInfo.fCellHeight = fCellHeight; [secInfo addCell:cellInfo]; // Content cellInfo = [[IBTTableViewCellInfo alloc] init]; cellInfo.makeTarget = self; cellInfo.makeSel = @selector(makeContentCell:); [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey]; cellInfo.fCellHeight = 185; [secInfo addCell:cellInfo]; // DueDate cellInfo = [IBTTableViewCellInfo normalCellForSel:@selector(onShowSelectDueDate:) target:self title:[IBTCommon localizableString:@"DueDate:"] rightValue:_m_task.requireDate accessoryType:UITableViewCellAccessoryDisclosureIndicator]; [cellInfo addUserInfoValue:titleColor forKey:CInfoTitleColorKey]; cellInfo.fCellHeight = fCellHeight; [secInfo addCell:cellInfo]; [self.m_tableViewInfo addSection:secInfo]; } - (void)initCheckBox { self.m_checkBoxView = [[UIView alloc] init]; self.m_checkBoxView.backgroundColor = [UIColor clearColor]; self.m_handleCheckBox = [[ICRCheckBox alloc] initWithFrame:(CGRect){ .origin.x = 0, .origin.y = (_m_checkBoxView.height - CHECK_BOX_DEFAULT_WIDTH) * .5f, .size.width = CHECK_BOX_DEFAULT_WIDTH, .size.height = CHECK_BOX_DEFAULT_WIDTH }]; _m_handleCheckBox.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; _m_handleCheckBox.isSelected = NO; _m_handleCheckBox.m_eBGType = kCheckBoxBGGray; [_m_checkBoxView addSubview:_m_handleCheckBox]; IBTUILabel *handleLabel = [[IBTUILabel alloc] init]; handleLabel.textAlignment = NSTextAlignmentLeft; handleLabel.textColor = [UIColor colorWithW:135.0f a:1]; handleLabel.font = [UIFont systemFontOfSize:14.0f]; handleLabel.text = [IBTCommon localizableString:@"Hande by Self"]; [handleLabel sizeToFit]; CGFloat fDx = _m_handleCheckBox.right + 10; handleLabel.frame = (CGRect){ .origin.x = fDx, .origin.y = 0, .size.width = handleLabel.width, .size.height = _m_checkBoxView.height }; handleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [_m_checkBoxView addSubview:handleLabel]; IBTUIButton *handleBtn = [[IBTUIButton alloc] initWithFrame:_m_checkBoxView.bounds]; handleBtn.backgroundColor = [UIColor clearColor]; [handleBtn autoresizingWithStrechFullSize]; [handleBtn addTarget:_m_handleCheckBox action:@selector(onCheckBoxAction:) forControlEvents:UIControlEventTouchUpInside]; [_m_checkBoxView addSubview:handleBtn]; // _m_handleCheckBox.isSelected = _m_task.assignToMe; } - (void)makeContentCell:(IBTTableViewCellInfo *)cellInfo { IBTTableViewCell *cell = cellInfo.cell; cell.selectionStyle = UITableViewCellSelectionStyleNone; [cell.contentView removeAllSubViews]; UIView *contentView = cell.contentView; IBTUILabel *titleLabel = [[IBTUILabel alloc] init]; [cell.contentView addSubview:titleLabel]; id titleColor = [cellInfo getUserInfoValueForKey:CInfoTitleColorKey]; if ([titleColor isKindOfClass:[UIColor class]]) { titleLabel.textColor = titleColor; } titleLabel.text = [IBTCommon localizableString:@"Content:"]; titleLabel.frame = (CGRect){ .origin.x = 15, .origin.y = 10, .size.width = 50, .size.height = 20 }; UIView *txtContentView = [[UIView alloc] initWithFrame:(CGRect){ .origin.x = titleLabel.right, .origin.y = titleLabel.top, .size.width = contentView.width - titleLabel.right - 10, .size.height = 95 }]; txtContentView.layer.masksToBounds = YES; txtContentView.layer.cornerRadius = 5; txtContentView.layer.borderWidth = 1; txtContentView.layer.borderColor = [UIColor colorWithW:239 a:1].CGColor; txtContentView.backgroundColor = [UIColor colorWithW:245 a:1]; if (!_m_textView) { self.m_textView = [[ICRPlaceholderTextView alloc] initWithFrame:CGRectInset(txtContentView.bounds, 5, 5)]; _m_textView.font = [UIFont systemFontOfSize:16.0f]; _m_textView.backgroundColor = [UIColor clearColor]; _m_textView.text = _m_task.content; } [txtContentView addSubview:_m_textView]; [contentView addSubview:txtContentView]; if (!_m_photoView) { self.m_photoView = [[ICRAttachmentView alloc] initWithType:kAttViewImage]; _m_photoView.frame = (CGRect){ .origin.x = txtContentView.left, .origin.y = txtContentView.bottom + 5, .size.width = txtContentView.width, .size.height = 70 }; _m_photoView.m_uiMaxAttCount = 1; [_m_photoView.m_addButton addTarget:self action:@selector(onShowImagePicker:) forControlEvents:UIControlEventTouchUpInside]; } [contentView addSubview:_m_photoView]; } - (IBTImagePicker *)imagePicker { if (!_m_imagePicker) { self.m_imagePicker = [[IBTImagePicker alloc] init]; } return _m_imagePicker; } #pragma mark - Actions - (void)onSubmit:(__unused id)sender { IBTTableViewCellInfo *cellInfo = [_m_tableViewInfo getCellAtSection:0 row:kTaskCellTitle]; UITextField *titleTxtF = [cellInfo getUserInfoValueForKey:CInfoEditorKey]; IBTTableViewCellInfo *duedateCellInfo = [_m_tableViewInfo getCellAtSection:0 row:kTaskCellDuedate]; NSString *reqDate = [duedateCellInfo getUserInfoValueForKey:CInfoRightValueKey]; if (titleTxtF.text.length == 0 || _m_textView.text.length == 0) { [IBTLoadingView showTips:@"请输入标题和内容"]; return; } else if (reqDate.length == 0) { [IBTLoadingView showTips:@"请选择要求完成日期"]; return; } ICRUserUtil *user = [ICRUserUtil sharedInstance]; ICRPostTask *task = [[ICRPostTask alloc] init]; task.title = titleTxtF.text; task.content = _m_textView.text; task.createInfo = @{@"operator": _m_store.createInfo[@"operator"],@"time":_m_store.createInfo[@"time"]}; task.requireDate = reqDate; task.orgUuid = user.orgId; task.processor = [[_m_options getSelectedOption] valueForKey:@"login"]; task.uuid = [[ICRUserUtil sharedInstance] mobileID]; task.storeCode =_m_store.code; if ([_m_delegate respondsToSelector:@selector(taskEditViewCtrl:taskData:edit:)]) { NSArray *arrAttach = [_m_photoView.m_arrAttViews valueForKeyPath:@"m_oAttachmentWrap"]; UIImage *img = [arrAttach firstObject]; if (img) { IBTFileData *imgFile = [IBTCommon saveImageToLocal:img]; ICRPostAttachment *attE = [[ICRPostAttachment alloc] init]; attE.entityType = @"task"; attE.entityUuid = [[NSDate date] chatAttachmentFormatterString]; attE.fileName = imgFile.fileName; attE.content = [imgFile.fileData base64EncodedString]; } [_m_delegate taskEditViewCtrl:self taskData:task edit:_m_task]; return; } __weak typeof(self)weakSelf = self; void(^complete)(void) = ^(void) { ICRTask *taskE = [ICRTask taskFromPostTask:task]; taskE.storeCode = _m_store.storyID;//这个需要确定 ICRTaskDetailViewController *dVC = [[ICRTaskDetailViewController alloc]initWithTaskData:taskE]; UIViewController *rVC = [self getViewControllerAtIndex:0]; [self PopToRootViewControllerAnimated:NO]; [rVC PushViewController:dVC animated:YES]; }; void(^succ)(id) = ^(id data) { __strong __typeof(weakSelf)strongSelf = weakSelf; [strongSelf doUploadAttachmentsToTask:task complete:complete]; }; void(^fail)(id) = ^(id data) { [IBTLoadingView showTips:data]; task.isNotUploaded = YES; [task saveToDBWithHandleData:NULL complete:NULL fail:NULL]; }; ICRHTTPController *httpCtrl = [ICRHTTPController sharedController]; [httpCtrl doCreateNewTaskWithInfo:[task dictForCommit] success:succ failure:fail]; } - (void)doUploadAttachmentsToTask:(ICRPostTask *)task complete:(void (^)(void))complete { NSArray *arrAttach = [_m_photoView.m_arrAttViews valueForKeyPath:@"m_oAttachmentWrap"]; NSUInteger uiAttCount = [arrAttach count]; if (uiAttCount > 0) { __block NSUInteger uiSucCount = 0; void(^suc)(id) = ^(id data) { uiSucCount ++; if (uiSucCount == uiAttCount) { if (complete) { complete(); } } }; void(^fai)(id) = ^(id data) { [IBTLoadingView showTips:@"上传失败"]; }; ICRHTTPController *httpCtrl = [ICRHTTPController sharedController]; for (UIImage *img in arrAttach) { IBTFileData *imgFile = [IBTCommon saveImageToLocal:img]; ICRPostAttachment *attE = [[ICRPostAttachment alloc] init]; attE.entityUuid =[[ICRUserUtil sharedInstance] mobileID]; attE.fileName = imgFile.fileName; attE.content = [imgFile.fileData base64EncodedString]; attE.entityType= @"task"; [httpCtrl doAddAttachment:[attE dictForCommit] success:suc failure:fai]; } } else { if (complete) { complete(); } } } - (void)onShowImagePicker:(__unused id)sender { [[self imagePicker] showImagePickerTitle:nil mediaType:kIBTMediaBImage editable:NO fromViewController:self]; } - (void)onShowTypesList:(__unused id)sender { if (_m_options) { IBTTableViewCellInfo *cellInfo = [_m_tableViewInfo getCellAtSection:0 row:kTaskCellType]; JTOptionsViewController *oVC = [[JTOptionsViewController alloc] initWithOptions:_m_options]; oVC.title = [cellInfo getUserInfoValueForKey:CInfoLeftValueKey]; oVC.optionsDelegate = self; [self PushViewController:oVC animated:YES]; } } - (void)onShowSelectDueDate:(__unused id)sender { IBTDatePickerViewController *dVC = [[IBTDatePickerViewController alloc] init]; dVC.title = [IBTCommon localizableString:@"Select Date"]; dVC.delegate = self; [self PushViewController:dVC animated:YES]; } #pragma mark - IBTImagePickerDelegate - (void)imagePicker:(IBTImagePickerController *)picker didImagePicked:(UIImage *)image referenceURL:(NSURL *)imageUrl { [self addAttachment:image]; } - (void)imagePicker:(IBTImagePickerController *)picker didVideoPickedWithURL:(NSURL *)videoUrl { } - (void)fetchTypeList { ICRDatabaseFetchBlock fetchBlk = ^FMResultSet *(FMDatabase *db) { NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@", [ICRPerson TableName]]; return [db executeQuery:sql]; }; __weak typeof(self)weakSelf = self; ICRDatabaseFetchResultsBlock fetchResultsBlk = ^(NSArray *fetchedObjects) { __strong __typeof(weakSelf)strongSelf = weakSelf; NSUInteger lastInd = _m_options.selectedIndex; strongSelf.m_options = [JTOptionsEntity entityWithOptions:fetchedObjects defaultOptionIndex:lastInd andSelectedOption:@"login"]; }; ICRDataBaseController *dbCtrl = [ICRDataBaseController sharedController]; [dbCtrl runFetchForClass:[ICRPerson class] fetchBlock:fetchBlk fetchResultsBlock:fetchResultsBlk]; } - (void)onTapImage:(ICRAttachmentUnit *)unit { CGRect rect = [self.view.window convertRect:unit.frame fromView:unit.superview]; UIImage *img = unit.m_oAttachmentWrap; JTImagePreviewer *ipv = [[JTImagePreviewer alloc] initWithViewController:self tempImage:img url:nil startRect:rect]; [ipv show]; } - (void)addAttachment:(id)oAtt { SEL selector = NULL; UIImage *iconImg; ICRAttachmentView *attachView = nil; iconImg = oAtt; selector = @selector(onTapImage:); attachView = _m_photoView; ICRAttachmentUnit *attV = [[ICRAttachmentUnit alloc] initWithFrame:(CGRect){ .origin.x = 0, .origin.y = 0, .size.width = IBT_ATTACH_UNIT_DEFAULT_WIDTH, .size.height = IBT_ATTACH_UNIT_DEFAULT_WIDTH }]; [attV updateWithType:kATTCloseBtn masker:nil placeHolder:nil image:iconImg title:nil]; attV.m_oAttachmentWrap = oAtt; [attV addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside]; [attachView addContentAttachmentView:attV]; } #pragma mark - JTOptionsDelegate - (void)optionsViewController:(JTOptionsViewController *)optionVC didChangedSelectedOptions:(JTOptionsEntity *)options { self.m_options = options; [optionVC PopViewControllerAnimated:YES]; } #pragma mark - ICRDatePickerDelegate - (void)datePickerVCtrl:(IBTDatePickerViewController *)pickerVCtrl didSelectedDate:(NSDate *)selectDate { IBTTableViewCellInfo *cellInfo = [_m_tableViewInfo getCellAtSection:0 row:kTaskCellDuedate]; [cellInfo addUserInfoValue:[selectDate httpParameterString] forKey:CInfoRightValueKey]; [[_m_tableViewInfo getTableView] reloadData]; [pickerVCtrl PopViewControllerAnimated:YES]; } #pragma mark - Keyboard Notification - (void)keyboardWillShow:(NSNotification *)keyboard { // get keyboard size and loctaion CGRect keyboardBounds; [[keyboard.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds]; NSNumber *duration = [keyboard.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSNumber *curve = [keyboard.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]; // Need to translate the bounds to account for rotation. keyboardBounds = [self.view convertRect:keyboardBounds toView:nil]; // animations settings [UIView beginAnimations:nil context:NULL]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:[duration doubleValue]]; [UIView setAnimationCurve:[curve intValue]]; // set views with new info IBTTableView *tableView = [_m_tableViewInfo getTableView]; [tableView setContentInsetTop:tableView.contentInset.top andBottom:CGRectGetHeight(keyboardBounds)]; // commit animations [UIView commitAnimations]; } - (void)keyboardWillHide:(NSNotification *)keyboard { NSNumber *duration = [keyboard.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]; NSNumber *curve = [keyboard.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey]; // animations settings [UIView beginAnimations:nil context:NULL]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:[duration doubleValue]]; [UIView setAnimationCurve:[curve intValue]]; // set views with new info IBTTableView *tableView = [_m_tableViewInfo getTableView]; [tableView setContentInsetTop:tableView.contentInset.top andBottom:0]; // commit animations [UIView commitAnimations]; } @end