//
//  GMDatePhotoViewController.m
//  Gengmei
//
//  Created by Q14 on 2018/9/28.
//  Copyright © 2018年 更美互动信息科技有限公司. All rights reserved.
//

#import "GMDatePhotoViewController.h"
#import "GMDatePhotoPreviewViewController.h"
#import "GMPhotoDefine.h"
#import "GMCustomCameraViewController.h"
#import "GMPhoto3DTouchViewController.h"
#import "UIView+GMExtension.h"
#import "GMCustomCameraController.h"
#import "GMCustomPreviewView.h"
#import "GMDatePhotoEditViewController.h"
#import "GMTopicTools.h"

@interface GMDatePhotoViewController ()<
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UIViewControllerPreviewingDelegate,
GMDatePhotoViewCellDelegate,
GMDatePhotoPreviewViewControllerDelegate,
GMCustomCameraViewControllerDelegate,
GMDatePhotoEditViewControllerDelegate
>
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) GMDatePhotoViewFlowLayout *customLayout;

@property (nonatomic, strong) NSMutableArray *allArray;
@property (nonatomic, strong) NSMutableArray *previewArray;
@property (nonatomic, strong) NSMutableArray *photoArray;
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic,strong) UIButton *numberButton;
@property (assign, nonatomic) NSInteger currentSectionIndex;
@property (weak, nonatomic) id<UIViewControllerPreviewing> previewingContext;

@property (assign, nonatomic) BOOL orientationDidChange;
@property (assign, nonatomic) BOOL needChangeViewFrame;
@property (nonatomic, strong) NSIndexPath *beforeOrientationIndexPath;

@property (weak, nonatomic) GMDatePhotoViewSectionFooterView *footerView;
@end

@implementation GMDatePhotoViewController

// TODO : 调试内存泄漏，记得删除
- (BOOL)willDealloc {
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageName = @"time_album";
    self.title = @"选择照片/视频";
    [self setupUI];
    [self changeSubviewFrame];
    [self getPhotoList];
    
    [self setupRightView];
}
- (void)setupRightView {
    UIView *bgView = [[UIView alloc] init];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightButtonClicked:)];
    [bgView addGestureRecognizer:tap];
    bgView.frame = CGRectMake(MAINSCREEN_WIDTH - 98, 0, 74, 44);
    [self.navigationBar.itemView addSubview:bgView];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"下一步";
    titleLabel.textColor = RGBCOLOR_HEX(0x282828);
    titleLabel.font = [UIFont gmFont:16];
    titleLabel.frame = CGRectMake(0, 0, 50, 44);
    [bgView addSubview:titleLabel];
    
    _numberButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _numberButton.enabled = NO;
    [_numberButton setBackgroundColor:RGBCOLOR_HEX(0x3ADBD2)];
    _numberButton.titleLabel.font = [UIFont gmFont:13];
    _numberButton.adjustsImageWhenDisabled = YES;
    [_numberButton setTitle:[NSString stringWithFormat:@"%ld",[self.manager selectedCount]] forState:UIControlStateNormal];
    _numberButton.frame = CGRectMake(54, 10, 24, 24);
    _numberButton.layer.cornerRadius = 12;
    [bgView addSubview:_numberButton];
}

- (void)backAction:(OCNavigationBarButton *)button {
    [self didCancelClick];
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    __weak __typeof(self)weakSelf = self;
    if (self.manager.configuration.isShowSpiltAlert) {
        if ([GMTopicTools isSameDayPhotoOrVideo:self.manager.selectedArray]) {
            gm_showAlert(self, @"照片时间和日记贴不是同一天哦，是否按照照片时间拆分成多篇日记？", nil, @"不用了", @"好的", ^{
                weakSelf.manager.configuration.isSpiltDate = NO;
                [weakSelf datePhotoViewDidDoneBtn];
            }, ^{
                weakSelf.manager.configuration.isSpiltDate = YES;
                [weakSelf datePhotoViewDidDoneBtn];
            });
        } else {
            weakSelf.manager.configuration.isSpiltDate = NO;
            [weakSelf datePhotoViewDidDoneBtn];
        }
        
    } else {
        self.manager.configuration.isSpiltDate = NO;
        [self datePhotoViewDidDoneBtn];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.needChangeViewFrame) {
        self.needChangeViewFrame = NO;
    }
}

- (void)changeSubviewFrame {
    CGFloat navBarHeight = OCNavigationBar.barHeight;
    NSInteger lineCount = self.manager.configuration.rowCount;
    CGFloat bottomMargin = kBottomMargin;
    CGFloat leftMargin = 0;
    CGFloat rightMargin = 0;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    CGFloat viewWidth = [UIScreen mainScreen].bounds.size.width;
    
    if (!CGRectEqualToRect(self.view.bounds, [UIScreen mainScreen].bounds)) {
        self.view.frame = CGRectMake(0, 0, viewWidth, height);
    }
    CGFloat itemWidth = (width - (lineCount - 1)) / lineCount;
    CGFloat itemHeight = itemWidth;
    if (self.manager.configuration.showDateSectionHeader) {
        self.customLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    }else {
        self.flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight);
    }
    
    self.collectionView.contentInset = UIEdgeInsetsMake(navBarHeight, leftMargin, bottomMargin, rightMargin);
    if (!self.manager.configuration.singleSelected) {
        self.collectionView.contentInset = UIEdgeInsetsMake(navBarHeight, leftMargin, 50 + bottomMargin, rightMargin);
    } else {
        self.collectionView.contentInset = UIEdgeInsetsMake(navBarHeight, leftMargin, bottomMargin, rightMargin);
    }
    self.collectionView.scrollIndicatorInsets = _collectionView.contentInset;
    
    if (self.orientationDidChange) {
        [self.collectionView scrollToItemAtIndexPath:self.beforeOrientationIndexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    }
    
    if (self.manager.configuration.photoListCollectionView) {
        self.manager.configuration.photoListCollectionView(self.collectionView);
    }
}
- (void)setupUI {
    self.currentSectionIndex = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];

}
- (void)didCancelClick {
    if ([self.delegate respondsToSelector:@selector(datePhotoViewControllerDidCancel:)]) {
        [self.delegate datePhotoViewControllerDidCancel:self];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (GMDatePhotoViewCell *)currentPreviewCell:(GMPhotoModel *)model {
    if (!model || ![self.allArray containsObject:model]) {
        return nil;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self dateItem:model] inSection:model.dateSection];
    return (GMDatePhotoViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
}
- (BOOL)scrollToModel:(GMPhotoModel *)model {
    if ([self.allArray containsObject:model]) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[self dateItem:model] inSection:model.dateSection] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:[self dateItem:model] inSection:model.dateSection]]];
    }
    return [self.allArray containsObject:model];
}
- (NSInteger)dateItem:(GMPhotoModel *)model {
    NSInteger dateItem = model.dateItem;
    if (self.manager.configuration.showDateSectionHeader && self.manager.configuration.reverseDate && model.dateSection != 0) {
        dateItem = model.dateItem;
    }else if (self.manager.configuration.showDateSectionHeader && !self.manager.configuration.reverseDate && model.dateSection != self.dateArray.count - 1) {
        dateItem = model.dateItem;
    }else {
        if (model.type == GMPhotoModelMediaTypeCameraPhoto || model.type == GMPhotoModelMediaTypeCameraVideo) {
            if (self.manager.configuration.showDateSectionHeader) {
                if (self.manager.configuration.reverseDate) {
                    GMPhotoDateModel *dateModel = self.dateArray.firstObject;
                    dateItem = [dateModel.photoModelArray indexOfObject:model];
                }else {
                    GMPhotoDateModel *dateModel = self.dateArray.lastObject;
                    dateItem = [dateModel.photoModelArray indexOfObject:model];
                }
            }else {
                dateItem = [self.allArray indexOfObject:model];
            }
        }else {
            if (self.manager.configuration.showDateSectionHeader) {
                if (self.manager.configuration.reverseDate) {
                    GMPhotoDateModel *dateModel = self.dateArray.firstObject;
                    dateItem = [dateModel.photoModelArray indexOfObject:model];
                }else {
                    GMPhotoDateModel *dateModel = self.dateArray.lastObject;
                    dateItem = [dateModel.photoModelArray indexOfObject:model];
                }
            }else {
                dateItem = [self.allArray indexOfObject:model];
            }
        }
    }
    return dateItem;
}
- (void)scrollToPoint:(GMDatePhotoViewCell *)cell rect:(CGRect)rect {
    CGFloat navBarHeight = OCNavigationBar.barHeight;

    if (self.manager.configuration.showDateSectionHeader) {
        navBarHeight += 50;
    }
    if (rect.origin.y < navBarHeight) {
        [self.collectionView setContentOffset:CGPointMake(0, cell.frame.origin.y - navBarHeight)];
    }else if (rect.origin.y + rect.size.height > self.view.gm_h - 50.5 - kBottomMargin) {
        [self.collectionView setContentOffset:CGPointMake(0, cell.frame.origin.y - self.view.gm_h + 50.5 + kBottomMargin + rect.size.height)];
    }
}
- (void)getPhotoList {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        __weak typeof(self) weakSelf = self;
        [self.manager getPhotoListWithAlbumModel:self.albumModel complete:^(NSArray *allList, NSArray *previewList, NSArray *photoList, NSArray *videoList, NSArray *dateList, GMPhotoModel *firstSelectModel) {
            weakSelf.dateArray = [NSMutableArray arrayWithArray:dateList];
            weakSelf.photoArray = [NSMutableArray arrayWithArray:photoList];
            weakSelf.videoArray = [NSMutableArray arrayWithArray:videoList];
            weakSelf.allArray = [NSMutableArray arrayWithArray:allList];
            weakSelf.previewArray = [NSMutableArray arrayWithArray:previewList];
            dispatch_async(dispatch_get_main_queue(), ^{
                CATransition *transition = [CATransition animation];
                transition.type = kCATransitionPush;
                transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
                transition.fillMode = kCAFillModeForwards;
                transition.duration = 0.1;
                transition.subtype = kCATransitionFade;
                [[weakSelf.collectionView layer] addAnimation:transition forKey:@""];
                [weakSelf.collectionView reloadData];
                if (!weakSelf.manager.configuration.reverseDate) {
                    if (weakSelf.manager.configuration.showDateSectionHeader && weakSelf.dateArray.count > 0) {
                        GMPhotoDateModel *dateModel = weakSelf.dateArray.lastObject;
                        if (dateModel.photoModelArray.count > 0) {
                            if (firstSelectModel) {
                                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[weakSelf dateItem:firstSelectModel] inSection:firstSelectModel.dateSection] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
                            }else {
                                NSInteger forItem = (dateModel.photoModelArray.count - 1) <= 0 ? 0 : dateModel.photoModelArray.count - 1;
                                NSInteger inSection = (weakSelf.dateArray.count - 1) <= 0 ? 0 : weakSelf.dateArray.count - 1;
                                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:forItem inSection:inSection] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
                            }
                        }
                    }else {
                        if (weakSelf.allArray.count > 0) {
                            if (firstSelectModel) {
                                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[weakSelf.allArray indexOfObject:firstSelectModel] inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
                            }else {
                                NSInteger forItem = (weakSelf.allArray.count - 1) <= 0 ? 0 : weakSelf.allArray.count - 1;
                                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:forItem inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
                            }
                        }
                    }
                }else {
                    if (firstSelectModel) {
                        if (weakSelf.manager.configuration.showDateSectionHeader) {
                            [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[weakSelf dateItem:firstSelectModel] inSection:firstSelectModel.dateSection] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
                        }else {
                            [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[weakSelf.allArray indexOfObject:firstSelectModel] inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
                        }
                    }
                }
            });
        }];
    });
}
#pragma mark - < GMCustomCameraViewControllerDelegate >
- (void)customCameraViewController:(GMCustomCameraViewController *)viewController didDone:(GMPhotoModel *)model {
    if (self.manager.configuration.singleSelected) {
        if (model.type == GMPhotoModelMediaTypeCameraPhoto) {
            GMDatePhotoEditViewController *vc = [[GMDatePhotoEditViewController alloc] init];
            vc.delegate = self;
            vc.manager = self.manager;
            vc.model = model;
            [self.navigationController pushViewController:vc animated:NO];
        }else {
            GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
            previewVC.delegate = self;
            previewVC.modelArray = [NSMutableArray arrayWithObjects:model, nil];
            previewVC.manager = self.manager;
            previewVC.currentModelIndex = 0;
            self.navigationController.delegate = previewVC;
            [self.navigationController pushViewController:previewVC animated:YES];
        }
        return;
    }
    model.currentAlbumIndex = self.albumModel.index;
    [self.manager beforeListAddCameraTakePicturesModel:model];

    // 判断类型
    if (model.type == GMPhotoModelMediaTypeCameraPhoto) {
        if (self.manager.configuration.reverseDate) {
            [self.photoArray insertObject:model atIndex:0];
        }else {
            [self.photoArray addObject:model];
        }
    }else if (model.type == GMPhotoModelMediaTypeCameraVideo) {
        if (self.manager.configuration.reverseDate) {
            [self.videoArray insertObject:model atIndex:0];
        }else {
            [self.videoArray addObject:model];
        }
    }
    NSInteger cameraIndex = self.manager.configuration.openCamera ? 1 : 0;
    if (self.manager.configuration.reverseDate) {
        [self.allArray insertObject:model atIndex:cameraIndex];
        [self.previewArray insertObject:model atIndex:0];
    }else {
        NSInteger count = self.allArray.count - cameraIndex;
        [self.allArray insertObject:model atIndex:count];
        [self.previewArray addObject:model];
    }
    if (self.manager.configuration.showDateSectionHeader) {
        if (self.manager.configuration.reverseDate) {
            model.dateSection = 0;
            GMPhotoDateModel *dateModel = self.dateArray.firstObject;
            NSMutableArray *array = [NSMutableArray arrayWithArray:dateModel.photoModelArray];
            [array insertObject:model atIndex:cameraIndex];
            dateModel.photoModelArray = array;
            [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:cameraIndex inSection:0]]];
        }else {
            model.dateSection = self.dateArray.count - 1;
            GMPhotoDateModel *dateModel = self.dateArray.lastObject;
            NSMutableArray *array = [NSMutableArray arrayWithArray:dateModel.photoModelArray];
            NSInteger count = array.count - cameraIndex;
            [array insertObject:model atIndex:count];
            dateModel.photoModelArray = array;
            [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:count inSection:self.dateArray.count - 1]]];
        }
    }else {
        if (self.manager.configuration.reverseDate) {
            [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:cameraIndex inSection:0]]];
        }else {
            NSInteger count = self.allArray.count - 1;
            [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:count - cameraIndex inSection:0]]];
        }
    }
    [self.numberButton setTitle:[NSString stringWithFormat:@"%ld",[self.manager selectedCount]] forState: UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CustomCameraViewControllerDidDoneNotification" object:nil];
}
#pragma mark - < UICollectionViewDataSource >
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if (self.manager.configuration.showDateSectionHeader) {
        return [self.dateArray count];
    }
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.manager.configuration.showDateSectionHeader) {
        GMPhotoDateModel *dateModel = [self.dateArray objectAtIndex:section];
        return [dateModel.photoModelArray count];
    }
    return self.allArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GMPhotoModel *model;
    if (self.manager.configuration.showDateSectionHeader) {
        GMPhotoDateModel *dateModel = [self.dateArray objectAtIndex:indexPath.section];
        model = dateModel.photoModelArray[indexPath.item];
    }else {
        model = self.allArray[indexPath.item];
    }
    model.rowCount = self.manager.configuration.rowCount;
   
    model.dateCellIsVisible = YES;
    if (model.type == GMPhotoModelMediaTypeCamera) {
        GMDatePhotoCameraViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DateCameraCellId" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }else {

        if (self.manager.videoSelectedType == GMPhotoManagerVideoSelectedTypeSingle && !self.manager.videoCanSelected && model.subType == GMPhotoModelMediaSubTypeVideo) {
            model.videoUnableSelect = YES;
        }else {
            model.videoUnableSelect = NO;
        }
        GMDatePhotoViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DateCellId" forIndexPath:indexPath];
        cell.delegate = self;
        if (self.manager.configuration.cellSelectedTitleColor) {
            cell.selectedTitleColor = self.manager.configuration.cellSelectedTitleColor;
        }else if (self.manager.configuration.selectedTitleColor) {
            cell.selectedTitleColor = self.manager.configuration.selectedTitleColor;
        }
        if (self.manager.configuration.cellSelectedBgColor) {
            cell.selectBgColor = self.manager.configuration.cellSelectedBgColor;
        }else {
            cell.selectBgColor = self.manager.configuration.themeColor;
        }
        cell.model = model;
        cell.singleSelected = self.manager.configuration.singleSelected;
        if ([self.manager beforeSelectCountIsMaximum] && !model.selected) {
            cell.selectMaskLayer.hidden = NO;
        } else {
            if ([self.manager beforeSelectVideoCountIsMaximum]) {
                if ((cell.model.type == GMPhotoModelMediaTypeVideo) || (cell.model.type == GMPhotoModelMediaTypeCameraVideo)) {
                    cell.selectMaskLayer.hidden = NO;
                } else {
                    cell.selectMaskLayer.hidden = YES;
                }
            } else {
                cell.selectMaskLayer.hidden = YES;
            }
        }
        return cell;
    }
}
#pragma mark - < UICollectionViewDelegate >
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.navigationController.topViewController != self) {
        return;
    }
    GMPhotoModel *model;
    if (self.manager.configuration.showDateSectionHeader) {
        GMPhotoDateModel *dateModel = [self.dateArray objectAtIndex:indexPath.section];
        model = dateModel.photoModelArray[indexPath.item];
    }else {
        model = self.allArray[indexPath.item];
    }
    if (model.type == GMPhotoModelMediaTypeCamera) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            return;
        }
        __weak typeof(self) weakSelf = self;
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    if (weakSelf.manager.configuration.replaceCameraViewController) {
                        GMPhotoConfigurationCameraType cameraType;
                        if (weakSelf.manager.type == GMPhotoManagerSelectedTypePhoto) {
                            cameraType = GMPhotoConfigurationCameraTypePhoto;
                        }else if (weakSelf.manager.type == GMPhotoManagerSelectedTypeVideo) {
                            cameraType = GMPhotoConfigurationCameraTypeVideo;
                        }else {
                            if (!weakSelf.manager.configuration.selectTogether) {
                                if (weakSelf.manager.selectedPhotoArray.count > 0) {
                                    cameraType = GMPhotoConfigurationCameraTypePhoto;
                                }else if (weakSelf.manager.selectedVideoArray.count > 0) {
                                    cameraType = GMPhotoConfigurationCameraTypeVideo;
                                }else {
                                    cameraType = GMPhotoConfigurationCameraTypeTypePhotoAndVideo;
                                }
                            }else {
                                cameraType = GMPhotoConfigurationCameraTypeTypePhotoAndVideo;
                            }
                        }
                        if (weakSelf.manager.configuration.shouldUseCamera) {
                            weakSelf.manager.configuration.shouldUseCamera(weakSelf, cameraType, weakSelf.manager);
                        }
                        weakSelf.manager.configuration.useCameraComplete = ^(GMPhotoModel *model) {
                            if (model.videoDuration > weakSelf.manager.configuration.videoMaxDuration) {
                                [self showLoading:@"视频过大,无法选择"];
                            }
                        };
                        return;
                    }
                    GMCustomCameraViewController *vc = [[GMCustomCameraViewController alloc] init];
                    vc.delegate = weakSelf;
                    vc.manager = weakSelf.manager;
                    GMNavigationController *nav = [[GMNavigationController alloc] initWithRootViewController:vc];
                    [weakSelf presentViewController:nav animated:YES completion:nil];
                }else {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在设置-隐私-相机中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
                    [alert addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }]];
                    [weakSelf presentViewController:alert animated:YES completion:nil];
                }
            });
        }];
    }else {
        GMDatePhotoViewCell *cell = (GMDatePhotoViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        if (!self.manager.configuration.singleSelected) {
            NSInteger currentIndex = [self.previewArray indexOfObject:cell.model];
            GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
            previewVC.delegate = self;
            previewVC.modelArray = self.previewArray;
            previewVC.manager = self.manager;
            previewVC.currentModelIndex = currentIndex;
            self.navigationController.delegate = previewVC;
            [self.navigationController pushViewController:previewVC animated:YES];
        }else {
            if (!self.manager.configuration.singleJumpEdit) {
                NSInteger currentIndex = [self.previewArray indexOfObject:cell.model];
                GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
                previewVC.delegate = self;
                previewVC.modelArray = self.previewArray;
                previewVC.manager = self.manager;
                previewVC.currentModelIndex = currentIndex;
                self.navigationController.delegate = previewVC;
                [self.navigationController pushViewController:previewVC animated:YES];
            }else {
                    GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
                    previewVC.delegate = self;
                    previewVC.modelArray = [NSMutableArray arrayWithObjects:cell.model, nil];
                    previewVC.manager = self.manager;
                    previewVC.currentModelIndex = 0;
                    [self.navigationController pushViewController:previewVC animated:YES];
            }
        }
    }
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    GMPhotoModel *model;
    if (self.manager.configuration.showDateSectionHeader) {
        GMPhotoDateModel *dateModel = [self.dateArray objectAtIndex:indexPath.section];
        model = dateModel.photoModelArray[indexPath.item];
    }else {
        model = self.allArray[indexPath.item];
    }
    if (model.type != GMPhotoModelMediaTypeCamera) {
        //        model.dateCellIsVisible = NO;
        //        NSSLog(@"cell消失");
        [(GMDatePhotoViewCell *)cell cancelRequest];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader] && self.manager.configuration.showDateSectionHeader) {
        GMDatePhotoViewSectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionHeaderId" forIndexPath:indexPath];
        headerView.translucent = self.manager.configuration.sectionHeaderTranslucent;
        headerView.suspensionBgColor = self.manager.configuration.sectionHeaderSuspensionBgColor;
        headerView.suspensionTitleColor = self.manager.configuration.sectionHeaderSuspensionTitleColor;
        headerView.model = self.dateArray[indexPath.section];
        return headerView;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        if (self.manager.configuration.showBottomPhotoDetail) {
            GMDatePhotoViewSectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"sectionFooterId" forIndexPath:indexPath];
            footerView.photoCount = self.photoArray.count;
            footerView.videoCount = self.videoArray.count;
            self.footerView = footerView;
            return footerView;
        }
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (self.manager.configuration.showDateSectionHeader) {
        return CGSizeMake(self.view.gm_w, 49);
    }
    return CGSizeZero;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (self.manager.configuration.showDateSectionHeader) {
        if (section == self.dateArray.count - 1) {
            return self.manager.configuration.showBottomPhotoDetail ? CGSizeMake(self.view.gm_w, 50) : CGSizeZero;
        }else {
            return CGSizeZero;
        }
    }else {
        return self.manager.configuration.showBottomPhotoDetail ? CGSizeMake(self.view.gm_w, 50) : CGSizeZero;
    }
}

- (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:location];
    if (!indexPath) {
        return nil;
    }
    if (![[self.collectionView cellForItemAtIndexPath:indexPath] isKindOfClass:[GMDatePhotoViewCell class]]) {
        return nil;
    }
    GMDatePhotoViewCell *cell = (GMDatePhotoViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    if (!cell || cell.model.type == GMPhotoModelMediaTypeCamera ) {
        return nil;
    }
    if (cell.model.networkPhotoUrl) {
        if (cell.model.downloadError) {
            return nil;
        }
        if (!cell.model.downloadComplete) {
            return nil;
        }
    }
    //设置突出区域
    previewingContext.sourceRect = [self.collectionView cellForItemAtIndexPath:indexPath].frame;
    GMPhotoModel *model = cell.model;
    GMPhoto3DTouchViewController *vc = [[GMPhoto3DTouchViewController alloc] init];
    vc.model = model;
    vc.indexPath = indexPath;
    vc.image = cell.imageView.image;
    vc.preferredContentSize = model.previewViewSize;
    return vc;
}
- (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    GMPhoto3DTouchViewController *vc = (GMPhoto3DTouchViewController *)viewControllerToCommit;
    GMDatePhotoViewCell *cell = (GMDatePhotoViewCell *)[self.collectionView cellForItemAtIndexPath:vc.indexPath];
    if (!self.manager.configuration.singleSelected) {
        GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
        previewVC.delegate = self;
        previewVC.modelArray = self.previewArray;
        previewVC.manager = self.manager;
        cell.model.tempImage = vc.imageView.image;
        NSInteger currentIndex = [self.previewArray indexOfObject:cell.model];
        previewVC.currentModelIndex = currentIndex;
        self.navigationController.delegate = previewVC;
        [self.navigationController pushViewController:previewVC animated:YES];
    }else {
        if (vc.model.subType == GMPhotoModelMediaSubTypePhoto) {
//            GMDatePhotoEditViewController *vc = [[GMDatePhotoEditViewController alloc] init];
//            vc.model = cell.model;
//            vc.delegate = self;
//            vc.manager = self.manager;
//            [self.navigationController pushViewController:vc animated:NO];
        }else {
            GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
            previewVC.delegate = self;
            previewVC.modelArray = [NSMutableArray arrayWithObjects:cell.model, nil];
            previewVC.manager = self.manager;
            cell.model.tempImage = vc.imageView.image;
            previewVC.currentModelIndex = 0;
            self.navigationController.delegate = previewVC;
            [self.navigationController pushViewController:previewVC animated:YES];
        }
    }
}
#pragma mark - < GMDatePhotoViewCellDelegate >
- (void)datePhotoViewCellRequestICloudAssetComplete:(GMDatePhotoViewCell *)cell {
    if (cell.model.dateCellIsVisible) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self dateItem:cell.model] inSection:cell.model.dateSection];
        if (indexPath) {
            [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        }
        [self.manager addICloudModel:cell.model];
    }
}
- (void)datePhotoViewCell:(GMDatePhotoViewCell *)cell didSelectBtn:(UIButton *)selectBtn {
   
  
    if (selectBtn.selected) {
        BOOL isMax = [self.manager beforeSelectCountIsMaximum];
        BOOL isMaxVideo = [self.manager beforeSelectVideoCountIsMaximum];
        if (cell.model.type != GMPhotoModelMediaTypeCameraVideo && cell.model.type != GMPhotoModelMediaTypeCameraPhoto) {
            cell.model.thumbPhoto = nil;
            cell.model.previewPhoto = nil;
        }
        [self.manager beforeSelectedListdeletePhotoModel:cell.model];
        cell.model.selectIndexStr = @"";
        selectBtn.selected = NO;
        if ([self.manager beforeSelectVideoCountIsMaximum]) {
            [self.collectionView reloadData];
        }
        if (isMaxVideo) {
            [self.collectionView reloadData];
        }
        if (isMax) {
            [self.collectionView reloadData];
        }
    }else {
        NSString *str = [self.manager maximumOfJudgment:cell.model];
        if (str) {
            [self.view showImageHUDText:str];
            return;
        }
        if (cell.model.type != GMPhotoModelMediaTypeCameraVideo && cell.model.type != GMPhotoModelMediaTypeCameraPhoto) {
            cell.model.thumbPhoto = cell.imageView.image;
        }
        [self.manager beforeSelectedListAddPhotoModel:cell.model];
        selectBtn.selected = YES;
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
        anim.duration = 0.25;
        anim.values = @[@(1.2),@(0.8),@(1.1),@(0.9),@(1.0)];
        [selectBtn.layer addAnimation:anim forKey:@""];
        
        if ([self.manager beforeSelectVideoCountIsMaximum]) {
            [self.collectionView reloadData];
        }
        
        if ([self.manager beforeSelectCountIsMaximum]) {
            [self.collectionView reloadData];
        }
    }
    
    if ([self.delegate respondsToSelector:@selector(datePhotoViewControllerDidChangeSelect:selected:)]) {
        [self.delegate datePhotoViewControllerDidChangeSelect:cell.model selected:selectBtn.selected];
    }
    
    [self.numberButton setTitle:[NSString stringWithFormat:@"%ld",[self.manager selectedCount]] forState: UIControlStateNormal];
    
}
#pragma mark - < GMDatePhotoPreviewViewControllerDelegate >
- (void)datePhotoPreviewDownLoadICloudAssetComplete:(GMDatePhotoPreviewViewController *)previewController model:(GMPhotoModel *)model {
    if (model.dateCellIsVisible) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self dateItem:model] inSection:model.dateSection];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        [self.manager addICloudModel:model];
    }
}
- (void)datePhotoPreviewControllerDidSelect:(GMDatePhotoPreviewViewController *)previewController model:(GMPhotoModel *)model {
    NSMutableArray *indexPathList = [NSMutableArray array];
    if (model.currentAlbumIndex == self.albumModel.index) {
        [indexPathList addObject:[NSIndexPath indexPathForItem:[self dateItem:model] inSection:model.dateSection]];
    }
    if (!model.selected) {
        NSInteger index = 0;
        for (GMPhotoModel *subModel in [self.manager selectedArray]) {
            subModel.selectIndexStr = [NSString stringWithFormat:@"%ld",index + 1];
            if (subModel.currentAlbumIndex == self.albumModel.index && subModel.dateCellIsVisible) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self dateItem:subModel] inSection:subModel.dateSection];
                [indexPathList addObject:indexPath];
            }
            index++;
        }
    }
    
    if (self.manager.videoSelectedType == GMPhotoManagerVideoSelectedTypeSingle) {
        for (UICollectionViewCell *tempCell in self.collectionView.visibleCells) {
            if ([tempCell isKindOfClass:[GMDatePhotoViewCell class]]) {
                if ([(GMDatePhotoViewCell *)tempCell model].subType == GMPhotoModelMediaSubTypeVideo) {
                    [indexPathList addObject:[self.collectionView indexPathForCell:tempCell]];
                }
            }
        }
    }
    if (indexPathList.count) {
        [self.collectionView reloadItemsAtIndexPaths:indexPathList];
    }
    
    if ([self.delegate respondsToSelector:@selector(datePhotoViewControllerDidChangeSelect:selected:)]) {
        [self.delegate datePhotoViewControllerDidChangeSelect:model selected:model.selected];
    }
}
- (void)datePhotoPreviewControllerDidDone:(GMDatePhotoPreviewViewController *)previewController {
    [self datePhotoViewDidDoneBtn];
}
- (void)datePhotoPreviewDidEditClick:(GMDatePhotoPreviewViewController *)previewController {
    [self datePhotoViewDidDoneBtn];
}
- (void)datePhotoPreviewSingleSelectedClick:(GMDatePhotoPreviewViewController *)previewController model:(GMPhotoModel *)model {
    [self.manager beforeSelectedListAddPhotoModel:model];
    [self datePhotoViewDidDoneBtn];
}

- (void)datePhotoViewDidDoneBtn {
    [self cleanSelectedList];
    if (!self.manager.configuration.requestImageAfterFinishingSelection) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
#pragma mark - < GMDatePhotoEditViewControllerDelegate >
//- (void)datePhotoEditViewControllerDidClipClick:(GMDatePhotoEditViewController *)datePhotoEditViewController beforeModel:(GMPhotoModel *)beforeModel afterModel:(GMPhotoModel *)afterModel {
//    if (self.manager.configuration.singleSelected) {
//        [self.manager beforeSelectedListAddPhotoModel:afterModel];
//        [self datePhotoBottomViewDidDoneBtn];
//        return;
//    }
//    [self.manager beforeSelectedListdeletePhotoModel:beforeModel];
//
//    [self datePhotoPreviewControllerDidSelect:nil model:beforeModel];
//    [self customCameraViewController:nil didDone:afterModel];
//}
#pragma mark - < GMDatePhotoBottomViewDelegate >
- (void)datePhotoBottomViewDidPreviewBtn {
    if (self.navigationController.topViewController != self || [self.manager selectedCount] == 0) {
        return;
    }
    GMDatePhotoPreviewViewController *previewVC = [[GMDatePhotoPreviewViewController alloc] init];
    previewVC.delegate = self;
    previewVC.modelArray = [NSMutableArray arrayWithArray:[self.manager selectedArray]];
    previewVC.manager = self.manager;
    previewVC.currentModelIndex = 0;
    previewVC.selectPreview = YES;
    self.navigationController.delegate = previewVC;
    [self.navigationController pushViewController:previewVC animated:YES];
}

- (void)datePhotoBottomViewDidEditBtn {

}

- (void)cleanSelectedList {
    [self.manager selectedListTransformAfter];
    if (!self.manager.configuration.singleSelected) {
        if ([self.delegate respondsToSelector:@selector(datePhotoViewController:didDoneAllList:photos:videos:original:)]) {
            [self.delegate datePhotoViewController:self didDoneAllList:self.manager.afterSelectedArray.mutableCopy photos:self.manager.afterSelectedPhotoArray.mutableCopy videos:self.manager.afterSelectedVideoArray.mutableCopy original:self.manager.afterOriginal];
        }
    }else {
        if ([self.delegate respondsToSelector:@selector(datePhotoViewController:didDoneAllList:photos:videos:original:)]) {
            [self.delegate datePhotoViewController:self didDoneAllList:self.manager.selectedArray.mutableCopy photos:self.manager.selectedPhotoArray.mutableCopy videos:self.manager.selectedVideoArray.mutableCopy original:self.manager.original];
        }
    }
}
#pragma mark - < 懒加载 >

- (GMDatePhotoViewFlowLayout *)customLayout {
    if (!_customLayout) {
        _customLayout = [[GMDatePhotoViewFlowLayout alloc] init];
        _customLayout.minimumLineSpacing = 1;
        _customLayout.minimumInteritemSpacing = 1;
        _customLayout.sectionInset = UIEdgeInsetsMake(0.5, 0, 0.5, 0);
        if (@available(iOS 9.0, *)) {
            _customLayout.sectionHeadersPinToVisibleBounds = YES;
        }
    }
    return _customLayout;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGFloat collectionHeight = self.view.gm_h;
        if (self.manager.configuration.showDateSectionHeader) {
            _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.gm_w, collectionHeight) collectionViewLayout:self.customLayout];
        }else {
            _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.gm_w, collectionHeight) collectionViewLayout:self.flowLayout];
        }
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.alwaysBounceVertical = YES;
        [_collectionView registerClass:[GMDatePhotoViewCell class] forCellWithReuseIdentifier:@"DateCellId"];
        [_collectionView registerClass:[GMDatePhotoCameraViewCell class] forCellWithReuseIdentifier:@"DateCameraCellId"];
        [_collectionView registerClass:[GMDatePhotoViewSectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionHeaderId"];
        [_collectionView registerClass:[GMDatePhotoViewSectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"sectionFooterId"];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            self.automaticallyAdjustsScrollViewInsets = NO;
            if (self.manager.configuration.open3DTouchPreview) {
                if ([self respondsToSelector:@selector(traitCollection)]) {
                    if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)]) {
                        if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
                            self.previewingContext = [self registerForPreviewingWithDelegate:self sourceView:_collectionView];
                        }
                    }
                }
            }
        }
    }
        return _collectionView;
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.minimumLineSpacing = 1;
        _flowLayout.minimumInteritemSpacing = 1;
        _flowLayout.sectionInset = UIEdgeInsetsMake(0.5, 0, 0.5, 0);
    }
    return _flowLayout;
}
- (NSMutableArray *)allArray {
    if (!_allArray) {
        _allArray = [NSMutableArray array];
    }
    return _allArray;
}
- (NSMutableArray *)photoArray {
    if (!_photoArray) {
        _photoArray = [NSMutableArray array];
    }
    return _photoArray;
}
- (NSMutableArray *)videoArray {
    if (!_videoArray) {
        _videoArray = [NSMutableArray array];
    }
    return _videoArray;
}
- (NSMutableArray *)previewArray {
    if (!_previewArray) {
        _previewArray = [NSMutableArray array];
    }
    return _previewArray;
}
- (NSMutableArray *)dateArray {
    if (!_dateArray) {
        _dateArray = [NSMutableArray array];
    }
    return _dateArray;
}
- (void)dealloc {
    [self.collectionView.layer removeAllAnimations];
    if (self.manager.configuration.open3DTouchPreview) {
        if (self.previewingContext) {
            if (@available(iOS 9.0, *)) {
                [self unregisterForPreviewingWithContext:self.previewingContext];
            } else {
                // Fallback on earlier versions
            }
        }
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
@end

@interface GMDatePhotoCameraViewCell ()
@property (nonatomic, strong) UIButton *cameraBtn;
@property (nonatomic, strong) GMCustomCameraController *cameraController;
@property (nonatomic, strong) GMCustomPreviewView *previewView;
@end
    
@implementation GMDatePhotoCameraViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}
- (void)setupUI  {
    [self.contentView addSubview:self.previewView];
    [self.contentView addSubview:self.cameraBtn];
}
- (void)starRunning {
    if (![UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera]) {
        return;
    }
    if (self.cameraController.captureSession) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                if ([weakSelf.cameraController setupSession:nil]) {
                    [weakSelf.previewView setSession:weakSelf.cameraController.captureSession];
                    [weakSelf.cameraController startSession];
                    weakSelf.cameraBtn.selected = YES;
                }
            }
        });
    }];
}
- (void)stopRunning {
    if (![UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera]) {
        return;
    }
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus != AVAuthorizationStatusAuthorized) {
        return;
    }
    if (!self.cameraController.captureSession) {
        return;
    }
    [self.cameraController stopSession];
    self.cameraBtn.selected = NO;
}
- (void)setModel:(GMPhotoModel *)model {
    _model = model;
    [self.cameraBtn setImage:model.thumbPhoto forState:UIControlStateNormal];
    [self.cameraBtn setImage:model.previewPhoto forState:UIControlStateSelected];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.cameraBtn.frame = self.bounds;
    self.previewView.frame = self.bounds;
}
- (void)dealloc {
    [self stopRunning];
}
- (UIButton *)cameraBtn {
    if (!_cameraBtn) {
        _cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cameraBtn.userInteractionEnabled = NO;
    }
    return _cameraBtn;
}
- (GMCustomCameraController *)cameraController {
    if (!_cameraController) {
        _cameraController = [[GMCustomCameraController alloc] init];
    }
    return _cameraController;
}
- (GMCustomPreviewView *)previewView {
    if (!_previewView) {
        _previewView = [[GMCustomPreviewView alloc] init];
        _previewView.pinchToZoomEnabled = NO;
        _previewView.tapToFocusEnabled = NO;
        _previewView.tapToExposeEnabled = NO;
    }
    return _previewView;
}
@end

@interface GMDatePhotoViewCell ()
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *maskView;
@property (copy, nonatomic) NSString *localIdentifier;
@property (assign, nonatomic) PHImageRequestID requestID;
@property (assign, nonatomic) PHImageRequestID iCloudRequestID;
@property (nonatomic, strong) UILabel *stateLb;
@property (nonatomic, strong) CAGradientLayer *bottomMaskLayer;
@property (nonatomic, strong) GMButton *selectBtn;
@property (nonatomic, strong) UIImageView *iCloudIcon;
@property (nonatomic, strong) CALayer *iCloudMaskLayer;
@property (nonatomic, strong) CALayer *videoMaskLayer;
@end
    
@implementation GMDatePhotoViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    [self.contentView addSubview:self.imageView];
    [self.contentView addSubview:self.maskView];

}

- (void)bottomViewStartAnimation {
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.maskView.alpha = 1;
    } completion:nil];
}
- (void)setSingleSelected:(BOOL)singleSelected {
    _singleSelected = singleSelected;
    if (singleSelected) {
        [self.selectBtn removeFromSuperview];
    }
}
- (void)bottomViewPrepareAnimation {
    self.maskView.alpha = 0;
}

- (void)setModel:(GMPhotoModel *)model {
    _model = model;

    __weak typeof(self) weakSelf = self;
    if (model.type == GMPhotoModelMediaTypeCamera || model.type == GMPhotoModelMediaTypeCameraPhoto || model.type == GMPhotoModelMediaTypeCameraVideo) {
        if (model.networkPhotoUrl) {

        }else {
            self.imageView.image = model.thumbPhoto;
        }
    }else {
        self.imageView.image = nil;
        PHImageRequestID requestID = [GMPhotoTools getImageWithModel:model completion:^(UIImage *image, GMPhotoModel *model) {
            if (weakSelf.model == model) {
                weakSelf.imageView.image = image;
            }
        }];
        self.requestID = requestID;
    }
    if (model.type == GMPhotoModelMediaTypePhotoGif) {
        self.stateLb.text = @"GIF";
        self.stateLb.hidden = NO;
        self.bottomMaskLayer.hidden = NO;
    }else if (model.type == GMPhotoModelMediaTypeLivePhoto) {
        self.stateLb.text = @"Live";
        self.stateLb.hidden = NO;
        self.bottomMaskLayer.hidden = NO;
    }else {
        if (model.subType == GMPhotoModelMediaSubTypeVideo) {
            self.stateLb.text = model.videoTime;
            self.stateLb.hidden = NO;
            self.bottomMaskLayer.hidden = NO;
        }else {
            self.stateLb.hidden = YES;
            self.bottomMaskLayer.hidden = YES;
        }
    }
 
    self.selectMaskLayer.hidden = !model.selected;
    self.selectBtn.selected = model.selected;
    
    // 当前是否需要隐藏选择按钮
    if (model.needHideSelectBtn) {
        self.selectBtn.hidden = YES;
        self.selectBtn.userInteractionEnabled = NO;
    }else {
        self.selectBtn.hidden = NO;
        self.selectBtn.userInteractionEnabled = YES;
    }
    
    // 当前是否需要隐藏选择按钮
    if (model.needHideSelectBtn) {
        // 当前视频是否不可选
        self.videoMaskLayer.hidden = !model.videoUnableSelect;
        self.userInteractionEnabled = !model.videoUnableSelect;
    }else {
        self.videoMaskLayer.hidden = YES;
        self.userInteractionEnabled = YES;
    }
}
- (void)setSelectBgColor:(UIColor *)selectBgColor {
    _selectBgColor = selectBgColor;
    if ([selectBgColor isEqual:[UIColor whiteColor]] && !self.selectedTitleColor) {
        [self.selectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    }
}
- (void)setSelectedTitleColor:(UIColor *)selectedTitleColor {
    _selectedTitleColor = selectedTitleColor;
    [self.selectBtn setTitleColor:selectedTitleColor forState:UIControlStateSelected];
}
- (void)startRequestICloudAsset {

    self.iCloudIcon.hidden = YES;
    self.iCloudMaskLayer.hidden = YES;
    __weak typeof(self) weakSelf = self;
    if (self.model.type == GMPhotoModelMediaTypeVideo) {
        self.iCloudRequestID = [GMPhotoTools getAVAssetWithModel:self.model startRequestIcloud:^(GMPhotoModel *model, PHImageRequestID cloudRequestId) {
            if (weakSelf.model == model) {
                weakSelf.iCloudRequestID = cloudRequestId;
            }
        } progressHandler:^(GMPhotoModel *model, double progress) {
            if (weakSelf.model == model) {

            }
        } completion:^(GMPhotoModel *model, AVAsset *asset) {
            if (weakSelf.model == model) {
                if ([weakSelf.delegate respondsToSelector:@selector(datePhotoViewCellRequestICloudAssetComplete:)]) {
                    [weakSelf.delegate datePhotoViewCellRequestICloudAssetComplete:weakSelf];
                }
            }
        } failed:^(GMPhotoModel *model, NSDictionary *info) {
            if (weakSelf.model == model) {
                [weakSelf downloadError:info];
            }
        }];
    }else if (self.model.type == GMPhotoModelMediaTypeLivePhoto){
        if (@available(iOS 9.1, *)) {
            self.iCloudRequestID = [GMPhotoTools getLivePhotoWithModel:self.model size:CGSizeMake(self.model.previewViewSize.width * 1.5, self.model.previewViewSize.height * 1.5) startRequestICloud:^(GMPhotoModel *model, PHImageRequestID iCloudRequestId) {
                if (weakSelf.model == model) {
                    weakSelf.iCloudRequestID = iCloudRequestId;
                }
            } progressHandler:^(GMPhotoModel *model, double progress) {
                if (weakSelf.model == model) {

                }
            } completion:^(GMPhotoModel *model, PHLivePhoto *livePhoto) {
                if (weakSelf.model == model) {
                    if ([weakSelf.delegate respondsToSelector:@selector(datePhotoViewCellRequestICloudAssetComplete:)]) {
                        [weakSelf.delegate datePhotoViewCellRequestICloudAssetComplete:weakSelf];
                    }
                }
            } failed:^(GMPhotoModel *model, NSDictionary *info) {
                if (weakSelf.model == model) {
                    [weakSelf downloadError:info];
                }
            }];
        } else {
        }
    }else {
        self.iCloudRequestID = [GMPhotoTools getImageDataWithModel:self.model startRequestIcloud:^(GMPhotoModel *model, PHImageRequestID cloudRequestId) {
            if (weakSelf.model == model) {
                weakSelf.iCloudRequestID = cloudRequestId;
            }
        } progressHandler:^(GMPhotoModel *model, double progress) {
            if (weakSelf.model == model) {

            }
        } completion:^(GMPhotoModel *model, NSData *imageData, UIImageOrientation orientation) {
            if (weakSelf.model == model) {
                if ([weakSelf.delegate respondsToSelector:@selector(datePhotoViewCellRequestICloudAssetComplete:)]) {
                    [weakSelf.delegate datePhotoViewCellRequestICloudAssetComplete:weakSelf];
                }
            }
        } failed:^(GMPhotoModel *model, NSDictionary *info) {
            if (weakSelf.model == model) {
                [weakSelf downloadError:info];
            }
        }];
    }
}
- (void)downloadError:(NSDictionary *)info {

}
- (void)cancelRequest {
#if __has_include(<SDWebImage/UIImageView+WebCache.h>) || __has_include("UIImageView+WebCache.h")
    [self.imageView sd_cancelCurrentAnimationImagesLoad];
#endif
    if (self.requestID) {
        [[PHImageManager defaultManager] cancelImageRequest:self.requestID];
        self.requestID = -1;
    }
    if (self.iCloudRequestID) {
        [[PHImageManager defaultManager] cancelImageRequest:self.iCloudRequestID];
        self.iCloudRequestID = -1;
    }
}
- (void)didSelectClick:(UIButton *)button {
    if (self.model.type == GMPhotoModelMediaTypeCamera) {
        return;
    }

    if ([self.delegate respondsToSelector:@selector(datePhotoViewCell:didSelectBtn:)]) {
        [self.delegate datePhotoViewCell:self didSelectBtn:button];
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = self.bounds;
    self.maskView.frame = self.bounds;
    self.stateLb.frame = CGRectMake(0, self.gm_h - 18, self.gm_w - 4, 18);
    self.bottomMaskLayer.frame = CGRectMake(0, self.gm_h - 25, self.gm_w, 25);
    self.selectBtn.frame = CGRectMake(self.gm_w - 27, 2, 25, 25);
    self.selectMaskLayer.frame = self.bounds;
    self.iCloudMaskLayer.frame = self.bounds;
    self.iCloudIcon.gm_x = self.gm_w - 3 - self.iCloudIcon.gm_w;
    self.iCloudIcon.gm_y = 3;

    self.videoMaskLayer.frame = self.bounds;
}
- (void)dealloc {
    self.model.dateCellIsVisible = NO;
}
#pragma mark - < 懒加载 >

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
    }
    return _imageView;
}
- (UIView *)maskView {
    if (!_maskView) {
        _maskView = [[UIView alloc] init];
        _maskView.backgroundColor = [UIColor clearColor];
        [_maskView.layer addSublayer:self.bottomMaskLayer];
        [_maskView.layer addSublayer:self.selectMaskLayer];
        [_maskView.layer addSublayer:self.iCloudMaskLayer];
        [_maskView.layer addSublayer:self.videoMaskLayer];
        [_maskView addSubview:self.iCloudIcon];
        [_maskView addSubview:self.stateLb];
        [_maskView addSubview:self.selectBtn];
    }
    return _maskView;
}
- (UIImageView *)iCloudIcon {
    if (!_iCloudIcon) {
        _iCloudIcon = [[UIImageView alloc] initWithImage:[GMPhotoTools GM_imageNamed:@"icon_yunxiazai@2x.png"]];
        _iCloudIcon.hidden = YES;
        _iCloudIcon.gm_size = _iCloudIcon.image.size;
    }
    return _iCloudIcon;
}
- (CALayer *)selectMaskLayer {
    if (!_selectMaskLayer) {
        _selectMaskLayer = [CALayer layer];
        _selectMaskLayer.hidden = YES;
        _selectMaskLayer.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.66].CGColor;
    }
    return _selectMaskLayer;
}
- (CALayer *)iCloudMaskLayer {
    if (!_iCloudMaskLayer) {
        _iCloudMaskLayer = [CALayer layer];
        _iCloudMaskLayer.hidden = YES;
        _iCloudMaskLayer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.44].CGColor;
    }
    return _iCloudMaskLayer;
}
- (CALayer *)videoMaskLayer {
    if (!_videoMaskLayer) {
        _videoMaskLayer = [CALayer layer];
        _videoMaskLayer.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5].CGColor;
    }
    return _videoMaskLayer;
}
- (UILabel *)stateLb {
    if (!_stateLb) {
        _stateLb = [[UILabel alloc] init];
        _stateLb.textColor = [UIColor whiteColor];
        _stateLb.textAlignment = NSTextAlignmentRight;
        _stateLb.font = [UIFont gmFont:12];
    }
    return _stateLb;
}
- (CAGradientLayer *)bottomMaskLayer {
    if (!_bottomMaskLayer) {
        _bottomMaskLayer = [CAGradientLayer layer];
        _bottomMaskLayer.colors = @[
                                    (id)[[UIColor blackColor] colorWithAlphaComponent:0].CGColor,
                                    (id)[[UIColor blackColor] colorWithAlphaComponent:0.35].CGColor
                                    ];
        _bottomMaskLayer.startPoint = CGPointMake(0, 0);
        _bottomMaskLayer.endPoint = CGPointMake(0, 1);
        _bottomMaskLayer.locations = @[@(0.15f),@(0.9f)];
        _bottomMaskLayer.borderWidth  = 0.0;
    }
    return _bottomMaskLayer;
}
- (GMButton *)selectBtn {
    if (!_selectBtn) {
        _selectBtn = [GMButton buttonWithType:UIButtonTypeCustom];
        [_selectBtn setBackgroundImage:[UIImage imageNamed:@"album_cell_normal"] forState:UIControlStateNormal];
        [_selectBtn setBackgroundImage:[UIImage imageNamed:@"album_cell_selected"] forState:UIControlStateSelected];
        [_selectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        _selectBtn.titleLabel.font = [UIFont gmFont:14];
        _selectBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        [_selectBtn addTarget:self action:@selector(didSelectClick:) forControlEvents:UIControlEventTouchUpInside];
        _selectBtn.layer.cornerRadius = 25 / 2;
        _selectBtn.enableAdaptive = YES;
        _selectBtn.adaptiveHotAreaWidth = 60;
        _selectBtn.adaptiveHotAreaHeight = 60;
    }
    return _selectBtn;
}
@end
    
@interface GMDatePhotoViewSectionHeaderView ()
@property (nonatomic, strong) UILabel *dateLb;
@property (nonatomic, strong) UILabel *subTitleLb;
@property (nonatomic, strong) UIToolbar *bgView;
@end
    
@implementation GMDatePhotoViewSectionHeaderView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    [self addSubview:self.bgView];
    [self addSubview:self.dateLb];
    [self addSubview:self.subTitleLb];
}
- (void)setChangeState:(BOOL)changeState {
    _changeState = changeState;
    if (self.translucent) {
        self.bgView.translucent = changeState;
    }
    if (self.suspensionBgColor) {
        self.translucent = NO;
    }
    if (changeState) {
        if (self.translucent) {
            self.bgView.alpha = 1;
        }
        if (self.suspensionTitleColor) {
            self.dateLb.textColor = self.suspensionTitleColor;
            self.subTitleLb.textColor = self.suspensionTitleColor;
        }
        if (self.suspensionBgColor) {
            self.bgView.barTintColor = self.suspensionBgColor;
        }
    }else {
        if (!self.translucent) {
            self.bgView.barTintColor = [UIColor whiteColor];
        }
        if (self.translucent) {
            self.bgView.alpha = 0;
        }
        self.dateLb.textColor = [UIColor blackColor];
        self.subTitleLb.textColor = [UIColor blackColor];
    }
}
- (void)setTranslucent:(BOOL)translucent {
    _translucent = translucent;
    if (!translucent) {
        self.bgView.translucent = YES;
        self.bgView.barTintColor = [UIColor whiteColor];
    }
}
- (void)setModel:(GMPhotoDateModel *)model {
    _model = model;
//    暂时不需要展示位置信息
//    if (model.location) {
//        if (model.hasLocationTitles) {
//            self.dateLb.frame = CGRectMake(8, 4, self.gm_w - 16, 30);
//            self.subTitleLb.hidden = NO;
//            self.subTitleLb.text = model.locationSubTitle;
//            self.dateLb.text = model.locationTitle;
//        }else {
//            self.dateLb.frame = CGRectMake(8, 0, self.gm_w - 16, 50);
//            self.dateLb.text = model.dateString;
//            self.subTitleLb.hidden = YES;
//            __weak typeof(self) weakSelf = self;
//            [GMPhotoTools getDateLocationDetailInformationWithModel:model completion:^(CLPlacemark *placemark, GMPhotoDateModel *model) {
//                if (placemark.locality) {
//                    NSString *province = placemark.administrativeArea;
//                    NSString *city = placemark.locality;
//                    NSString *area = placemark.subLocality;
//                    NSString *street = placemark.thoroughfare;
//                    NSString *subStreet = placemark.subThoroughfare;
//                    if (area) {
//                        model.locationTitle = [NSString stringWithFormat:@"%@ ﹣ %@",city,area];
//                    }else {
//                        model.locationTitle = [NSString stringWithFormat:@"%@",city];
//                    }
//                    if (street) {
//                        if (subStreet) {
//                            model.locationSubTitle = [NSString stringWithFormat:@"%@・%@%@",model.dateString,street,subStreet];
//                        }else {
//                            model.locationSubTitle = [NSString stringWithFormat:@"%@・%@",model.dateString,street];
//                        }
//                    }else if (province) {
//                        model.locationSubTitle = [NSString stringWithFormat:@"%@・%@",model.dateString,province];
//                    }else {
//                        model.locationSubTitle = [NSString stringWithFormat:@"%@・%@",model.dateString,city];
//                    }
//                }else {
//                    NSString *province = placemark.administrativeArea;
//                    model.locationSubTitle = [NSString stringWithFormat:@"%@・%@",model.dateString,province];
//                    model.locationTitle = province;
//                }
//                model.hasLocationTitles = YES;
//                if (weakSelf.model == model) {
//                    weakSelf.subTitleLb.text = model.locationSubTitle;
//                    weakSelf.dateLb.text = model.locationTitle;
//                    weakSelf.dateLb.frame = CGRectMake(8, 4, weakSelf.gm_w - 16, 30);
//                    weakSelf.subTitleLb.hidden = NO;
//                }
//            }];
//        }
//    }else {
        self.dateLb.frame = CGRectMake(20, 20, self.gm_w - 40, 15);
        self.dateLb.text = model.dateString;
        self.subTitleLb.hidden = YES;
//    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.bgView.frame = self.bounds;
}
- (UILabel *)dateLb {
    if (!_dateLb) {
        _dateLb = [[UILabel alloc] init];
        _dateLb.textColor = RGBCOLOR_HEX(0x282828);
        _dateLb.font = [UIFont gmFont:15];//[UIFont systemFontOfSize:15];
    }
    return _dateLb;
}
- (UIToolbar *)bgView {
    if (!_bgView) {
        _bgView = [[UIToolbar alloc] init];
        _bgView.translucent = NO;
        _bgView.clipsToBounds = YES;
    }
    return _bgView;
}
- (UILabel *)subTitleLb {
    if (!_subTitleLb) {
        _subTitleLb = [[UILabel alloc] init];
        _subTitleLb.textColor = [UIColor blackColor];
        _subTitleLb.font = [UIFont gmFont:11];
    }
    return _subTitleLb;
}
@end
    
@interface GMDatePhotoViewSectionFooterView ()
@property (nonatomic, strong) UILabel *titleLb;
@end
    
@implementation GMDatePhotoViewSectionFooterView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.titleLb];
}
- (void)setVideoCount:(NSInteger)videoCount {
    _videoCount = videoCount;
    if (self.photoCount > 0 && videoCount > 0) {
        NSString *photoStr;
        if (self.photoCount > 1) {
            photoStr = @"Photos";
        }else {
            photoStr = @"Photo";
        }
        NSString *videoStr;
        if (videoCount > 1) {
            videoStr = @"Videos";
        }else {
            videoStr = @"Video";
        }
        self.titleLb.text = [NSString stringWithFormat:@"%ld %@、%ld %@",self.photoCount,photoStr,videoCount,videoStr];
        
    }else if (self.photoCount > 0) {
        NSString *photoStr;
        if (self.photoCount > 1) {
            photoStr = @"Photos";
        }else {
            photoStr = @"Photo";
        }
        self.titleLb.text = [NSString stringWithFormat:@"%ld %@",self.photoCount,photoStr];
    }else {
        NSString *videoStr;
        if (videoCount > 1) {
            videoStr = @"Videos";
        }else {
            videoStr = @"Video";
        }
        self.titleLb.text = [NSString stringWithFormat:@"%ld %@",videoCount,
                             videoStr];
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.titleLb.frame = CGRectMake(0, 0, self.gm_w, 50);
}
- (UILabel *)titleLb {
    if (!_titleLb) {
        _titleLb = [[UILabel alloc] init];
        _titleLb.textColor = [UIColor blackColor];
        _titleLb.textAlignment = NSTextAlignmentCenter;
        _titleLb.font = [UIFont gmFont:15];
    }
    return _titleLb;
}
@end
    
@interface GMDatePhotoBottomView ()
@property (nonatomic, strong) UIButton *previewBtn;
@property (nonatomic, strong) UIButton *doneBtn;
@property (nonatomic, strong) UIButton *editBtn;
@end
    
@implementation GMDatePhotoBottomView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}
- (void)setupUI {
    [self addSubview:self.bgView];
    [self addSubview:self.previewBtn];
    [self addSubview:self.originalBtn];
    [self addSubview:self.doneBtn];
    [self addSubview:self.editBtn];
    [self changeDoneBtnFrame];
}
- (void)setManager:(GMPhotoManager *)manager {
    _manager = manager;
    if (manager.type == GMPhotoManagerSelectedTypePhoto) {
        self.editBtn.hidden = !manager.configuration.photoCanEdit;
    }else if (manager.type == GMPhotoManagerSelectedTypeVideo) {
        self.originalBtn.hidden = YES;
    }else {

    }
    self.originalBtn.selected = self.manager.original;
    
    [self.previewBtn setTitleColor:self.manager.configuration.themeColor forState:UIControlStateNormal];
    [self.previewBtn setTitleColor:[self.manager.configuration.themeColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
    self.doneBtn.backgroundColor = [self.manager.configuration.themeColor colorWithAlphaComponent:0.5];
    [self.originalBtn setTitleColor:self.manager.configuration.themeColor forState:UIControlStateNormal];
    [self.originalBtn setTitleColor:[self.manager.configuration.themeColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
    [self.originalBtn setImage:[GMPhotoTools GM_imageNamed:self.manager.configuration.originalNormalImageName] forState:UIControlStateNormal];
    [self.originalBtn setImage:[GMPhotoTools GM_imageNamed:self.manager.configuration.originalSelectedImageName] forState:UIControlStateSelected];
    [self.editBtn setTitleColor:self.manager.configuration.themeColor forState:UIControlStateNormal];
    [self.editBtn setTitleColor:[self.manager.configuration.themeColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
    if ([self.manager.configuration.themeColor isEqual:[UIColor whiteColor]]) {
        [self.doneBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.doneBtn setTitleColor:[[UIColor blackColor] colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
    }
    if (self.manager.configuration.selectedTitleColor) {
        [self.doneBtn setTitleColor:self.manager.configuration.selectedTitleColor forState:UIControlStateNormal];
        [self.doneBtn setTitleColor:[self.manager.configuration.selectedTitleColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
    }
}
- (void)setSelectCount:(NSInteger)selectCount {
    _selectCount = selectCount;
    if (selectCount <= 0) {
        self.previewBtn.enabled = NO;
        self.doneBtn.enabled = NO;
        [self.doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    }else {
        self.previewBtn.enabled = YES;
        self.doneBtn.enabled = YES;
    }
    
    self.doneBtn.backgroundColor = self.doneBtn.enabled ? self.manager.configuration.themeColor : [self.manager.configuration.themeColor colorWithAlphaComponent:0.5];
    [self changeDoneBtnFrame];
    
    if (!self.manager.configuration.selectTogether) {
        if (self.manager.selectedPhotoArray.count) {
            self.editBtn.enabled = self.manager.configuration.photoCanEdit;
        }else if (self.manager.selectedVideoArray.count) {
        }else {
            self.editBtn.enabled = NO;
        }
    }else {
        if (self.manager.selectedArray.count) {
            GMPhotoModel *model = self.manager.selectedArray.firstObject;
            if (model.subType == GMPhotoModelMediaSubTypePhoto) {
                self.editBtn.enabled = self.manager.configuration.photoCanEdit;
            }else {
            }
        }else {
            self.editBtn.enabled = NO;
        }
    }
    if (self.manager.selectedPhotoArray.count == 0) {
        self.originalBtn.enabled = NO;
        self.originalBtn.selected = NO;
        [self.manager setOriginal:NO] ;
    }else {
        self.originalBtn.enabled = YES;
    }
}
- (void)changeDoneBtnFrame {
    CGFloat width = [GMPhotoTools getTextWidth:self.doneBtn.currentTitle height:30 fontSize:14];
    self.doneBtn.gm_w = width + 20;
    if (self.doneBtn.gm_w < 50) {
        self.doneBtn.gm_w = 50;
    }
    self.doneBtn.gm_x = self.gm_w - 12 - self.doneBtn.gm_w;
}
- (void)didDoneBtnClick {
    if ([self.delegate respondsToSelector:@selector(datePhotoBottomViewDidDoneBtn)]) {
        [self.delegate datePhotoBottomViewDidDoneBtn];
    }
}
- (void)didPreviewClick {
    if ([self.delegate respondsToSelector:@selector(datePhotoBottomViewDidPreviewBtn)]) {
        [self.delegate datePhotoBottomViewDidPreviewBtn];
    }
}
- (void)didEditBtnClick {
    if ([self.delegate respondsToSelector:@selector(datePhotoBottomViewDidEditBtn)]) {
        [self.delegate datePhotoBottomViewDidEditBtn];
    }
}
- (void)didOriginalClick:(UIButton *)button {
    button.selected = !button.selected;
    [self.manager setOriginal:button.selected];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.bgView.frame = self.bounds;
    self.previewBtn.frame = CGRectMake(12, 0, [GMPhotoTools getTextWidth:self.previewBtn.currentTitle height:50 fontSize:16], 50);
    self.previewBtn.center = CGPointMake(self.previewBtn.center.x, 25);
    self.editBtn.frame = CGRectMake(CGRectGetMaxX(self.previewBtn.frame) + 10, 0, [GMPhotoTools getTextWidth:self.editBtn.currentTitle height:50 fontSize:16], 50);
    if (self.editBtn.hidden) {
        self.originalBtn.frame = CGRectMake(CGRectGetMaxX(self.previewBtn.frame) + 10, 0, 80, 50);
    }else {
        self.originalBtn.frame = CGRectMake(CGRectGetMaxX(self.editBtn.frame) + 10, 0, [GMPhotoTools getTextWidth:self.originalBtn.currentTitle height:50 fontSize:16] + 20, 50);
        self.originalBtn.imageEdgeInsets = UIEdgeInsetsMake(0, [GMPhotoTools getTextWidth:self.originalBtn.currentTitle height:50 fontSize:16] , 0, 0);
    }
    self.doneBtn.frame = CGRectMake(0, 0, 50, 30);
    self.doneBtn.center = CGPointMake(self.doneBtn.center.x, 25);
    [self changeDoneBtnFrame];
}
- (UIToolbar *)bgView {
    if (!_bgView) {
        _bgView = [[UIToolbar alloc] init];
    }
    return _bgView;
}
- (UIButton *)previewBtn {
    if (!_previewBtn) {
        _previewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_previewBtn setTitle:@"预览" forState:UIControlStateNormal];
        _previewBtn.titleLabel.font = [UIFont gmFont:16];
        _previewBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_previewBtn addTarget:self action:@selector(didPreviewClick) forControlEvents:UIControlEventTouchUpInside];
        _previewBtn.enabled = NO;
    }
    return _previewBtn;
}
- (UIButton *)doneBtn {
    if (!_doneBtn) {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_doneBtn setTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
        _doneBtn.titleLabel.font = [UIFont gmFont:14];
        _doneBtn.layer.cornerRadius = 3;
        _doneBtn.enabled = NO;
        [_doneBtn addTarget:self action:@selector(didDoneBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneBtn;
}
- (UIButton *)originalBtn {
    if (!_originalBtn) {
        _originalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_originalBtn setTitle:@"原图" forState:UIControlStateNormal];
        [_originalBtn addTarget:self action:@selector(didOriginalClick:) forControlEvents:UIControlEventTouchUpInside];
        _originalBtn.titleLabel.font = [UIFont gmFont:16];
        _originalBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 35, 0, 0);
        _originalBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
        _originalBtn.enabled = NO;
        _originalBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    }
    return _originalBtn;
}
- (UIButton *)editBtn {
    if (!_editBtn) {
        _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        _editBtn.titleLabel.font = [UIFont gmFont:16];;
        _editBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_editBtn addTarget:self action:@selector(didEditBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _editBtn.enabled = NO;
    }
    return _editBtn;
}
@end
