//
//  ReleasePostViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/12/9.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "ReleasePostViewController.h"
#import "HeadlineTableViewCell.h"
#import "ContentTableViewCell.h"
#import "PhotoManagerViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "MWPhotoBrowser.h"
#import "OSSHelper.h"
#import "UIImage+Fit.h"





@interface ReleasePostViewController ()<UITableViewDelegate,UITableViewDataSource,ExtensionViewTapDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MWPhotoBrowserDelegate>

/**
 选择图片
 */
@property (nonatomic,strong) NSMutableArray *selectedImageArray;

/**
 相册图片
 */
@property (nonatomic,strong) NSMutableArray *allPhotoArray;

/**
 MWPhoto
 */
@property (nonatomic,strong) NSMutableArray *mwPhotoArray;

/**
 缩略图
 */
@property (nonatomic,strong) NSMutableArray *thumbsArray;

/**
 图片是否选中
 */
@property (nonatomic,strong) NSMutableArray *selecedSectionArray;

/**
 输入框高度
 */
@property (nonatomic,assign) CGFloat contentTextViewHeight;

@end

@implementation ReleasePostViewController


#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 30.0f;
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 0.0f;
}


#pragma mark - lazy
- (NSMutableArray *)selectedImageArray
{
    if (!_selectedImageArray) {
        _selectedImageArray = [NSMutableArray array];
    }
    return _selectedImageArray;
}

- (NSMutableArray *)selecedSectionArray
{
    if (!_selecedSectionArray) {
        _selecedSectionArray = [NSMutableArray array];
    }
    return _selecedSectionArray;
}

- (NSMutableArray *)allPhotoArray
{
    if (!_allPhotoArray.count) {
        _allPhotoArray = [NSMutableArray array];
        PHFetchOptions *options = [PHFetchOptions new];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        PHFetchResult *fetchResults = [PHAsset fetchAssetsWithOptions:options];
        [fetchResults enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [_allPhotoArray addObject:obj];
        }];
        for (int i=0; i<_allPhotoArray.count; i++) {
            [self.selecedSectionArray addObject:@0];
        }
    }
    return _allPhotoArray;
}

- (NSMutableArray *)mwPhotoArray
{
    if (!_mwPhotoArray.count) {
        _mwPhotoArray = [NSMutableArray array];
        UIScreen *screen = [UIScreen mainScreen];
        CGFloat scale = screen.scale;
        // Sizing is very rough... more thought required in a real implementation
        CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
        CGSize imageTargetSize = CGSizeMake(imageSize * scale, imageSize * scale);
        for (PHAsset *asset in self.allPhotoArray) {
            [_mwPhotoArray addObject:[MWPhoto photoWithAsset:asset targetSize:imageTargetSize]];
        }
    }
    return _mwPhotoArray;
}

- (NSMutableArray *)thumbsArray
{
    if (!_thumbsArray) {
        _thumbsArray = [NSMutableArray array];
        UIScreen *screen = [UIScreen mainScreen];
        CGFloat scale = screen.scale;
        // Sizing is very rough... more thought required in a real implementation
        CGFloat imageSize = MAX(screen.bounds.size.width, screen.bounds.size.height) * 1.5;
        CGSize thumbTargetSize = CGSizeMake(imageSize / 3.0 * scale, imageSize / 3.0 * scale);
        for (PHAsset *asset in self.allPhotoArray) {
            [_thumbsArray addObject:[MWPhoto photoWithAsset:asset targetSize:thumbTargetSize]];
        }
    }
    return _thumbsArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self addChildViewController];
}

#pragma mark - UI
- (void)uiConfigAction
{
    self.publishTableView.tableFooterView = [UIView new];
    [self.categoryImageView sd_setImageWithURL:[NSURL URLWithString:self.category.attachment.fileUrl] placeholderImage:REPLACEIMAGE];
    self.categoryTitleLabel.text = self.category.name;
    [self allPhotoArray];
    if (![[self class] determinePhotosPermissions]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPad的“设置-隐私-相册”选项中，允许欧立方访问你的相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

#pragma mark - 图片管理
- (void)addChildViewController
{
    PhotoManagerViewController *photoManager = [[[self class] getLearningCenterStoryboardClass] instantiateViewControllerWithIdentifier:@"PhotoManagerViewController"];
    [self addChildViewController:photoManager];
}


#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case HeadlineCell:
        {
            HeadlineTableViewCell *titleCell = [tableView dequeueReusableCellWithIdentifier:@"HeadlineTableViewCell" forIndexPath:indexPath];
            return titleCell;
        }
            break;
        case ContentCell:
        {
            ContentTableViewCell *contentCell = [tableView dequeueReusableCellWithIdentifier:@"ContentTableViewCell" forIndexPath:indexPath];
            contentCell.delgate = self;
            PhotoManagerViewController *photo = [self.childViewControllers firstObject];
            [contentCell.contentView addSubview:photo.view];
            photo.view.frame = CGRectMake(contentCell.contentTextView.x, contentCell.contentTextView.bottom+10, contentCell.contentTextView.width, [self calculateImageHeight]);
            photo.imageArray = self.selectedImageArray;
            return contentCell;
        }
            break;
            
        default:
            break;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case HeadlineCell:
            return 44;
            break;
        case ContentCell:
        {
            return self.contentTextViewHeight + 30 + [self calculateImageHeight];
        }
            break;
            
        default:
            break;
    }
    return 0;
}


#pragma mark - 拍照
- (void)showCameraAction
{
    if ([[self class] determineCameraPermissions]) {
        
        UIImagePickerController *camera = [[UIImagePickerController alloc]init];
        camera.delegate = self;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [camera setSourceType:UIImagePickerControllerSourceTypeCamera];
            camera.allowsEditing = YES;
            [self presentViewController:camera animated:YES completion:nil];
        }else {
            [XBLoadingView showHUDViewWithText:@"相机无法使用"];
        }
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPad的“设置-隐私-相机”选项中，允许欧立方访问你的相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    UIImage *headImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self.selectedImageArray addObject:headImage];
    [self.publishTableView reloadData];
}


#pragma mark - 相册
- (void)showPhotoAlbumAction
{
    for (int i=0; i<self.selecedSectionArray.count; i++) {
        if ([self.selecedSectionArray[i] boolValue]) {
            self.selecedSectionArray[i] = @0;
        }
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = YES;
    browser.alwaysShowControls = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = YES;
    browser.startOnGrid = YES;
    browser.enableSwipeToDismiss = YES;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:browser];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

#pragma mark - 刷新高度
- (void)refreshHeight:(CGFloat)height
{
    self.contentTextViewHeight = height;
    [self.publishTableView reloadData];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.mwPhotoArray.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.mwPhotoArray.count)
        return [self.mwPhotoArray objectAtIndex:index];
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < self.thumbsArray.count)
        return [self.thumbsArray objectAtIndex:index];
    return nil;
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    if (self.selecedSectionArray.count) {
        return [[self.selecedSectionArray objectAtIndex:index] boolValue];
    }
    return NO;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected  {
    [self.selecedSectionArray replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:selected]];
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    
    [self dismissViewControllerAnimated:YES completion:^{
        for (int i=0; i<self.selecedSectionArray.count; i++) {
            BOOL boolValue = [self.selecedSectionArray[i] boolValue];
            if (boolValue) {
                PHAsset *asset = self.allPhotoArray[i];
                [self performLoadUnderlyingImageAndNotifyWithAsset:asset targetSize:CGSizeMake(ScreenWidth, ScreenHeight)];
            }
        }
        [self.publishTableView reloadData];
    }];
}

#pragma mark - 获取选择的图片
- (void)performLoadUnderlyingImageAndNotifyWithAsset:(PHAsset *)asset targetSize:(CGSize)targetSize {
    
    PHImageManager *imageManager = [PHImageManager defaultManager];
    PHImageRequestOptions *options = [PHImageRequestOptions new];
    options.networkAccessAllowed = YES;
    options.resizeMode = PHImageRequestOptionsResizeModeFast;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.synchronous = false;
    [imageManager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.selectedImageArray addObject:result];
            [self.publishTableView reloadData];
        });
    }];
}

#pragma mark - 计算选中图片显示所需高度
- (CGFloat)calculateImageHeight
{
    //默认每行显示8张图片
    CGFloat height = (ScreenWidth-40-7*20)/8;
    CGFloat interval = 20;
    CGFloat allHeight = 0;
    NSInteger number = self.selectedImageArray.count/8;
    if (self.selectedImageArray.count < 8) {
        return height;
    }else if (self.selectedImageArray.count %8 == 0) {
        allHeight = number*height + (number-1)*interval;
    }else if (number) {
        allHeight = (number+1)*height + (self.selectedImageArray.count/8)*interval;
    }
    return allHeight;
}

#pragma mark - 发表
- (IBAction)publishButtonClickAction:(UIButton *)sender {
    
    [self.view endEditing:YES];
    WS(weakSelf);
    ShowDefaultAlertView(self, nil, @"确认发表吗?", UIAlertControllerStyleAlert, ^{
        HeadlineTableViewCell *titleCell = [weakSelf.publishTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        ContentTableViewCell *contentCell = [weakSelf.publishTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        if ([[weakSelf class] isBlankString:titleCell.titleTextField.text]) {
            [XBLoadingView showHUDViewWithText:@"标题不能为空"];return;
        }
        if ([[weakSelf class] isBlankString:contentCell.contentTextView.text]) {
            [XBLoadingView showHUDViewWithText:@"内容不能为空"];return;
        }
        WS(weakSelf);
        if (weakSelf.selectedImageArray.count) {
            [weakSelf uploadAttachments:^(NSArray *OSSKeys)  {
                [weakSelf submitPost:titleCell.titleTextField.text withContent:contentCell.contentTextView.text withAttachments:OSSKeys];
            }];
        }else {
            [weakSelf submitPost:titleCell.titleTextField.text withContent:contentCell.contentTextView.text withAttachments:nil];
        }
    }, nil);
}

#pragma mark - 上传图片附件
- (void)uploadAttachments:(void(^)(NSArray *OSSKeys))finish
{
    NSMutableArray *OSSKeyArray = [NSMutableArray array];
    for (int i=0; i<self.selectedImageArray.count; i++) {
        [OSSKeyArray addObject:[OSSHelper getOSSObjectKeyWithtype:@"png" index:i]];
    }
    XBLoadingView *loadView = [XBLoadingView showHUDViewProgressLabel:[NSString stringWithFormat:@"图片上传中:1/%ld",self.selectedImageArray.count]];
    static NSInteger number = 0;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        for (int i=0;i<self.selectedImageArray.count;i++) {
            UIImage *image = self.selectedImageArray[i];
            NSString *ossKey = OSSKeyArray[i];
            NSData *data = UIImagePNGRepresentation(image);
            [OSSHelper uploadImageObjectWithKey:ossKey data:data type:OSSHelperOperationTypeSynchronous progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                CGFloat totalBytesSentFloat = totalBytesSent;
                CGFloat totalBytesExpectedToSendFloat = totalBytesExpectedToSend;
                CGFloat progress = totalBytesSentFloat / totalBytesExpectedToSendFloat;
                NSLog(@"-->进度%f", progress);
                loadView.progress = progress;
                
            } success:^id(OSSTask *task) {
                
                number ++;
                loadView.labelText = [NSString stringWithFormat:@"图片上传中:%ld/%ld",number,self.selectedImageArray.count];
                if (number == self.selectedImageArray.count) {
                    number = 0;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [loadView hide:YES];
                        [XBLoadingView showHUDViewWithSuccessText:@"图片上传成功" completeBlock:^{
                            finish(OSSKeyArray);
                        }];
                    });
                }
                return nil;
            } error:^(NSError *error) {
                [XBLoadingView hideHUDViewWithDefault];
                [XBLoadingView showHUDViewWithText:error.localizedDescription];
            }];
        }
    });
}

#pragma mark - 发布帖子
- (void)submitPost:(NSString *)title withContent:(NSString *)content withAttachments:(NSArray *)OSSKeyArray
{
    TOForumTopicEntity *topic = [[TOForumTopicEntity alloc] init];
    topic.posterId = [Shoppersmanager manager].shoppers.employee.fid;
    topic.posterName = [Shoppersmanager manager].shoppers.employee.userName;
    topic.posterRealName = [Shoppersmanager manager].shoppers.employee.realName;
    topic.posterPosition = [Shoppersmanager manager].shoppers.employee.positionsName;
    topic.posterPicture = [Shoppersmanager manager].shoppers.employee.picture;
    topic.postTime = [[self class] getTimeby:0];
    topic.category = self.category.fid;
    topic.backEnd = NO;
    topic.forumType = self.category.typeId;
    topic.title = title;
    topic.content = content;
    topic.bestTopic = false;
    NSMutableArray *attachments = [NSMutableArray array];
    NSString *entityId = [OSSHelper getOSSObjectKey];
    topic.attachmentId = entityId;
    for (NSString *ossKey in OSSKeyArray) {
        TOAttachmentEntity *entity = [[TOAttachmentEntity alloc] init];
        entity.entityType = @"forumTopic";
        entity.entityId = entityId;
        entity.fileUrl = [OSSHelper getCompleteImageURLWithOSSkey:ossKey];
        entity.fileName = ossKey;
        [attachments addObject:entity];
    }
    topic.attachments = (NSArray<TOAttachmentEntity>*)attachments;
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(SUBMITTOPIC) withRequestType:ZERO withParameter:topic withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [XBLoadingView showHUDViewWithSuccessText:@"发布成功" completeBlock:^{
                if (weakSelf.finishBlock) {
                    weakSelf.finishBlock();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }];
        }else {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}




@end
