// // ModelPhotoViewController.m // model // // Created by liufei on 2018/7/25. // Copyright © 2018年 Mine. All rights reserved. // #import "ModelPhotoViewController.h" #import "PhotoCollectionViewCell.h" #import "PhotoModel.h" #import "Masonry.h" #import "UICollectionViewLeftAlignedLayout.h" @interface ModelPhotoViewController () { UIImagePickerController *pickerVc; } @property(nonatomic, strong) UICollectionView *photoListView; @property(nonatomic, strong) NSMutableArray *dataSource; @property(nonatomic, strong) NSMutableArray *tempUrl; @property(nonatomic, strong) NSMutableArray *updateData; @property(nonatomic, strong) NSMutableArray *deleteData; @end @implementation ModelPhotoViewController - (NSMutableArray *)dataSource { if (!_dataSource) { _dataSource = [NSMutableArray array]; } return _dataSource; } - (NSMutableArray *)updateData { if (!_updateData) { _updateData = [NSMutableArray array]; } return _updateData; } - (NSMutableArray *)deleteData { if (!_deleteData) { _deleteData = [NSMutableArray array]; } return _deleteData; } - (NSMutableArray *)tempUrl { if (!_tempUrl) { _tempUrl = [NSMutableArray array]; } return _tempUrl; } - (void)viewDidLoad { [super viewDidLoad]; [self configUI]; [self getModelPhoto]; } - (void)getModelPhoto { [MBProgressHUD showHUDAddedTo:self.view animated:YES]; [YanCNetWorkManager requestGETWithURLStr:Url_getModelPhoto(PublicUrl) parameters:@{@"modelpk": [ModelUser user].modelpk} finish:^(id dataDic) { [MBProgressHUD hideHUDForView:self.view animated:YES]; if ([dataDic[@"msg"] isEqualToString:@"success"]) { for (NSDictionary *dic in dataDic[@"data"]) { PhotoModel *model = [PhotoModel mj_objectWithKeyValues:dic]; [self.dataSource addObject:model]; } [self.photoListView reloadData]; } } enError:^(NSError *error) { }]; } - (void)configUI { self.view.backgroundColor = [UIColor colorWithHexString:@"#F2F4F5"]; self.title = @"照片"; self.navigationController.navigationBar.tintColor = RGBValueColor(0x333333, 1); UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(handleSave)]; rightItem.tintColor = [UIColor blackColor]; self.navigationItem.rightBarButtonItem = rightItem; UICollectionViewFlowLayout *layout = [[UICollectionViewLeftAlignedLayout alloc] init]; self.photoListView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; self.photoListView.delegate = self; self.photoListView.dataSource = self; self.photoListView.backgroundColor = [UIColor clearColor]; [self.photoListView registerNib:[UINib nibWithNibName:@"PhotoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class])]; [self.photoListView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"]; [self.view addSubview:self.photoListView]; [self.photoListView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view); make.bottom.equalTo(self.view); make.left.right.equalTo(self.view); }]; } - (void)backClick { [self.navigationController popViewControllerAnimated:YES]; } #pragma mark -collectionView - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 0) { return CGSizeMake(ScreenWidth - 40, ScreenWidth - 40); } else { return CGSizeMake((ScreenWidth - 50) / 2, (ScreenWidth - 50) / 2); } } - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { return UIEdgeInsetsMake(10, 20, 20, 20); } - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { return 10; } - (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 10; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.dataSource.count + 1; } - (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { return CGSizeMake(ScreenWidth, 35); } - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { if (kind == UICollectionElementKindSectionHeader) { UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath]; for (UIView *view in [headerView subviews]) { [view removeFromSuperview]; } UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, ScreenWidth - 40, 20)]; label.text = @"点击可删除照片(最少上传5张)"; label.font = [UIFont systemFontOfSize:14]; label.textColor = [UIColor colorWithHexString:@"#666666"]; [headerView addSubview:label]; return headerView; } return nil; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class]) forIndexPath:indexPath]; cell.layer.cornerRadius = 8; cell.clipsToBounds = YES; if (indexPath.item < self.dataSource.count) { PhotoModel *model = self.dataSource[indexPath.item]; if (model.localImage) { cell.userImageView.image = model.localImage; } else { [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", PublicUrl, model.photo]]]; } } else { cell.userImageView.image = nil; } return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { if (self.dataSource.count == indexPath.item) { if (self.dataSource.count >= 9) { [MBProgressHUD showSuccess:@"最多不能超过9张"]; } else { UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; pickerVc = [[UIImagePickerController alloc] init]; pickerVc.allowsEditing = YES; pickerVc.delegate = self; UIAlertAction *library = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) { pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:pickerVc animated:YES completion:nil]; }]; UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) { pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:pickerVc animated:YES completion:nil]; }]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; [alertVc addAction:library]; [alertVc addAction:camera]; [alertVc addAction:cancel]; [self presentViewController:alertVc animated:YES completion:nil]; } } else { UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:@"是否确定删除" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) { [self deletePhoto:indexPath.item]; }]; [alertVc addAction:cancelAction]; [alertVc addAction:sureAction]; [self presentViewController:alertVc animated:YES completion:nil]; } } #pragma mark -imagePickerController - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = info[@"UIImagePickerControllerEditedImage"]; [picker dismissViewControllerAnimated:NO completion:nil]; PhotoModel *model = [[PhotoModel alloc] init]; model.localImage = image; NSData *photoData = UIImageJPEGRepresentation(image, 0.5); NSInteger length = [photoData length] / 1000; NSLog(@"图片大小:%ld Kb", (long) length); [self.dataSource addObject:model]; [self.updateData addObject:image]; [self.photoListView reloadData]; [self uploadImage:image]; } - (void)uploadImage:(UIImage *)image { [MBProgressHUD showHUDAddedTo:self.view animated:YES]; [YanCNetWorkManager requestPostWithURLStr:Url_uploadImage(PublicUrl) fileData:image name:@"img" fileName:@"file.jpg" mimeType:@"image/jpeg" parameters:nil finish:^(id dataDic) { [MBProgressHUD hideHUDForView:self.view animated:YES]; [self.tempUrl addObject:dataDic[@"img"]]; } enError:^(NSError *error) { [MBProgressHUD hideHUDForView:self.view animated:YES]; }]; } #pragma mark - - (void)handleSave { [self uploadImageThroughURLs:self.tempUrl]; // [MBProgressHUD showHUDAddedTo:self.view animated:YES]; // dispatch_group_t group = dispatch_group_create(); // // for (NSInteger i = 0; i < self.updateData.count; i++) { // // dispatch_group_enter(group); // // [YanCNetWorkManager requestPostWithURLStr:Url_uploadImage(PublicUrl) fileData:self.updateData[i] name:@"img" fileName:@"file.jpg" mimeType:@"image/jpeg" parameters:nil finish:^(id dataDic) { // // [self.tempUrl addObject:dataDic[@"img"]]; // // NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, dataDic); // dispatch_group_leave(group); // } enError:^(NSError *error) { // NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error); // dispatch_group_leave(group); // }]; // } // [MBProgressHUD hideHUDForView:self.view animated:YES]; // dispatch_group_notify(group, dispatch_get_main_queue(), ^{ // NSLog(@"上传完成!"); // // [self uploadImageThroughURLs:self.tempUrl]; // }); } - (void)uploadImageThroughURLs:(NSMutableArray *)urls { NSString *urlStr = @""; if (urls.count > 0) { urlStr = [urls firstObject]; if (urls.count > 1) { for (int i = 1; i < urls.count; i++) { urlStr = [urlStr stringByAppendingFormat:@",%@", urls[i]]; } } NSDictionary *dic = @{@"modelpk": [ModelUser user].modelpk, @"photo": urlStr}; [YanCNetWorkManager requestPostWithURLStr:Url_addModelPhoto(PublicUrl) parameters:dic finish:^(id dataDic) { if ([dataDic[@"msg"] isEqualToString:@"success"]) { [MBProgressHUD showSuccess:@"保存成功"]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(backClick) userInfo:nil repeats:NO]; } } enError:^(NSError *error) { }]; } else { [MBProgressHUD showSuccess:@"保存成功"]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(backClick) userInfo:nil repeats:NO]; } } - (void)deletePhoto:(NSInteger)index { PhotoModel *model = self.dataSource[index]; if (model.localImage) { for (UIImage *img in self.updateData) { if (img == model.localImage) { [self.updateData removeObject:img]; } } } else { NSDictionary *dic = @{@"modelpk": [ModelUser user].modelpk, @"modelphotopk": model.modelphotopk}; [YanCNetWorkManager requestPostWithURLStr:Url_deleteModelPhoto(PublicUrl) parameters:dic finish:^(id dataDic) { if ([dataDic[@"msg"] isEqualToString:@"success"]) { } } enError:^(NSError *error) { }]; } [self.dataSource removeObjectAtIndex:index]; [self.photoListView reloadData]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #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. } */ @end