FeedbackController.m 14.9 KB
//
//  FeedbackController.m
//  DreamSleep
//
//  Created by peter on 2022/4/22.
//

#import "FeedbackController.h"
#import "MyFeedListController.h"
#import "FeedbackRequestModel.h"
#import "TZImagePickerController.h"
#import "FeedImageCollectionCell.h"

// 最大图片上传数量
static int MaxUpdateImgCount = 3;
// 相册显示列数
static int AlbumColumnCount = 4;

@interface FeedbackController () <MyFeedListControllerDelegate, UITextViewDelegate, TZImagePickerControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate>
@property (strong, nonatomic) UILabel *redLab;
@property (assign, nonatomic) int unreadCount;
@property (strong, nonatomic) UITextView *feedTV;
@property (strong, nonatomic) UICollectionView *imgCollectionView;
@property (strong, nonatomic) UIButton *commitBtn;
@end

@implementation FeedbackController {
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
    BOOL _isSelectOriginalPhoto;
    NSString *_result_imgurls;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"意见反馈";
    self.view.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
    
    _selectedPhotos = [NSMutableArray array];
    _selectedAssets = [NSMutableArray array];
    
    [self setNaviRightItem];
    
    [self.view addSubview:self.feedTV];
    [self.view addSubview:self.imgCollectionView];
    [self.view addSubview:self.commitBtn];
    
    [self layoutUI];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.feedTV endEditing:YES];
}

#pragma mark - MyFeedListControllerDelegate
- (void)didClickMessage {
    if (self.unreadCount == 0) { return; }
    self.unreadCount--;
    self.redLab.text = [NSString stringWithFormat:@"%d", self.unreadCount];
    self.redLab.hidden = self.unreadCount == 0;
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView {
    textView.text = [NSString trimString:textView.text];
}

#pragma mark - 品牌模式
- (NaviStyle)navigationBarStyle {
    return NaviStyleDefault;
}

#pragma mark - Actions
- (void)myFeedAction {
    MyFeedListController *myFeedVC = [[MyFeedListController alloc] initWithDelegate:self];
    [self.navigationController pushViewController:myFeedVC animated:YES];
}

- (void)commitAction {
    if (self.feedTV.text.length == 0) {
        [DSProgressHUD showDetailInfo:@"请输入遇到的问题或建议"];
        return;
    }
    // 发送提交请求
    [DSProgressHUD showProgressHUDWithInfo:@"提交中..."];
    _result_imgurls = _result_imgurls ? _result_imgurls : @"";
    [FeedbackRequestModel adviceFeedbackRequestWithContent:self.feedTV.text contentImg:_result_imgurls completion:^(FeedbackRequestModel * _Nonnull requestModel) {
        [DSProgressHUD dissmissProgressHUD];
        if (requestModel.resCode == DSResCodeSuccess) {
            [DSProgressHUD showDetailInfo:@"已收到您的宝贵建议,谢谢!"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.feedTV endEditing:YES];
}

- (void)getUnreadMessageRequest {
    [FeedbackRequestModel queryUserTotalReplysRequest:^(FeedbackRequestModel * _Nonnull requestModel) {
        if (requestModel.resCode == DSResCodeSuccess) {
            self.unreadCount = requestModel.unreadCount;
            self.redLab.text = [NSString stringWithFormat:@"%d", self.unreadCount];
            self.redLab.hidden = self.unreadCount == 0;
        }
    }];
}

- (void)deleteBtnClick:(UIButton *)sender {
    [_selectedPhotos removeObjectAtIndex:sender.tag];
    [_selectedAssets removeObjectAtIndex:sender.tag];
    
    [self.imgCollectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag inSection:0];
        [self.imgCollectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self.imgCollectionView reloadData];
    }];
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _selectedPhotos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FeedImageCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FeedImageCollectionCell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        cell.imageView.image = nil;
        cell.addIcon.hidden = NO;
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = _selectedPhotos[indexPath.row-1];
        cell.asset = _selectedAssets[indexPath.row-1];
        cell.addIcon.hidden = YES;
        cell.deleteBtn.hidden = NO;
        cell.deleteBtn.tag = indexPath.row - 1;
        [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) { // 打开相册
        [self pushTZImagePickerController];
    } else { // 预览照片或者视频
        id asset = _selectedAssets[(indexPath.row - 1)];
        BOOL isVideo = NO;
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = asset;
            isVideo = phAsset.mediaType == PHAssetMediaTypeVideo;
        }
        
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_selectedAssets selectedPhotos:_selectedPhotos index:(indexPath.row - 1)];
        imagePickerVc.maxImagesCount = MaxUpdateImgCount;
        imagePickerVc.allowPickingOriginalPhoto = YES;
        imagePickerVc.allowPickingMultipleVideo =NO;
        imagePickerVc.showSelectedIndex = YES;
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        WS(weakSelf);
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            self->_selectedPhotos = [NSMutableArray arrayWithArray:photos];
            self->_selectedAssets = [NSMutableArray arrayWithArray:assets];
            self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
            [weakSelf.imgCollectionView reloadData];
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

#pragma mark - TZImagePickerController
- (void)pushTZImagePickerController {
    if (MaxUpdateImgCount <= 0) { return; }
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:MaxUpdateImgCount columnNumber:AlbumColumnCount delegate:self pushPhotoPickerVc:NO];
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    // 设置目前已经选中的图片数组
    if (MaxUpdateImgCount > 1) { imagePickerVc.selectedAssets = _selectedAssets; }
    // 在内部显示拍照按钮
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.iconThemeColor = ColorFromRGBA(31.0, 185.0, 34.0, 1.0);
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [DSWhite colorWithAlphaComponent:0.8];
    // 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    // 是否可以多选视频
    imagePickerVc.allowPickingMultipleVideo = NO;
    // 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    // 设置竖屏下的裁剪尺寸
    NSInteger left = 30;
    NSInteger widthHeight = self.view.width - 2 * left;
    NSInteger top = (self.view.height - widthHeight) / 2;
    imagePickerVc.cropRect = CGRectMake(left, top, widthHeight, widthHeight);
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.autoDismiss = NO;
    // 你可以通过block或者代理,来得到用户选择的照片.
    __weak TZImagePickerController *weakPicker = imagePickerVc;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count) { [self uploadImgsWithPhotos:photos picker:weakPicker]; }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [self.imgCollectionView reloadData];
    
    // 1.打印图片名字
    [self printAssetsName:assets];
    // 2.图片位置信息
    for (PHAsset *phAsset in assets) {
        DSLog(@"location:%@", phAsset.location);
    }
}

// 如果用户选择了一个gif图片,下面的handle会被执行
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset {
    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
    [self.imgCollectionView reloadData];
}

// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    return YES;
}

// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    return YES;
}

#pragma mark - Private
- (void)printAssetsName:(NSArray *)assets {
    /// 打印图片名字
    NSString *fileName;
    for (id asset in assets) {
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = (PHAsset *)asset;
            fileName = [phAsset valueForKey:@"filename"];
        }
    }
}

#pragma mark - 图片上传
- (void)uploadImgsWithPhotos:(NSArray<UIImage *> *)photos picker:(TZImagePickerController *)picker {
    // 1、处理图片
    NSMutableString *mstr = [NSMutableString string];
    [mstr appendString:@"["];
    for (int index = 0; index < photos.count; index++) {
        UIImage *img = photos[index];
        NSString *base64Str = [UIImage imageToBase64Str:img];
        NSString *sepStr = (index == (photos.count - 1)) ? @"" : @",";
        [mstr appendString:[NSString stringWithFormat:@"\"%@\"%@", base64Str, sepStr]];
    }
    [mstr appendString:@"]"];
    // 2、上传图片
    [DSProgressHUD showProgressHUDWithInfo:@""];
    [FeedbackRequestModel uploadBulkImagesWithImgStr:[mstr copy] completion:^(FeedbackRequestModel * _Nonnull requestModel) {
        [DSProgressHUD dissmissProgressHUD];
        if (requestModel.resCode == DSResCodeSuccess) {
            // 存储图片上传成功后返回的urls
            self->_result_imgurls = requestModel.result_imgurls;
            [picker dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}

#pragma mark - lazy
- (UITextView *)feedTV {
    if (!_feedTV) {
        _feedTV = [[UITextView alloc] init];
        _feedTV.dk_backgroundColorPicker = DKColorPickerWithColors(ColorFromHex(0xf0f0f0), CornerViewDarkColor, DSWhite);
        _feedTV.dk_textColorPicker = DKColorPickerWithColors(SubTitleColor, DarkTextColor, DSWhite);
        _feedTV.font = SysFont(14);
        _feedTV.delegate = self;
        [_feedTV cornerRadius:12];
    }
    return _feedTV;
}

- (UICollectionView *)imgCollectionView {
    if (!_imgCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(92, 92);
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _imgCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _imgCollectionView.showsHorizontalScrollIndicator = NO;
        _imgCollectionView.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
        _imgCollectionView.dataSource = self;
        _imgCollectionView.delegate = self;
        _imgCollectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_imgCollectionView registerClass:[FeedImageCollectionCell class] forCellWithReuseIdentifier:@"FeedImageCollectionCell"];
    }
    return _imgCollectionView;
}

- (UIButton *)commitBtn {
    if (!_commitBtn) {
        _commitBtn = [UIButton btnWithTitle:@"提交" titleColor:DSWhite font:BoldFont(16) bgColor:BrandColor];
        [_commitBtn addTarget:self action:@selector(commitAction) forControlEvents:UIControlEventTouchUpInside];
        [_commitBtn cornerRadius:20];
    }
    return _commitBtn;
}

- (void)setNaviRightItem {
    UIView *cusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 105, 32)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cusView];
    
    UIButton *myFeedBtn = [UIButton btnWithTitle:@"      我的反馈      " titleColor:DSWhite font:SysFont(12)];
    [myFeedBtn cornerRadius:13];
    myFeedBtn.layer.borderColor = DSWhite.CGColor;
    myFeedBtn.layer.borderWidth = 1;
    [myFeedBtn addTarget:self action:@selector(myFeedAction) forControlEvents:UIControlEventTouchUpInside];
    [cusView addSubview:myFeedBtn];
    
    [myFeedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(cusView);
        make.top.equalTo(cusView).offset(6);
    }];
    
    UILabel *lab = [UILabel labWithTextColor:DSWhite font:SysFont(12)];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.backgroundColor = DSRed;
    [lab cornerRadius:10];
    lab.hidden = YES;
    self.redLab = lab;
    [cusView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cusView);
        make.top.equalTo(cusView);
        make.width.height.equalTo(@20);
    }];
}

- (void)layoutUI {
    [self.feedTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.right.equalTo(@-15);
        make.top.equalTo(@15);
    }];
    [self.imgCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.feedTV.mas_bottom).offset(26);
        make.left.equalTo(@15);
        make.right.equalTo(@-15);
        make.height.equalTo(@92);
    }];
    [self.commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.imgCollectionView.mas_bottom).offset(60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-91);
        make.size.mas_equalTo(CGSizeMake(155, 40));
    }];
}

@end