CNLiveBackgroundImageController.m 13.3 KB
//
//  CNLiveBackgroundImageController.m
//  CNLiveSettingModule
//
//  Created by 153993236@qq.com on 11/12/2019.
//  Copyright (c) 2019 153993236@qq.com. All rights reserved.
//

#import "CNLiveBackgroundImageController.h"
#import "MJExtension.h"
#import <SDWebImage/SDWebImage.h>
#import "QMUIKit.h"

#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "XFCameraController.h"
#import "TZImagePickerController.h"
#import "CNLiveBusinessTools.h"
#import "CNLiveSettingModel.h"
#import "CNLiveSettingCell.h"
#import "CNLiveServices.h"
#import "CNLiveSettingNavigationBar.h"

@interface CNLiveBackgroundImageController ()
<UITableViewDelegate, UITableViewDataSource, CNLiveSettingNavigationBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>{
    UIImage *_selectedImage;// 当 isSettingAll为 YES 才需要用到
}
@property (nonatomic, strong) CNLiveSettingNavigationBar *navigationBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *setting;
@property (nonatomic, strong) NSMutableArray *data;

@end

@implementation CNLiveBackgroundImageController
static const NSInteger timeValue = 1.5;

#pragma mark - 加载数据
- (void)loadData {
    NSArray *data = @[
                      @{
                          @"style":@"1",
                          @"title":@"从手机相册选择",
                          @"height":@"60",
                          @"lineHeight":@"10"
                          },
                      @{
                          @"style":@"1",
                          @"title":@"拍一张",
                          @"height":@"60",
                          @"lineHeight":@"10"
                          },
                      
                      
                      ];
    for(NSDictionary *dic in data){
        [self.data addObject:[CNLiveSettingModel mj_objectWithKeyValues:dic]];
    }
    [self.tableView reloadData];
    
}

#pragma mark - 生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

    [self createSubViews];
    [self loadData];
    
}

- (void)dealloc {
    
    
}

- (void)createSubViews {
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.setting];

}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CNLiveSettingModel *model = self.data[indexPath.row];
    return model.height;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CNLiveSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:kCNLiveSettingCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CNLiveSettingModel *model = self.data[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        picker.allowPickingVideo = NO;
        picker.allowPreview = NO;
        __weak typeof(self) weakSelf = self;
        [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(!strongSelf) return ;
            if (strongSelf.isSettingAll) {
                strongSelf->_selectedImage = [photos firstObject];
            }
            else{
                [strongSelf saveImage:[photos firstObject]];
            }
        }];
        [self presentViewController:picker animated:YES completion:nil];
    
    }
    else if(indexPath.row == 1){
        XFCameraController *cameraController = [[XFCameraController alloc] init];
        cameraController.isCanShootVideo = NO;
        cameraController.modalPresentationStyle = UIModalPresentationFullScreen;
        __weak XFCameraController *weakCameraController = cameraController;
        __weak typeof(self) weakSelf = self;
        cameraController.takePhotosCompletionBlock = ^(UIImage *image, NSError *error) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(!strongSelf) return ;
            if (strongSelf.isSettingAll) {
                strongSelf->_selectedImage = image;
            }
            else{
                [strongSelf saveImage:image];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
               [weakCameraController dismissViewControllerAnimated:YES completion:nil];
            });
        };
        [self presentViewController:cameraController animated:YES completion:nil];
    
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)data {
    if (!_data) {
        _data = [NSMutableArray array];
    }
    return _data;
}

- (CNLiveSettingNavigationBar *)navigationBar {
    if (!_navigationBar) {
        _navigationBar = [[CNLiveSettingNavigationBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, NavigationContentTop)];
        _navigationBar.backgroundColor = [UIColor whiteColor];
        _navigationBar.delegate = self;
        _navigationBar.title.text = @"聊天背景";
        _navigationBar.right = nil;
    }
    return _navigationBar;
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavigationContentTop, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationContentTop-50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1.0];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[CNLiveSettingCell class] forCellReuseIdentifier:kCNLiveSettingCell];
    }
    return _tableView;
}
- (UIButton *)setting{
    if(!_setting){
        _setting = [UIButton buttonWithType:UIButtonTypeCustom];
        _setting.frame = CGRectMake(0, SCREEN_HEIGHT-SafeAreaInsetsConstantForDeviceWithNotch.bottom-50, SCREEN_WIDTH, 50);
        _setting.backgroundColor = [UIColor whiteColor];
        _setting.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [_setting setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_setting setTitle:@"将背景应用到所有聊天场景" forState:UIControlStateNormal];
        _setting.adjustsImageWhenHighlighted = NO;
        [_setting addTarget:self action:@selector(settingDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _setting;
}

#pragma mark - 响应方法
- (void)goBack {
    if (self.presentingViewController != nil) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)settingDidClicked:(UIButton *)btn{
    if (_selectedImage == nil) {
        [QMUITips showError:@"请选择图片" inView:self.view hideAfterDelay:timeValue];
         return;
     }
    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"将背景应用到所有聊天场景" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        

    }];
    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
    }];
           
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alertController addAction:sure];
    [alertController addAction:cancel];
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.alertTitleAttributes];
           
    titleAttributs[NSForegroundColorAttributeName] = [UIColor colorWithRed:35/255.0 green:212/255.0 blue:30/255.0 alpha:1.0];
    
    NSMutableDictionary *cancelAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.alertTitleAttributes];
    cancelAttributs[NSForegroundColorAttributeName] = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];

    sure.buttonAttributes = titleAttributs;
    cancel.buttonAttributes = cancelAttributs;

    [alertController showWithAnimated:YES];
    
}

#pragma mark - 私有方法
- (void)saveImage:(UIImage *)image {
    NSData *data = UIImagePNGRepresentation(image);
    if (data.length > 10*1024.0*1024.0) {
        [QMUITips showError:@"图片太大,请重新选择" inView:self.view hideAfterDelay:timeValue];
        return ;
    }
//    NSString *fileName = [NSString stringWithFormat:@"%ld_backgroupImage",(long)[CNLiveTimeTools getNowTimestamp]];
//    NSString *filePath = [[CNLiveBusinessTools chatBackgroupImagefilePath] stringByAppendingPathComponent:fileName];
    NSString *filePath = @"asd";

    [QMUITips showLoadingInView:self.view];
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([data writeToFile:filePath atomically:YES]) {
            if(YES){
//            if ([[CNChatBackgroundImageFMDBManager manager] searchChatBackgroupImage:_user.userId]){
//                //先删除再添加
//                CNChatBackgroupModel *oldModel = [[CNChatBackgroundImageFMDBManager manager] searchChatBackgroupImage:_user.userId];
//                //并删除之前的背景图片
//                NSString *oldFileName = [oldModel.imageFilePath lastPathComponent];
//                if ([[NSFileManager defaultManager] fileExistsAtPath:[[CNLiveBusinessTools chatBackgroupImagefilePath] stringByAppendingPathComponent:oldFileName]]) {
//
//                    [[NSFileManager defaultManager] removeItemAtPath:[[CNLiveBusinessTools chatBackgroupImagefilePath] stringByAppendingPathComponent:oldFileName] error:nil];
//                }
//
//                [[CNChatBackgroundImageFMDBManager manager] deleteChatBackgroupImage:oldModel];
//
//                //保存新的数据
//                CNChatBackgroupModel *newModel = [[CNChatBackgroupModel alloc] init];
//                newModel.receiver = _user.userId;
//                newModel.imageFilePath = filePath;
//                [[CNChatBackgroundImageFMDBManager manager] insertChatBackgroupImage:newModel];
            }
            else {
                //添加新数据
//                CNChatBackgroupModel *model = [[CNChatBackgroupModel alloc] init];
//                model.receiver = _user.userId;
//                model.imageFilePath = filePath;
//                [[CNChatBackgroundImageFMDBManager manager] insertChatBackgroupImage:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllToastInView:weakSelf.view animated:YES];
                NSArray *array = [self.navigationController viewControllers];
                for (UIViewController *vc in array) {
//                    if ([vc isKindOfClass:[CNChatViewController class]]) {
//                        [self.navigationController popToViewController:vc animated:YES];
//                    }
                }
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllToastInView:weakSelf.view animated:YES];
                [QMUITips showError:@"保存失败,请重试" inView:weakSelf.view hideAfterDelay:timeValue];
            });
        }
    });
}
/**
 *  创建图片
 *
 *  @param imageName 图片名字
 *  @param bundleName 图片所在的bundle名字
 *  @param targetClass 类和bundle的同级目录
 *  @return 返回UIImage
 */
- (UIImage *)xw_getImageName:(NSString *)imageName bundleName:(NSString *)bundleName targetClass:(Class)targetClass{
    NSBundle *bundle = [NSBundle bundleForClass:targetClass];
    NSURL *url = [bundle URLForResource:bundleName withExtension:@"bundle"];
    NSBundle *targetBundle = [NSBundle bundleWithURL:url];
    UIImage *image = [UIImage imageNamed:imageName inBundle:targetBundle compatibleWithTraitCollection:nil];
    return image?image:[UIImage imageNamed:imageName inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
}

#pragma mark - CNLiveSettingNavigationBarDelegate
- (void)navigationBar:(CNLiveSettingNavigationBar *)navigationBar actionEvents:(NSString *)actionEvents{
    if ([actionEvents isEqualToString:@"1"]) {
        [self goBack];
    }else if ([actionEvents isEqualToString:@"2"]){
        
    }
}


@end