ECModifyingGroupViewController.m 32.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
//
//  ECModifyingGroupViewController.m
//  EducationContact
//
//  Created by Apple on 2022/8/1.
//

#import "ECModifyingGroupViewController.h"
#import "ECModifyingGroupCollCell.h"
#import "CSHTTPSessionManager+GroupIM.h"
#import "CSHTTPSessionManager+IOLogin.h"
#import "ECGroupInfoModel.h"
#import "IQKeyboardManager.h"
#import "TZImagePickerController.h"
#import "ECModifyImgCollCell.h"
#import "YBImageBrowser.h"
#import "YBIBImageData.h"
#import "YBIBVideoData.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ECModifyingGroupViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ECModifyingGroupCollCellDelete,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIGestureRecognizerDelegate>

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) ECGroupInfoModel * data_model;
@property (nonatomic,strong) UIImagePickerController *imagePicker;
@property (nonatomic,strong) NSMutableDictionary *uploadParams;

//@property (nonatomic,strong) NSMutableArray *modImgMutArray;

@end

@implementation ECModifyingGroupViewController

//-(NSMutableArray *)modImgMutArray
//{
//    if (!_modImgMutArray) {
//        _modImgMutArray = [NSMutableArray array];
//    }
//    return _modImgMutArray;
//}

-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]init];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"修改群资料";
    [self creatHeaderView];
    [self creatView];
    [self requesData];
}

- (void)requesData {
    MJWeakSelf;
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:userToken,@"token",self.groupID,@"group_id", nil];
    
    [[CSHTTPSessionManager sharedManager]conversationGroupSettingsPageWithParams:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        NSInteger code = [responseObject[@"code"] intValue];
        if (code == 1) {
            ECGroupInfoModel * model = [[ECGroupInfoModel alloc]initWithDictionary:responseObject[@"data"]];
            weakSelf.data_model = model;
            [weakSelf setDefaultData];
            [weakSelf.collectionView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
-(void)setDefaultData{
    self.textField.text = self.data_model.GroupName;
    self.textView.text = self.data_model.GroupCon;
}

-(void)creatHeaderView{
    
    UILabel *lab ;
    UIView *garyView;
    lab = [[UILabel alloc]init];
    lab.textAlignment = NSTextAlignmentLeft;
    lab.textColor = COLOR_WITH_HEX(0x3D4447);
    lab.font = [UIFont systemFontOfSize:14];
    [self.headerView addSubview:lab];
    lab.sd_layout.leftSpaceToView(self.headerView, 16).topSpaceToView(self.headerView, 14).widthIs(60).heightIs(20);
    lab.text = @"群名称";
    
    self.textField = [[UITextField alloc]init];
    self.textField.textColor = COLOR_WITH_HEX(0xB1BDC2);
    self.textField.font = [UIFont systemFontOfSize:12];
    self.textField.textAlignment = NSTextAlignmentRight;
    [self.headerView addSubview:self.textField];
    self.textField.sd_layout.rightSpaceToView(self.headerView, 16).centerYEqualToView(lab).widthIs(220).heightIs(30);
    
    garyView = [[UIView alloc]init];
    garyView.backgroundColor = COLOR_WITH_HEX(0xEBEDF0);
    [self.headerView addSubview:garyView];
    garyView.sd_layout.leftSpaceToView(self.headerView, 0).rightSpaceToView(self.headerView, 0).topSpaceToView(lab, 14).heightIs(1);
    
    lab = [[UILabel alloc]init];
    lab.textAlignment = NSTextAlignmentLeft;
    lab.textColor = COLOR_WITH_HEX(0x3D4447);
    lab.font = [UIFont systemFontOfSize:14];
    [self.headerView addSubview:lab];
    lab.sd_layout.leftSpaceToView(self.headerView, 16).topSpaceToView(garyView, 14).widthIs(60).heightIs(20);
    lab.text = @"群简介";
    
    garyView = [[UIView alloc]init];
    garyView.backgroundColor = COLOR_WITH_HEX(0xF5F8FA);
    [self.headerView addSubview:garyView];
    garyView.sd_layout.leftSpaceToView(self.headerView, 16).rightSpaceToView(self.headerView, 16).topSpaceToView(self.headerView, 94).heightIs(126);
    [garyView.layer setMasksToBounds:YES];
    [garyView.layer setCornerRadius:12];
    
    self.textView = [[UITextView alloc]init];
    self.textView.backgroundColor = [UIColor clearColor];
    self.textView.font = [UIFont systemFontOfSize:13];
    self.textView.textColor = COLOR_WITH_HEX(0x6B767B);
    [garyView addSubview:self.textView];
    self.textView.sd_layout.leftSpaceToView(garyView, 12).rightSpaceToView(garyView, 12).topSpaceToView(garyView, 12).bottomSpaceToView(garyView, 12);
    
    garyView = [[UIView alloc]init];
    garyView.backgroundColor = COLOR_WITH_HEX(0xF5F8FA);
    [self.headerView addSubview:garyView];
    garyView.sd_layout.leftSpaceToView(self.headerView, 0).rightSpaceToView(self.headerView, 0).topSpaceToView(lab, 154).heightIs(8);
    
    lab = [[UILabel alloc]init];
    lab.textAlignment = NSTextAlignmentLeft;
    lab.textColor = COLOR_WITH_HEX(0x3D4447);
    lab.font = [UIFont systemFontOfSize:14];
    [self.headerView addSubview:lab];
    lab.sd_layout.leftSpaceToView(self.headerView, 16).topSpaceToView(garyView, 16).widthIs(60).heightIs(20);
    lab.text = @"群关键词";
    
}

-(void)creatView{
    //1、创建流式布局(从上到下,从左到右的布局)
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    //5、设置可重用单元格标识与单元格类型
    [self.collectionView registerClass:[ECModifyingGroupCollCell class] forCellWithReuseIdentifier:@"ECModifyingGroupCollCell"];
    [self.collectionView registerClass:[ECModifyImgCollCell class] forCellWithReuseIdentifier:@"ECModifyImgCollCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader] ) {
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                withReuseIdentifier:@"UICollectionViewHeader"
                                                                                       forIndexPath:indexPath];
        [headView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if (indexPath.section == 0) {
            //删除
            [headView addSubview:self.headerView];
            self.headerView.frame = CGRectMake(0, 0, self.view.width, 248+48 - 16);
        }else{
            
            UILabel *lab ;
            UIView *garyView;
            
            garyView = [[UIView alloc]init];
            garyView.backgroundColor = COLOR_WITH_HEX(0xEBEDF0);
            [headView addSubview:garyView];
            garyView.sd_layout.leftSpaceToView(headView, 0).rightSpaceToView(headView, 0).topSpaceToView(headView, 14).heightIs(8);
            
            lab = [[UILabel alloc]init];
            lab.textAlignment = NSTextAlignmentLeft;
            lab.textColor = COLOR_WITH_HEX(0x3D4447);
            lab.font = [UIFont systemFontOfSize:14];
            [headView addSubview:lab];
            lab.sd_layout.leftSpaceToView(headView, 16).topSpaceToView(garyView, 16).widthIs(80).heightIs(20);
            lab.text = @"群相册";
        }
        
        return headView;
    }else{
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
        [footerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if (indexPath.section ==0) {
            footerView.backgroundColor = [UIColor whiteColor];

        }else{
            footerView.backgroundColor = COLOR_WITH_HEX(0xF5F8FA);
            UIButton *completeBtn = [[UIButton alloc]init];
            [completeBtn setTitle:@"完成" forState:UIControlStateNormal];
            [completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            completeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            completeBtn.backgroundColor = COLOR_WITH_HEX(0x26D2F8);
            [footerView addSubview:completeBtn];
            completeBtn.sd_layout.leftSpaceToView(footerView, 16).rightSpaceToView(footerView, 16).centerYEqualToView(footerView).heightIs(44);
            [completeBtn.layer setMasksToBounds:YES];
            [completeBtn.layer setCornerRadius:22];
            [completeBtn addTarget:self action:@selector(completeBtn:) forControlEvents:UIControlEventTouchUpInside];

        }
        return footerView;
    }
}




- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(self.view.frame.size.width,260 +16);
    }
    else {
        return CGSizeMake(self.view.frame.size.width, 44 + 16);
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(self.view.width, 1);

    }
    return CGSizeMake(self.view.width, 100);
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.data_model.GroupKeywords.count+1;
    }else{
        return self.data_model.GroupImages.count+1;

    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        ECModifyingGroupCollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ECModifyingGroupCollCell" forIndexPath:indexPath];
        cell.deletegate  = self;
        if (indexPath.row == self.data_model.GroupKeywords.count) {
            cell.deleBtn.hidden = YES;
            cell.defImg = [UIImage imageNamed:@"add_1"];
        }else{
            cell.deleBtn.hidden = NO;
            cell.titleModel = self.data_model.GroupKeywords[indexPath.row];
        }
        cell.tag = indexPath.row + 100;
        cell.deleBtn.tag = 200+indexPath.row;
        [cell.deleBtn addTarget:self action:@selector(titleDeleteBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        ECModifyImgCollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ECModifyImgCollCell" forIndexPath:indexPath];
        if (indexPath.row == self.data_model.GroupImages.count) {
            cell.deleBtn.hidden = YES;
            cell.defImg = [UIImage imageNamed:@"add_2"];

        }else{
            cell.deleBtn.hidden = NO;
            cell.imgModel =self.data_model.GroupImages[indexPath.row];
        
        }
        cell.deleBtn.tag = 300+indexPath.row;
        [cell.deleBtn addTarget:self action:@selector(ImgDeleteBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
-(void)titleDeleteBtn:(UIButton *)btn
{
    NSMutableArray *mutArray = [NSMutableArray arrayWithArray:self.data_model.GroupKeywords];
    [mutArray removeObjectAtIndex:btn.tag - 200];
    self.data_model.GroupKeywords = [mutArray copy];
    [self.collectionView reloadData];
}
-(void)ImgDeleteBtn:(UIButton *)btn
{

    [self.data_model.GroupImages removeObjectAtIndex:btn.tag - 300];
    [self.collectionView reloadData];
    
}

-(void)baclCellStr:(NSString *_Nullable)str andImgStr:(NSString * _Nullable)imgStr andTag:(NSInteger)tag{
    
    NSMutableArray *mutArray = [NSMutableArray arrayWithArray:self.data_model.GroupKeywords];
    [mutArray replaceObjectAtIndex:tag - 100 withObject:str];
    self.data_model.GroupKeywords = [mutArray copy];
    
}

/**
 点击某个cell
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击了第%ld分item",(long)indexPath.item);
    if (indexPath.section == 0) {
        if (indexPath.row == self.data_model.GroupKeywords.count) {
            NSMutableArray *mutArray = [NSMutableArray arrayWithArray:self.data_model.GroupKeywords];
            [mutArray addObject:@""];
            self.data_model.GroupKeywords = [mutArray copy];
            [self.collectionView reloadData];
        }
      
    }
    if (indexPath.section == 1) {
        __weak typeof(self) weakSelf = self;

        if (indexPath.row == self.data_model.GroupImages.count) {
            UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            }];
            
            
            UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                ///相机
//                weakSelf.imgManager.needEditing = @"NO";
//                weakSelf.imgManager.isVideo = YES;
//                [weakSelf.imgManager openCamera];
                [self photo];
            }];
            
            [camera setValue:[UIColor blackColor] forKey:@"titleTextColor"];
            
            UIAlertAction *picture = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                ///相册

                [weakSelf openPhotoAlbum];
            }];
            [picture setValue:[UIColor blackColor] forKey:@"titleTextColor"];
            [alertVc addAction:cancle];
            [alertVc addAction:camera];
            [alertVc addAction:picture];
            [self presentViewController:alertVc animated:YES completion:nil];
        }
        else{
            NSMutableArray *mutArray = [NSMutableArray array];
            for (int i = 0 ; i<self.data_model.GroupImages.count; i++) {
                ECGroupImagesModel *model = self.data_model.GroupImages[i];
                if ([model.type isEqualToString:@"video"]) {
                    if (model.pathStr != nil) {
                        YBIBVideoData *data2 = [[YBIBVideoData alloc]init];;
                        data2.videoURL = [NSURL fileURLWithPath:model.pathStr];
                        data2.projectiveView = self.view;
                        [mutArray addObject:data2];
                    }else{
                        YBIBVideoData *data2 = [[YBIBVideoData alloc]init];;
                        data2.videoURL = [NSURL URLWithString:model.cdnUrl];
                        data2.projectiveView = self.view;
                        [mutArray addObject:data2];
                    }
                    
                }else{
                    if (model.img != nil) {
                        YBIBImageData *data0 = [[YBIBImageData alloc]init];
                        data0.image = ^UIImage * _Nullable{
                            return model.img;
                        };
                        //= model.img;
                        data0.projectiveView = self.view;
                        [mutArray addObject:data0];
                    }else{
                        if (model.cdnUrl != nil) {
                            YBIBImageData *data1 = [YBIBImageData new];
                            data1.imageURL =[NSURL URLWithString:model.cdnUrl];
                            data1.projectiveView = self.view;
                            [mutArray addObject:data1];
                        }
                       
                    }
                }
            }
            
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = [mutArray copy];
            browser.currentPage = indexPath.row;
            [browser show];
        }
    }
}

-(void)photo{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //录制视频时长,默认10s
    imagePickerController.videoMaximumDuration = 60;
    
    //相机类型(拍照、录像...)字符串需要做相应的类型转换
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
    
    //视频上传质量
    //UIImagePickerControllerQualityTypeHigh高清
    //UIImagePickerControllerQualityTypeMedium中等质量
    //UIImagePickerControllerQualityTypeLow低质量
    //UIImagePickerControllerQualityType640x480
    imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    
    //设置摄像头模式(拍照,录制视频)为录像模式
    imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    
    // 是否编辑拍完的图片
    imagePickerController.allowsEditing = NO;
    // 仅当 sourceType 为 UIImagePickerControllerSourceTypeCamera 时,相机添加才可用。
    //  _imagePickerController.showsCameraControls = YES;//可设置一个视图来覆盖预览视图
    //  _imagePickerController.cameraOverlayView = nil;//可设置一个视图来覆盖预览视图
    
    // UIImagePickerControllerCameraCaptureModePhoto
    // UIImagePickerControllerCameraCaptureModeVideo
    imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    
    // UIImagePickerControllerCameraDeviceRear  //后摄像头
    // UIImagePickerControllerCameraDeviceFront //前摄像头
    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    
    // cameraFlashMode 控制当 cameraCaptureMode 为 Photo 时的静止图像闪光。 当 cameraCaptureMode 为 Video 时,cameraFlashMode 控制视频手电筒。
    // UIImagePickerControllerCameraFlashModeOff  = -1,
    // UIImagePickerControllerCameraFlashModeAuto = 0,
    // UIImagePickerControllerCameraFlashModeOn   = 1
    imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    
    
    [self presentViewController:imagePickerController animated:YES completion:nil];
}


//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
        UIImage *img = info[UIImagePickerControllerEditedImage];
        ECGroupImagesModel *model = [[ECGroupImagesModel alloc]init];
        model.img = img;
        [self.data_model.GroupImages addObject:model];
        [self.collectionView reloadData];

//        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

        
    }else{
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];

        //保存视频至相册(异步线程)
        NSString *urlStr = [url path];
        
        ECGroupImagesModel *model = [[ECGroupImagesModel alloc]init];
        model.img = [self getFileThumbnailImage:urlStr];
        model.pathStr = urlStr;
        [self.data_model.GroupImages addObject:model];
        [self.collectionView reloadData];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
                
                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        });

    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(UIImage*)getFileThumbnailImage:(NSString*)videoPath{
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    
    NSParameterAssert(asset);//断言
    
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    NSTimeInterval time = 0.1;
    
    CGImageRef thumbnailImageRef =NULL;
    
    CFTimeInterval thumbnailImageTime = time;
    
    NSError*error =nil;
    
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime,60) actualTime:NULL error:&error];
    
    if( error ) {
        
        NSLog(@"%@", error );
        
    }
    
    if( thumbnailImageRef ) {
        
        return[[UIImage alloc]initWithCGImage:thumbnailImageRef];
        
    }
    
    return nil;

}
#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    if (error) {
        NSLog(@"保存图片过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"图片保存成功.");
    }
}
// 视频保存
// UISaveVideoAtPathToSavedPhotosAlbum(@"videoPath", self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}


-(void)openPhotoAlbum{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.modalPresentationStyle = 0;
    imagePickerVc.allowPickingMultipleVideo = NO;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.naviBgColor = [UIColor blackColor];
    imagePickerVc.iconThemeColor = [UIColor blackColor];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto;
{
    for (UIImage *img in photos) {
        
        ECGroupImagesModel *model = [[ECGroupImagesModel alloc]init];
        model.img = img;
        [self.data_model.GroupImages addObject:model];
    }
    [self.collectionView reloadData];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset{
    __weak typeof(self) weakSelf = self;

    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
        
        ECGroupImagesModel *model = [[ECGroupImagesModel alloc]init];
        model.img = coverImage;
        model.pathStr = outputPath;
        model.type = @"video";
        [weakSelf.data_model.GroupImages addObject:model];
        [weakSelf.collectionView reloadData];
        
    } failure:^(NSString *errorMessage, NSError *error) {
        
    }];

}

/**
 cell的大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(106, 40);
    }else{
        return CGSizeMake(110, 110);
    }
}
/**
 每个分区的内边距(上左下右)
 */
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(16, 16, 16, 16);
}
/**
 分区内cell之间的最小行间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 16;
}
/**
 分区内cell之间的最小列间距
 */
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 4;
}

-(void)completeBtn:(UIButton *)btn
{
    if ([self.textField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"群昵称不能为空!"];
        return;
    }
    self.uploadParams = [NSMutableDictionary dictionary];
    [self.uploadParams setValue:self.textField.text forKey:@"group_name"];
    [self.uploadParams setValue:self.textView.text forKey:@"group_con"];
    [self.uploadParams setValue:userToken forKey:@"token"];

    [self uploadImgs];
}

- (void)uploadImgs {
    
   
    
    
    dispatch_group_t group =  dispatch_group_create();
    [MBProgressHUD showMessage:@"图片上传中..." toView:self.view];
    NSMutableArray *urlMutArray = [NSMutableArray array];
    for (int i = 0; i < self.data_model.GroupImages.count; i++) {
        ECGroupImagesModel *models = self.data_model.GroupImages[i];
        if (models.img == nil && models.pathStr ==nil) {
            [urlMutArray addObject:models.cdnUrl];
        }else{
            if (models.pathStr == nil) {
                UIImage *photo = models.img;
                NSData *imageData = UIImageJPEGRepresentation(photo,0.75);
                NSDictionary *dic = @{
                    @"token": @"",//RSSession.sharedSession.token,
                    @"file": imageData
                };
                
                dispatch_group_enter(group);
                [[CSHTTPSessionManager sharedManager]updateParameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
                    [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpg"];
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                    
                    NSInteger code = [responseObject[@"code"] intValue];
                    if (code == 1 ) {
                        
                        NSDictionary *dic = responseObject[@"data"];
                        if (dic != nil) {
                            
                            NSString *path = dic[@"fullurl"];
                            [urlMutArray addObject:path];
                            dispatch_group_leave(group);
                        }
                    } else {
                        [urlMutArray addObject:@""];
                        dispatch_group_leave(group);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"上传失败");
                    [urlMutArray addObject:@""];
                    dispatch_group_leave(group);// 都要移除
                }];
            }else{
                NSDictionary *dic = @{
                    @"token": @"",//RSSession.sharedSession.token,
                    @"file": [self getVideoNameBaseCurrentTime]
                };
                
                dispatch_group_enter(group);
                [[CSHTTPSessionManager sharedManager]updateParameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
                    
                    [formData appendPartWithFileData:[NSData dataWithContentsOfFile:models.pathStr] name:@"file" fileName:[self getVideoNameBaseCurrentTime] mimeType:@"video/mp4"];
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                    
                    NSInteger code = [responseObject[@"code"] intValue];
                    if (code == 1 ) {
                        
                        NSDictionary *dic = responseObject[@"data"];
                        if (dic != nil) {
                            
                            NSString  *path = dic[@"fullurl"];
                            [urlMutArray addObject:path];
                            dispatch_group_leave(group);
                        }
                    } else {
                        [urlMutArray addObject:@""];
                        dispatch_group_leave(group);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    [urlMutArray addObject:@""];
                    dispatch_group_leave(group);// 都要移除
                }];
            }
        }
        
        
        
        
    }
    
    
    
    // 上传头像后 提交修改信息
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view];
        [self upGroupData:urlMutArray];
    });
}
-(void)upGroupData:(NSArray *)array
{
    NSString *urlStr = [array componentsJoinedByString:@","];
    
    if (urlStr.length > 0) {
        [self.uploadParams setValue:urlStr forKey:@"group_images"];
    }
    if (self.data_model.GroupKeywords.count > 0) {
        NSMutableString * keywords = [NSMutableString string];
        for (NSString * keyword in self.data_model.GroupKeywords) {
            if (![keyword isEqualToString:@""] && keyword != nil) {
                [keywords appendString:keyword];
                [keywords appendString:@","];
            }
           
        }
//        NSRange deleteRange = { [keywords length] - 1, 1 };
//        [keywords deleteCharactersInRange:deleteRange];
        [self.uploadParams setValue:keywords forKey:@"group_keywords"];
    }else {
        [self.uploadParams setValue:@"" forKey:@"group_keywords"];
    }
    [self.uploadParams setValue:self.groupID forKey:@"group_id"];
    MJWeakSelf;
    [[CSHTTPSessionManager sharedManager]updateGroupInfoSetWithParams:self.uploadParams success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSInteger code = [responseObject[@"code"] intValue];
        NSLog(@"%@",responseObject);
        if (code == 1) {
            [MBProgressHUD showSuccess:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if(weakSelf.callBack) {
                    weakSelf.callBack();
                }
                [weakSelf.navigationController popViewControllerAnimated:true];
            });
        }else {
            NSString * msg = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
            [MBProgressHUD showError:msg];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}


//以当前时间合成视频名称
- (NSString *)getVideoNameBaseCurrentTime {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
    
    return [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:@".mp4"];
}

/*
#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