// // FKPublicProductController.m // FirstLink // // Created by ascii on 16/6/8. // Copyright © 2016年 FirstLink. All rights reserved. // #import "FKCirclePublicController.h" #import "FKCirclePublicViewModel.h" #import "FKCircleAddView.h" #import "FKButtonChoiceMenu.h" #import "FKCirclePublicUserCell.h" #import "FKCirclePublicTextCell.h" #import "FKCirclePublicImageCell.h" #import "FKCirclePublicProcuctCell.h" #import "FLControllerHelper.h" #import "FLImageHelper.h" #import "FKCirDetailRequest.h" #import "FKCirDetailReform.h" #import "FKCircleDetailViewModel.h" #import "FKCirclePhotoClipController.h" #import "FKCircleProductSegmentController.h" #import "FKCircleTagsController.h" #import "FKWeakTimerTarget.h" @interface FKCirclePublicController () @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) FKCircleAddView *circleAddView; @property (nonatomic, strong) FKButtonChoiceMenu *buttonChoiceMenu; @property (nonatomic, strong) FKCirclePublicViewModel *viewModel; @property (nonatomic, assign) BOOL viewDidAppear; @property (nonatomic, strong) UITextView *responderTextView; @property (nonatomic, strong) UITextView *reframeTextView; @property (nonatomic, assign) CGFloat keyboardHeight; @end static NSInteger const FKCircleDetailRequest = 1; @implementation FKCirclePublicController - (instancetype)initWithItemID:(NSString *)itemID { self = [super init]; if (self) { self.viewModel.itemID = itemID; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self configKeyboardNotifications]; self.view.backgroundColor = [UIColor whiteColor]; self.navigationItem.title = @"晒单发布"; [self configRightNaviItem]; [self prepareInitData]; [self addAllSubviews]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.view endEditing:NO]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self delayBecomeFirstResponder]; self.viewDidAppear = YES; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Request - (void)prepareInitData { if (self.viewModel.itemID.length > 0) { [FKCirDetailRequest reqCirDetailWithID:self.viewModel.itemID identify:FKCircleDetailRequest delegate:self]; } else { [self.viewModel prepareInitData]; } } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ #pragma mark - response - (void)networkDidSuccessResponse:(NSDictionary*)response identify:(int)identify header:(MSGHeader*)header { [self.hudView hide:NO]; if (header.code.integerValue == RESPONSE_MSG_NORMAL){ if (identify == FKCircleDetailRequest){ FKCircleDetailItem *dataItem = [FKCirDetailReform parserDetailItemWithDict:response]; [self.viewModel loadDataFrom:dataItem]; [self.tableView reloadData]; } } else { [FLProgressHUDHelper showText:header.msg inView:self.view]; } } - (void)networkDidReceiveError:(NSError*)error identify:(int)identify header:(MSGHeader*)header{ [self.hudView hide:NO]; [FLProgressHUDHelper showText:header.msg inView:self.view]; } #pragma mark - UITableViewDataSource, UITableViewDelegate - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return self.viewModel.modelMutArray.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { if (section == 0) { return 6; } return CGFLOAT_MIN; } - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { return 15; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { id item = [self.viewModel modelItemAtIndexPath:indexPath]; kCirclePublicType cellType = [self.viewModel cellTypeAtIndexPath:indexPath]; switch (cellType) { case kCirclePublicUser: return [FKCirclePublicUserCell height]; case kCirclePublicProductDesc: return [FKCirclePublicTextCell heightWith:item]; case kCirclePublicImage: return [FKCirclePublicImageCell heightWith:item]; case kCirclePublicProduct: return [FKCirclePublicProcuctCell height]; default: break; } return 44; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { id item = [self.viewModel modelItemAtIndexPath:indexPath]; kCirclePublicType cellType = [self.viewModel cellTypeAtIndexPath:indexPath]; NSString *identify = [self.viewModel orderCellIdentifyWith:cellType]; id cell = [self.tableView dequeueReusableCellWithIdentifier:identify]; switch (cellType) { case kCirclePublicUser: if ([cell isKindOfClass:[FKCirclePublicUserCell class]]) { FKCirclePublicUserCell *userCell = (FKCirclePublicUserCell *)cell; [userCell configWith:item]; } break; case kCirclePublicProductDesc: { if ([cell isKindOfClass:[FKCirclePublicTextCell class]]) { FKCirclePublicTextCell *textCell = (FKCirclePublicTextCell *)cell; textCell.textView.delegate = self; textCell.textView.tag = indexPath.section; [textCell configWith:item]; if (!self.viewDidAppear) { self.responderTextView = textCell.textView; } } break; } case kCirclePublicImage: if ([cell isKindOfClass:[FKCirclePublicImageCell class]]) { FKCirclePublicImageCell *imageCell = (FKCirclePublicImageCell *)cell; imageCell.textView.delegate = self; imageCell.tag = indexPath.section; imageCell.clickCallback = [self clickButtonOnImageCell]; [imageCell configWith:item]; } break; case kCirclePublicProduct: if ([cell isKindOfClass:[FKCirclePublicProcuctCell class]]) { FKCirclePublicProcuctCell *procuctCell = (FKCirclePublicProcuctCell *)cell; [procuctCell configWith:item]; procuctCell.deleteButton.tag = indexPath.section; [procuctCell.deleteButton addTarget:self action:@selector(clickDeleteButtonOnProductCell:) forControlEvents:UIControlEventTouchUpInside]; } break; default: break; } if (!cell) { cell = [[UITableViewCell alloc] init]; } return (UITableViewCell*)cell; } #pragma mark - UITextViewDelegate - (void)textViewDidBeginEditing:(UITextView *)textView { self.reframeTextView = textView; [self replaceInputTextviewUponAddView:textView]; } - (void) textViewDidChange:(UITextView *)textView { id item = [self.viewModel modelItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:textView.tag]]; if ([item isKindOfClass:[FKCirclePublicTextItem class]]) { FKCirclePublicTextItem *textItem = (FKCirclePublicTextItem*)item; textItem.text = textView.text; } else if ([item isKindOfClass:[FKCirclePublicImageItem class]]) { FKCirclePublicImageItem *imageItem = (FKCirclePublicImageItem*)item; imageItem.imageDesc = textView.text; } [self.tableView beginUpdates]; [self.tableView endUpdates]; [self replaceInputTextviewUponAddView:textView]; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [textView resignFirstResponder]; return NO; } return YES; } #pragma mark - KeyboardNotification - (void)keyboardWillChange:(NSNotification *)notification { if ([notification.name isEqualToString:UIKeyboardWillShowNotification]) { [self showBoardViewWithNotification:notification]; } else if ([notification.name isEqualToString:UIKeyboardWillHideNotification]){ [self dismissBoardViewWithNotification:notification]; } } - (void)showBoardViewWithNotification:(NSNotification *)notification { CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; CGRect endRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; UIViewAnimationOptions curve = (UIViewAnimationOptions)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; self.keyboardHeight = CGRectGetHeight(endRect); if (!IS_IPHONE_4) { WeakSelf(weakSelf); [UIView animateWithDuration:duration delay:0 options:curve animations:^{ weakSelf.circleAddView.frame = CGRectMake(0 , CGRectGetHeight(weakSelf.view.frame) - CGRectGetHeight(endRect) - [FKCircleAddView height] , CGRectGetWidth(weakSelf.circleAddView.bounds) , [FKCircleAddView height]); } completion:^(BOOL finished) { [weakSelf replaceInputTextviewUponAddView:self.reframeTextView]; }]; } else { [self replaceInputTextviewUponAddView:self.reframeTextView]; } } - (void)dismissBoardViewWithNotification:(NSNotification *)notification { CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue]; UIViewAnimationOptions curve = (UIViewAnimationOptions)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; self.keyboardHeight = 0; WeakSelf(weakSelf); [UIView animateWithDuration:duration delay:0 options:curve animations:^ { if (!IS_IPHONE_4) { weakSelf.circleAddView.frame = CGRectMake(0 , CGRectGetHeight(weakSelf.view.frame) - [FKCircleAddView height] , CGRectGetWidth(weakSelf.circleAddView.frame) , [FKCircleAddView height]); } weakSelf.tableView.frame = CGRectMake(0, 0, CGRectGetWidth(weakSelf.tableView.frame), CGRectGetHeight(weakSelf.tableView.frame)); } completion:^(BOOL finished) { }]; } #pragma mark - UIImagePickerControllerDelegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){ UIImage *sourceImage = [info objectForKey:([picker allowsEditing] ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage)]; FKCirclePublicImageItem *item = [[FKCirclePublicImageItem alloc] init]; item.sourceImage = sourceImage; if (sourceImage.size.width > FKCIRCLE_PUBLIC_IMAGE_LENGTH) { CGSize size = CGSizeMake(FKCIRCLE_PUBLIC_IMAGE_LENGTH, (FKCIRCLE_PUBLIC_IMAGE_LENGTH/sourceImage.size.width)*sourceImage.size.height); UIImage *scaleImage = [FLImageHelper imageWithImage:sourceImage scaledToSize:size]; item.displayImage = scaleImage; } else { item.displayImage = sourceImage; } [self.viewModel.modelMutArray addObject:item]; [self.tableView reloadData]; [self scrollTableViewToBottom]; } [picker dismissViewControllerAnimated:YES completion:^{ }]; } - (void)imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{ if (paramError) { [FLProgressHUDHelper showText:paramError.localizedDescription inView:self.view]; } } #pragma mark - FKCirclePhotoClipDelegate - (void)controller:(FKCirclePhotoClipController *)controller didFinishClipImage:(UIImage *)image { NSInteger tag = controller.view.tag; id item = [self.viewModel modelItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:tag]]; if ([item isKindOfClass:[FKCirclePublicImageItem class]]) { FKCirclePublicImageItem *imageItem = (FKCirclePublicImageItem*)item; imageItem.displayImage = image; imageItem.photoURL = nil; [self.tableView reloadData]; } } #pragma mark - Action - (FKCirclePublicImageCellClickCallback)clickButtonOnImageCell { WeakSelf(weakSelf); return ^(FKCirclePublicImageCellButton btnType, NSIndexPath *indexPath){ id item = [weakSelf.viewModel modelItemAtIndexPath:indexPath]; if (![item isKindOfClass:[FKCirclePublicImageItem class]]) { return ; } FKCirclePublicImageItem *imageItem = (FKCirclePublicImageItem*)item; switch (btnType) { case FKCirclePublicImageCellButtonDelete: { [weakSelf.viewModel removeModelItemAtIndexPath:indexPath]; [weakSelf.tableView reloadData]; break; } case FKCirclePublicImageCellButtonText: { imageItem.palceholder = CIRCLE_PUBLIC_IMAGETEXTVIEW_PALCEHOLDER; [weakSelf.tableView reloadData]; [weakSelf.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO]; FKCirclePublicImageCell *imageCell = [weakSelf.tableView cellForRowAtIndexPath:indexPath]; if ([imageCell isKindOfClass:[FKCirclePublicImageCell class]] && imageItem.imageDesc.length == 0) { weakSelf.responderTextView = imageCell.textView; [weakSelf delayBecomeFirstResponder]; } break; } case FKCirclePublicImageCellButtonClip: { [weakSelf pushPhotoClipController:imageItem.sourceImage indexPath:indexPath]; break; } default: break; } }; } - (IBAction)clickDeleteButtonOnProductCell:(UIButton *)sender { [self.viewModel removeModelItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sender.tag]]; [self.tableView reloadData]; } - (void)pushPhotoClipController:(UIImage *)sourceImg indexPath:(NSIndexPath *)indexPath { FKCirclePhotoClipController *controller = [[FKCirclePhotoClipController alloc] initWithImage:sourceImg delegate:self]; controller.view.tag = indexPath.section; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; } - (void)pushCircleProductController { FKCircleProductSegmentController *controller = [[FKCircleProductSegmentController alloc] init]; controller.hidesBottomBarWhenPushed = YES; WeakSelf(weakSelf); controller.callback = ^(NSArray *items) { for (FKCircleChoiceProductItem *product in items) { [weakSelf.viewModel.modelMutArray addObject:product]; } [weakSelf.tableView reloadData]; [weakSelf scrollTableViewToBottom]; }; [self.navigationController pushViewController:controller animated:YES]; } - (IBAction)clickRightNavItemAction:(id)sender { NSString *errMSG = [self.viewModel validDataMessage]; if (!errMSG) { FKCircleTagsController *controller = [[FKCircleTagsController alloc] initWithViewModel:self.viewModel]; controller.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:controller animated:YES]; } else { [FLProgressHUDHelper showText:errMSG inView:self.view]; } } #pragma mark - Method - (void)showImageChoiceMenu { [self.view.window addSubview:self.buttonChoiceMenu]; WeakSelf(weakSelf); // [UIView animateWithDuration:0.3 // animations:^ // { weakSelf.buttonChoiceMenu.alpha = 1.0; weakSelf.buttonChoiceMenu.frame = weakSelf.view.window.bounds; // }]; } - (void)hideImageChoiceMenu { WeakSelf(weakSelf); [UIView animateWithDuration:0.3 animations:^ { weakSelf.buttonChoiceMenu.alpha = 0; // weakSelf.buttonChoiceMenu.frame = CGRectMake(0, // CGRectGetMaxY(weakSelf.view.window.bounds), // CGRectGetWidth(weakSelf.view.window.bounds), // CGRectGetHeight(weakSelf.view.window.bounds)); }]; [self.buttonChoiceMenu removeFromSuperview]; } - (void)configKeyboardNotifications { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardDidHideNotification object:nil]; } - (void)replaceInputTextviewUponAddView:(UIView *)view { if (view && self.keyboardHeight > 0) { CGRect rect = [view.superview convertRect:view.frame toView:self.view]; CGFloat offset; if (IS_IPHONE_4) { offset = (CGRectGetMaxY(rect) - (CGRectGetHeight(self.view.frame) - self.keyboardHeight)); } else { offset = (CGRectGetMaxY(rect) - CGRectGetMinY(self.circleAddView.frame)); } if (offset > 0) { [self replaceViewOffsetY:-offset]; } } } - (void)replaceViewOffsetY:(CGFloat)offset { WeakSelf(weakSelf); [UIView animateWithDuration:0.3 animations:^ { CGRect frame = weakSelf.tableView.frame; weakSelf.tableView.frame = CGRectMake(0, CGRectGetMinY(frame) + offset, CGRectGetWidth(frame), CGRectGetHeight(frame)); }]; } - (void)scrollTableViewToBottom { [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:self.viewModel.modelMutArray.count-1] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; } - (void)configRightNaviItem { UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"下一步" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightNavItemAction:)]; [rightItem setTitleTextAttributes:@{NSForegroundColorAttributeName : UIColorFromRGB(0xff6362), NSFontAttributeName : [UIFont systemFontOfSize:16]} forState:UIControlStateNormal]; self.navigationItem.rightBarButtonItem = rightItem; } - (void)delayBecomeFirstResponder { [FKWeakTimerTarget scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(becomeFirstResponder:) userInfo:nil repeats:NO]; } - (IBAction)becomeFirstResponder:(id)sender { if (self.responderTextView) { [self.responderTextView becomeFirstResponder]; self.responderTextView = nil; } } #pragma mark - Layout - (void)addAllSubviews { [self.view addSubview:self.tableView]; [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.top.right.equalTo(self.view); make.bottom.equalTo(self.view).offset(-[FKCircleAddView height]); }]; [self.view addSubview:self.circleAddView]; [self.circleAddView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.bottom.right.equalTo(self.view); make.height.mas_equalTo([FKCircleAddView height]); }]; } #pragma mark - Property - (UITableView *)tableView { if (_tableView == nil) { _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped]; _tableView.dataSource = self; _tableView.delegate = self; _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; _tableView.sectionFooterHeight = 0; _tableView.showsVerticalScrollIndicator = NO; _tableView.backgroundColor = [UIColor whiteColor]; [_tableView registerClass:[FKCirclePublicUserCell class] forCellReuseIdentifier:FKCirclePublicUserCellIdentify]; [_tableView registerClass:[FKCirclePublicTextCell class] forCellReuseIdentifier:FKCirclePublicProductDescCellIdentify]; [_tableView registerClass:[FKCirclePublicImageCell class] forCellReuseIdentifier:FKCirclePublicImageCellIdentify]; [_tableView registerClass:[FKCirclePublicProcuctCell class] forCellReuseIdentifier:FKCirclePublicProductCellIdentify]; } return _tableView; } - (FKCircleAddView *)circleAddView { if (!_circleAddView) { _circleAddView = [FKCircleAddView new]; _circleAddView.backgroundColor = UIColorFromRGB(0xeeeeee); WeakSelf(weakSelf); _circleAddView.clickCallback = ^(NSInteger idx) { [weakSelf.view endEditing:NO]; if (idx == 0) { [weakSelf showImageChoiceMenu]; } else if (idx == 1) { [weakSelf pushCircleProductController]; } }; } return _circleAddView; } - (FKButtonChoiceMenu *)buttonChoiceMenu { if (!_buttonChoiceMenu) { _buttonChoiceMenu = [[FKButtonChoiceMenu alloc] initWithSectionTitles:@[@"拍照", @"从手机相册选择"] cancelTitle:@"取消"]; _buttonChoiceMenu.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5]; _buttonChoiceMenu.alpha = 0; _buttonChoiceMenu.frame = CGRectMake(0, CGRectGetMinY(self.view.window.bounds), CGRectGetWidth(self.view.window.bounds), CGRectGetHeight(self.view.window.bounds)); WeakSelf(weakSelf); _buttonChoiceMenu.clickCallback = ^(NSInteger idx) { switch (idx) { case 0: { [weakSelf hideImageChoiceMenu]; break; } case 1: { [weakSelf hideImageChoiceMenu]; [FLControllerHelper launchAppCamera:weakSelf type:UIImagePickerControllerSourceTypePhotoLibrary]; break; } case 2: { [weakSelf hideImageChoiceMenu]; [FLControllerHelper launchAppCamera:weakSelf type:UIImagePickerControllerSourceTypeCamera]; break; } default: break; } }; } return _buttonChoiceMenu; } - (FKCirclePublicViewModel *)viewModel { if (!_viewModel) { _viewModel = [FKCirclePublicViewModel new]; } return _viewModel; } @end