//
//  ZJKeyBoardAccessoryView.m
//  Lighting
//
//  Created by Javen on 2017/4/17.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "ZJKeyBoardAccessoryView.h"
#import "STEmojiKeyboard.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "MWPhotoBrowser.h"
/**
 扩展项
 
 - Camera:     相机
 - PhotoAlbum: 相册
 - Emoji:      表情
 */
typedef NS_ENUM(NSInteger, ItemIndex) {
    Camera = 0,
    PhotoAlbum,
    Emoji,
};

@interface ZJKeyBoardAccessoryView () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, MWPhotoBrowserDelegate>
@property (strong, nonatomic) NSMutableArray *allPhotoArray;

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

/**
 缩略图
 */
@property (strong, nonatomic) NSMutableArray *thumbsArray;
@property (strong, nonatomic) NSMutableDictionary *cache;
@end
@implementation ZJKeyBoardAccessoryView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        [self uiConfigAction];
    }
    return self;
}

#pragma mark - UI
- (void)uiConfigAction {
    NSArray *itemArray = @[ @"camera", @"album" ];
    CGFloat size = 25;
    CGFloat interval = 30;
    for (int i = 0; i < itemArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //        button.imageView
        button.tag = i;
        //        button.tintColor = [UIColor whiteColor];
        [button setImage:TCImage(itemArray[i]) forState:UIControlStateNormal];
        button.frame = CGRectMake(i * size + i * interval + 50, (self.height - size) / 2, size, size);
        [button addTarget:self action:@selector(extensionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    [self mwPhotoArray];
    
    self.mwPhotoArray = nil;
}

- (void)extensionButtonClick:(UIButton *)btn {
    switch (btn.tag) {
        case Camera: {
            [self showCameraAction];
        } break;
        case PhotoAlbum: {
            [self selectAlbumImage];
        } break;

        default:
            break;
    }
}

#pragma mark - 拍照选择照片
- (void)showCameraAction {
    if ([BaseViewController determineCameraPermissions]) {
        UIImagePickerController *camera = [[UIImagePickerController alloc] init];
        camera.delegate = self;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [camera setSourceType:UIImagePickerControllerSourceTypeCamera];
            camera.allowsEditing = YES;
            [self.viewController presentViewController:camera animated:YES completion:nil];
        } else {
            [XBLoadingView showHUDViewWithText:@"相机无法使用"];
        }
    }
}

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

#pragma mark - 相册选择照片

#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 {
    PHAsset *currentPhoto = self.allPhotoArray[index];
    return [self.arrSelectedAssets containsObject:currentPhoto];
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    PHAsset *currentPhoto = self.allPhotoArray[index];
    
    
    if (selected) {
        PHImageManager *imageManager = [PHImageManager defaultManager];
        PHImageRequestOptions *options = [PHImageRequestOptions new];
        options.networkAccessAllowed = YES;
        options.resizeMode = PHImageRequestOptionsResizeModeFast;
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        options.synchronous = YES;
        WS(weakSelf);
        [imageManager requestImageForAsset:currentPhoto
                                targetSize:CGSizeMake(ScreenWidth, ScreenHeight)
                               contentMode:PHImageContentModeAspectFit
                                   options:options
                             resultHandler:^(UIImage *result, NSDictionary *info) {
                                     [self.arrSelectedAssets addObject:currentPhoto];
                                     [weakSelf.arrSelectedPhotos addObject:result];
                                     [weakSelf.cache setObject:result forKey:currentPhoto];
                             }];
    }else{
        id result = [self.cache objectForKey:currentPhoto];
        [self.arrSelectedAssets removeObject:currentPhoto];
        [self.arrSelectedPhotos removeObject:result];
    }

}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    if (self.arrSelectedAssets.count > 3) {
        [XBLoadingView showHUDViewWithText:@"图片最多选择3张"];
        return;
    }
//
//    PHImageManager *imageManager = [PHImageManager defaultManager];
//    PHImageRequestOptions *options = [PHImageRequestOptions new];
//    options.networkAccessAllowed = YES;
//    options.resizeMode = PHImageRequestOptionsResizeModeFast;
//    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
//    options.synchronous = YES;
//    WS(weakSelf);
//    [self.arrSelectedPhotos removeAllObjects];
//    for (PHAsset *asset in self.arrSelectedAssets) {
//        [imageManager requestImageForAsset:asset
//                                targetSize:CGSizeMake(ScreenWidth, ScreenHeight)
//                               contentMode:PHImageContentModeAspectFit
//                                   options:options
//                             resultHandler:^(UIImage *result, NSDictionary *info) {
//                                 [weakSelf.arrSelectedPhotos addObject:result];
//                             }];
//    }

    if (self.blockFinishSelected) {
        self.blockFinishSelected();
    }

    [photoBrowser dismissViewControllerAnimated:YES
                                     completion:nil];
}

- (void)selectAlbumImage {
    if (![BaseViewController determinePhotosPermissions]) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在iPad的“设置-隐私-相册”选项中，允许欧立方访问你的相册" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil]];
        [self.viewController presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    
    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.viewController.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)deletePhotoWithIndex:(NSInteger)index {
    UIImage *image = self.arrSelectedPhotos[index];
    
    //如果要删除的照片在缓存里面，那么这是相册选择的照片，需要从缓存删除
    for (PHAsset *key in self.cache.allKeys) {
        UIImage *cacheImage = [self.cache objectForKey:key];
        if ([cacheImage isEqual:image]) {
            [self.cache removeObjectForKey:key];
            [self.arrSelectedAssets removeObject:key];
            break;
        }
    }
    
    [self.arrSelectedPhotos removeObject:image];


    if (self.blockFinishSelected) {
        self.blockFinishSelected();
    }
}

/**
 删除所有的图片
 */
- (void)deleteAll {
    [self.arrSelectedAssets removeAllObjects];
    [self.arrSelectedPhotos removeAllObjects];
    [self.cache removeAllObjects];
    if (self.blockFinishSelected) {
        self.blockFinishSelected();
    }
}

- (NSMutableArray *)mwPhotoArray {
    if (!_mwPhotoArray) {
        _mwPhotoArray = [NSMutableArray array];
        _thumbsArray = [NSMutableArray array];
        _allPhotoArray = [NSMutableArray array];
        PHFetchOptions *options = [PHFetchOptions new];
        options.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO] ];
        PHFetchResult *fetchResults = [PHAsset fetchAssetsWithOptions:options];

        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);
        CGSize imageTargetSize = CGSizeMake(imageSize * scale, imageSize * scale);
        [fetchResults enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [_allPhotoArray addObject:obj];
            [_mwPhotoArray addObject:[MWPhoto photoWithAsset:obj targetSize:imageTargetSize]];
            [_thumbsArray addObject:[MWPhoto photoWithAsset:obj targetSize:thumbTargetSize]];
        }];
    }
    return _mwPhotoArray;
}

- (NSMutableArray *)arrSelectedAssets {
    if (!_arrSelectedAssets) {
        _arrSelectedAssets = [NSMutableArray array];
    }
    return _arrSelectedAssets;
}

- (NSMutableArray *)arrSelectedPhotos {
    if (!_arrSelectedPhotos) {
        _arrSelectedPhotos = [NSMutableArray array];
    }
    return _arrSelectedPhotos;
}

- (NSDictionary *)cache {
    if (!_cache) {
        _cache = [NSMutableDictionary dictionary];
    }
    return _cache;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
