//
//  ALCreateTopicController.m
//  GMAlpha
//
//  Created by Q14 on 2018/11/7.
//  Copyright © 2018年 Gengmei. All rights reserved.
//

#import "ALCreateTopicController.h"
#import "ALCreateTopicHeaderView.h"
#import "GMAlbumListViewController.h"
#import "UIViewController+GMExtension.h"
#import "GMEditPhotoController.h"
#import "ALGroupListVController.h"
#import "ALCreateTopicCell.h"
#import "GMPhotoManager.h"
#import "GMEditPhotoInfo.h"
#import "ALCreateTopicListObject.h"
#import "ALTopicListVController.h"
#import "ALCreateTopicViewModel.h"

#define MAX_IMAGE_AND_VIDEO_COUNT 10
#define MAX_VIDEO_COUNT 1

@interface ALCreateTopicController ()<ALCreateTopicHeaderDelegate, GMEditPhotoControllerDelegate>

@property (nonatomic, strong) ALCreateTopicViewModel *viewModel;

@property (nonatomic, strong) ALCreateTopicHeaderView *headerView;
//@property (nonatomic, strong) ALCreateDiaryObject *diaryObj;
@property (strong, nonatomic) GMPhotoManager *manager;
/** 是否有选中的小组 */
@property (nonatomic, assign) BOOL isSelect;
/** 小组详情页进来的不需要显示现在列表 */
@property (nonatomic, assign) FromWhereComeIn fromType;
/** 统计需要的字段,从哪里进来的标识 */
@property (nonatomic, copy) NSString *fromStr;

@end

@implementation ALCreateTopicController

@synthesize viewModel;

- (instancetype)initWithComeInType:(FromWhereComeIn)type from:(NSString *)from
{
    if(self = [super init])
    {
        self.fromType = type;
        self.fromStr = from;
        self.pageName = @"topic_create";
        [self initController];
    }
    return self;
}

- (void)initController {
    [super initController];
    _needHeaderRefresh = NO;
    _needFooterRefresh = NO;
    self.viewModel = [[ALCreateTopicViewModel alloc] initWithType:self.fromType];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.navigationBar.rightIcon = @"fa_bu";

    self.table.tableHeaderView = self.headerView;
    [self hideLoading];
    [_table registerCell:[ALCreateTopicCell class]];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.fromType == FromWhereComeInDetail)
    {
        return 0;
    }
    else
    {
        return self.viewModel.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ALCreateTopicCell *cell = [tableView dequeueCell:[ALCreateTopicCell class] forIndexPath:indexPath];
    cell.object = self.viewModel.dataArray[indexPath.row];
    if (self.fromType == FromWhereComeInFace || self.fromType == FromWhereComeInCard) {
        self.isSelect = YES;
        cell.selectButton.selected = YES;
        self.viewModel.diaryObj.groupId = cell.object.id;
    }
    if (indexPath.row == self.viewModel.dataArray.count - 1)
    {
        cell.bottomLine.hidden  = YES;
    }
    else
    {
        cell.bottomLine.hidden  = NO;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.fromType == FromWhereComeInFace || self.fromType == FromWhereComeInCard) {
        return;
    }
    ALCreateTopicCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectButton.selected = !cell.selectButton.selected;
    ALCreateTopicListObject *model = self.viewModel.dataArray[indexPath.row];
    if (cell.selectButton.selected) {
        self.viewModel.diaryObj.groupId = model.id;
        self.isSelect = YES;
    }
    else
    {
        self.viewModel.diaryObj.groupId = nil;
        self.isSelect = NO;
    }
    [Phobos track:@"topic_create_click_choose_group" attributes:@{@"group_id": SafeString(model.id)}];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.fromType == FromWhereComeInFace || self.fromType == FromWhereComeInCard) {
        return;
    }
    ALCreateTopicCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //如果是选中的则需要不选中
    //如果是不选中的则不需要走这个方法了
    if (cell.selectButton.selected)
    {
        cell.selectButton.selected = !cell.selectButton.selected;
    }
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    
    [self hideEmptyView];
}

#pragma mark - Getter
- (GMPhotoManager *)manager
{
    if (!_manager) {
        _manager = [[GMPhotoManager alloc] initWithType:GMPhotoManagerSelectedTypePhotoAndVideo];
        _manager.configuration.deleteTemporaryPhoto = NO;
        _manager.configuration.lookLivePhoto = NO;
        _manager.configuration.saveSystemAblum = YES;
        _manager.configuration.themeColor = UIColor.whiteColor;
        __weak typeof(self) weakSelf = self;
        _manager.configuration.movableCropBox = NO;
        _manager.configuration.movableCropBoxEditSize = NO;
        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        _manager.configuration.cellSelectedTitleColor = nil;
        _manager.configuration.navBarBackgroudColor = UIColor.whiteColor;
        _manager.configuration.sectionHeaderTranslucent = YES;
        _manager.configuration.cellSelectedBgColor = [[UIColor whiteColor] colorWithAlphaComponent:0.44];
        _manager.configuration.selectedTitleColor = nil;
        _manager.configuration.sectionHeaderSuspensionBgColor = nil;
        _manager.configuration.sectionHeaderSuspensionTitleColor = nil;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.openCamera = YES;
        // 使用自动的相机  这里拿系统相机做示例
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, GMPhotoConfigurationCameraType cameraType, GMPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == GMPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == GMPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
        
        _manager.configuration.photoCanEdit = NO;
    }
    return _manager;
}

- (ALCreateTopicHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ALCreateTopicHeaderView alloc] init];
        _headerView.frame = CGRectMake(0, 0, MAINSCREEN_WIDTH, 326);
        _headerView.delegate = self;
    }
    return _headerView;
}
#pragma mark - delegare
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    GMPhotoModel *model;
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        model = [GMPhotoModel photoModelWithImage:image];
        if (self.manager.configuration.saveSystemAblum) {
//            [GMPhotoTools savePhotoToCustomAlbumWithName:self.manager.configuration.customAlbumName photo:model.thumbPhoto];
        }
    }else  if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *url = info[UIImagePickerControllerMediaURL];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
        float second = 0;
        second = urlAsset.duration.value/urlAsset.duration.timescale;
        model = [GMPhotoModel photoModelWithVideoURL:url videoTime:second];
        if (self.manager.configuration.saveSystemAblum) {
//            [GMPhotoTools saveVideoToCustomAlbumWithName:self.manager.configuration.customAlbumName fileURL:url];
        }
    }
    if (self.manager.configuration.useCameraComplete) {
        self.manager.configuration.useCameraComplete(model);
    }
}

- (void)updateOtherUIData
{
    [super updateOtherUIData];
    
    //有数据不隐藏
    if (self.viewModel.dataArray.count)
    {
        self.headerView.isHideLabel = NO;
        //从详情进来隐藏掉（因为是当前小组）
        if(self.fromType == FromWhereComeInDetail)
        {
            self.headerView.isHideLabel = YES;
        }
    }
    else
    {
        //没有数据直接隐藏
        self.headerView.isHideLabel = YES;
    }
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - ALCreateTopicHeaderDelegate
- (void)addPicturesOrVideo {
     [self.manager clearSelectedList];
    __weak __typeof(self)weakSelf = self;
    NSInteger videoCount = self.headerView.object.videoModel.fileURL ? 1 : 0;
    NSInteger imageCount = self.headerView.object.images.count;
    self.manager.configuration.maxNum = MAX_IMAGE_AND_VIDEO_COUNT -   - videoCount;
    self.manager.configuration.videoMaxNum = (MAX_VIDEO_COUNT - videoCount);
    self.manager.configuration.photoMaxNum = (MAX_IMAGE_AND_VIDEO_COUNT - MAX_VIDEO_COUNT - imageCount);
    
    [self gm_presentAlbumListViewControllerWithManager:self.manager done:^(NSArray<GMPhotoModel *> *allList, NSArray<GMPhotoModel *> *photoList, NSArray<GMPhotoModel *> *videoList, NSArray<UIImage *> *imageList, BOOL original, GMAlbumListViewController *viewController) {
        [weakSelf.viewModel.diaryObj.images addObjectsFromArray:photoList];
        if (videoList.count) {
            GMPhotoModel *obj = videoList.firstObject;
//            weakSelf.viewModel.diaryObj.videoModel.fileURL = obj.fileURL;
            weakSelf.viewModel.diaryObj.videoModel = obj;
        }
        weakSelf.headerView.object = weakSelf.viewModel.diaryObj;
        [weakSelf.headerView setNeedsLayout];
        [weakSelf.headerView layoutIfNeeded];
        
        weakSelf.headerView.size = [weakSelf.headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        NSLog(@"%.2f",weakSelf.headerView.size.height);
        weakSelf.table.tableHeaderView = weakSelf.headerView;
        
        [weakSelf.view setNeedsUpdateConstraints];
        [weakSelf.view updateConstraintsIfNeeded];
    } cancel:^(GMAlbumListViewController *viewController) {
        debugLog(@"取消了");
    }];
}

- (void)deletePictureAtCollectionIndex:(NSInteger)collectionIndex {
    ALCreateDiaryObject *obj = self.viewModel.diaryObj;
    if ( obj.videoModel.fileURL) {
        if (collectionIndex == 0) {
            obj.videoModel = nil;
        } else {
            [obj.images removeObjectAtIndex:collectionIndex - 1];
        }
    } else {
        [obj.images removeObjectAtIndex:collectionIndex];
    }
    self.headerView.object = obj;
    [self.headerView setNeedsLayout];
    [self.headerView layoutIfNeeded];
    
    self.headerView.size = [self.headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    self.table.tableHeaderView = self.headerView;
}

- (void)editPictureAtCollectionIndex:(NSInteger)collectionIndex {

    ALCreateDiaryObject *obj = self.viewModel.diaryObj;
    GMPhotoModel *imageObj;
    if ( obj.videoModel.fileURL) { // 有视频的时候，视频在第一个显示
        imageObj = obj.images[collectionIndex - 1];
        if (collectionIndex == 0) {
            // 播放视频
            
//            CGRect rect = [self.headerView convertRect:self.headerView.frame toView:nil];
            return;
        } else {
            imageObj = obj.images[collectionIndex - 1];
        }
    } else {
        imageObj = obj.images[collectionIndex];
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        GMEditPhotoInfo *info = [GMEditPhotoInfo new];
        info.preveiwImage = imageObj.thumbPhoto;
        info.thumbImage = imageObj.thumbPhoto;
        NSMutableArray *editingImages = (NSMutableArray<GMEditPhotoInfo *> *)[NSMutableArray array];
        [editingImages addObject:info];
        UIImage *optimizedImage = [self optimizedImageWithAsset:imageObj.asset];
        if (optimizedImage != nil) {
            info.preveiwImage = optimizedImage;
            info.editImage = optimizedImage;
            info.filtedImage = optimizedImage;
            info.asset = imageObj.asset;
        } else {
            info.preveiwImage = imageObj.thumbPhoto;
            info.editImage = imageObj.thumbPhoto;
            info.filtedImage = imageObj.thumbPhoto;
            info.pixelWidth = CGImageGetWidth(imageObj.thumbPhoto.CGImage);
            info.pixelHeight = CGImageGetHeight(imageObj.thumbPhoto.CGImage);
        }
        
        // 转回到主线程（编辑图片，或者直接使用图片）
        dispatch_sync(dispatch_get_main_queue(), ^{
            GMEditPhotoController *edit = [[GMEditPhotoController alloc] init];
            edit.finishDelegate = self;
            edit.editInfoArray = editingImages;
            [self pushViewController:edit];
        });
    });
}

- (UIImage *)optimizedImageWithAsset:(PHAsset *)asset {
    __block UIImage *resultImage = nil;
    PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
    
    // requestOption 中指定 resizeMode，requestImageForAsset方法中指定targetSize才可以进行裁剪
    PHImageRequestOptions *requestOption = [PHImageRequestOptions new];
    requestOption.synchronous = YES;
    requestOption.resizeMode = PHImageRequestOptionsResizeModeFast;
    requestOption.networkAccessAllowed = YES;
    [imageManager requestImageForAsset:asset
                            targetSize:CGSizeMake(640, MAXFLOAT)
                           contentMode:PHImageContentModeAspectFit
                               options:requestOption
                         resultHandler:^(UIImage *result, NSDictionary *info) {
                             NSError *error = info[PHImageErrorKey];
                             debugLog(@"%@",error);
                             resultImage = result;
                         }];
    
    return resultImage;
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
     __weak __typeof(self)weakSelf = self;

    //如果self.viewModel.diaryObj.groupId不是空
    if ([self.viewModel.diaryObj.groupId isNonEmpty]) {
        self.groupId = self.viewModel.diaryObj.groupId.integerValue;
    }
    
    self.viewModel.diaryObj = self.headerView.object;
    self.viewModel.diaryObj.content = SafeString(self.headerView.titleTextView.text);
    //因为有getter方法，所以需要重新赋值，这样值不会错
    if(self.isSelect || self.fromType == FromWhereComeInDetail)
    {
        self.viewModel.diaryObj.groupId = [NSString stringWithFormat:@"%ld",(long)self.groupId];
    }
    NSInteger videoCount = self.viewModel.diaryObj.videoModel.fileURL ? 1: 0;
    NSInteger pictureCount = self.viewModel.diaryObj.images.count;
    [self showLoading:nil];
    [self.viewModel uploadImagesAndVideoSuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        GMResponseOC *response = (GMResponseOC *)responseObject;
        if (response.isSuccess) {
            NSDictionary *data = response.data;
            if (data) {

                
                
//                if(self.fromType == FromWhereComeInCreat)
//                {
                    //帖子创建
                [Phobos track:@"topic_create_click_release" attributes:@{@"video": @(videoCount),
                                                                         @"picture": @(pictureCount),
                                                                         @"group_id": SafeString(self.viewModel.diaryObj.groupId),
                                                                         @"from":self.fromStr
                                                                         }];
                //                }
                
                NSInteger topicId = [data[@"id"]  integerValue];
                
                if (self.groupId)
                {
                    //有值进入小组详情
                    ALGroupListVController *toVc = [[ALGroupListVController alloc] initWithGroupId:self.groupId topicId:topicId];
                    toVc.isCreatContro = YES;
                    [weakSelf pushViewController:toVc];
                    
                }
                else
                {
                    //没有值进入贴子详情
                    ALTopicListVController *toVc = [[ALTopicListVController alloc]initWithTopicId:topicId];
                    toVc.isCreatContro = YES;
                    [weakSelf pushViewController:toVc];
                }
                

            }
        }
        [weakSelf toast:@"上传成功"];
    } failBlock:^(NSString *message) {
        [weakSelf toast:@"上传失败"];
    }];
}
@end
