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

#import "GMDatePhotoPreviewViewController.h"
#import "UIImage+GMExtension.h"
#import "GMPhotoDefine.h"
#import "UIView+GMExtension.h"
#import "GMPhotoTools.h"
#import "GMDatePhotoEditViewController.h"
#import "GMPhotoCustomNavigationBar.h"
#import "GMTopicTools.h"
@interface GMDatePhotoPreviewViewController ()
<
UICollectionViewDataSource,
UICollectionViewDelegate
>
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) GMPhotoModel *currentModel;
@property (strong, nonatomic) UIView *customTitleView;
@property (strong, nonatomic) UILabel *titleLb;
@property (strong, nonatomic) UILabel *subTitleLb;
@property (strong, nonatomic) GMDatePhotoPreviewViewCell *tempCell;
@property (strong, nonatomic) UIButton *selectBtn;
@property (assign, nonatomic) BOOL orientationDidChange;
@property (assign, nonatomic) NSInteger beforeOrientationIndex;

//@property (strong, nonatomic) GMPhotoCustomNavigationBar *navBar;
@property (strong, nonatomic) UINavigationItem *navItem;
@property (assign, nonatomic) BOOL isAddInteractiveTransition;
@property (strong, nonatomic) UIView *dismissTempTopView;
@end

@implementation GMDatePhotoPreviewViewController
- (instancetype)init {
    self = [super init];
    if (self) {
        self.transitioningDelegate = self;
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    self.navigationBar.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.6];
    self.navigationBar.itemView.backgroundColor = [UIColor clearColor];
    self.navigationBar.titleView.backgroundColor = [UIColor clearColor];
    self.navigationBar.isShowShadow = NO;
    self.navigationBar.leftIcon = @"backWhite";
    [self.navigationBar.rightButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    if ([self.manager selectedCount ]) {
        self.navigationBar.rightTitle = [NSString stringWithFormat:@"下一步(%ld)",[self.manager selectedCount]];
    } else {
        self.navigationBar.rightTitle = @"下一步";
    }
}

-(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;
                if ([weakSelf.delegate respondsToSelector:@selector(datePhotoPreviewControllerDidDone:)]) {
                    [weakSelf.delegate datePhotoPreviewControllerDidDone:weakSelf];
                }
            }, ^{
                weakSelf.manager.configuration.isSpiltDate = YES;
                if ([weakSelf.delegate respondsToSelector:@selector(datePhotoPreviewControllerDidDone:)]) {
                    [weakSelf.delegate datePhotoPreviewControllerDidDone:weakSelf];
                }
            });
        } else {
            weakSelf.manager.configuration.isSpiltDate = NO;
            if ([weakSelf.delegate respondsToSelector:@selector(datePhotoPreviewControllerDidDone:)]) {
                [weakSelf.delegate datePhotoPreviewControllerDidDone:weakSelf];
            }
        }
        
    } else {
        self.manager.configuration.isSpiltDate = NO;
        if ([weakSelf.delegate respondsToSelector:@selector(datePhotoPreviewControllerDidDone:)]) {
            [weakSelf.delegate datePhotoPreviewControllerDidDone:weakSelf];
        }
    }
}
- (GMDatePhotoPreviewViewCell *)currentPreviewCell:(GMPhotoModel *)model {
    if (!model) {
        return nil;
    }
    return (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
}
- (void)changeSubviewFrame {
    self.titleLb.hidden = NO;
    CGFloat bottomMargin = kBottomMargin;

    CGFloat width = self.view.gm_w;
    CGFloat itemMargin = 20;

    self.flowLayout.itemSize = CGSizeMake(width, self.view.gm_h - kTopMargin - bottomMargin);
    self.flowLayout.minimumLineSpacing = itemMargin;
    [self.collectionView setCollectionViewLayout:self.flowLayout];
    self.collectionView.frame = CGRectMake(-(itemMargin / 2), kTopMargin,self.view.gm_w + itemMargin, self.view.gm_h - kTopMargin- bottomMargin);
    
    self.collectionView.contentSize = CGSizeMake(self.modelArray.count * (self.view.gm_w + itemMargin), 0);
    [self.collectionView setContentOffset:CGPointMake(self.beforeOrientationIndex * (self.view.gm_w + itemMargin), 0)];
    [UIView performWithoutAnimation:^{
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.beforeOrientationIndex inSection:0]]];
    }];
    
    if (self.manager.configuration.previewCollectionView) {
        self.manager.configuration.previewCollectionView(self.collectionView);
    }
}

- (UIButton *)selectBtn {
    if (!_selectBtn) {
        _selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_selectBtn setBackgroundImage:[UIImage imageNamed:@"album_cell_normal"] forState:UIControlStateNormal];
        [_selectBtn setBackgroundImage:[UIImage imageNamed:@"album_cell_selected"] forState:UIControlStateSelected];
        _selectBtn.titleLabel.font = [UIFont gmFont:14];
        _selectBtn.adjustsImageWhenDisabled = YES;
        [_selectBtn addTarget:self action:@selector(didSelectClick:) forControlEvents:UIControlEventTouchUpInside];
        _selectBtn.layer.cornerRadius = 12;
        [self.view addSubview:_selectBtn];
        _selectBtn.frame = CGRectMake(self.view.gm_w - 45, OCNavigationBar.barHeight + 20, 25, 25);
    }
    return _selectBtn;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    GMPhotoModel *model = self.modelArray[self.currentModelIndex];
    self.currentModel = model;
    GMDatePhotoPreviewViewCell *cell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
    if (!cell) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            GMDatePhotoPreviewViewCell *tempCell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
            self.tempCell = tempCell;
            [tempCell requestHDImage];
        });
    }else {
        self.tempCell = cell;
        [cell requestHDImage];
    }
    if (!self.isAddInteractiveTransition) {
        if (!self.outside) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            });
        }else if (!self.disableaPersentInteractiveTransition) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            });
        }
        self.isAddInteractiveTransition = YES;
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    GMDatePhotoPreviewViewCell *cell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
    cell.stopCancel = self.stopCancel;
    [cell cancelRequest];
    self.stopCancel = NO;
}
- (void)setupUI {
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.collectionView];

    self.beforeOrientationIndex = self.currentModelIndex;
    [self changeSubviewFrame];
    GMPhotoModel *model = self.modelArray[self.currentModelIndex];

    if (!self.outside) {
        
    self.selectBtn.selected = model.selected;

    if (self.manager.configuration.singleSelected) {
        self.selectBtn.hidden = YES;
    }else {
#pragma mark - < 单选视频时隐藏选择按钮 >
            if (model.needHideSelectBtn) {
                self.selectBtn.hidden = YES;
                self.selectBtn.userInteractionEnabled = NO;
            }
        }
    }else {

    }
}

- (void)didSelectClick:(UIButton *)button {
    if (self.modelArray.count <= 0 || self.outside) {
        return;
    }
    GMPhotoModel *model = self.modelArray[self.currentModelIndex];
    if (button.selected) {
        button.selected = NO;
        [self.manager beforeSelectedListdeletePhotoModel:model];
    }else {
        NSString *str = [self.manager maximumOfJudgment:model];
        if (str) {
            [self.view showImageHUDText:str];
            return;
        }
        GMDatePhotoPreviewViewCell *cell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
        if (model.type == GMPhotoModelMediaTypePhotoGif) {
            if (cell.imageView.image.images.count > 0) {
                model.thumbPhoto = cell.imageView.image.images.firstObject;
                model.previewPhoto = cell.imageView.image.images.firstObject;
            }else {
                model.thumbPhoto = cell.imageView.image;
                model.previewPhoto = cell.imageView.image;
            }
        }else {
            model.thumbPhoto = cell.imageView.image;
            model.previewPhoto = cell.imageView.image;
        }
        [self.manager beforeSelectedListAddPhotoModel:model];
        button.selected = YES;
        CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
        anim.duration = 0.25;
        anim.values = @[@(1.2),@(0.8),@(1.1),@(0.9),@(1.0)];
        [button.layer addAnimation:anim forKey:@""];
    }
    if ([self.delegate respondsToSelector:@selector(datePhotoPreviewControllerDidSelect:model:)]) {
        [self.delegate datePhotoPreviewControllerDidSelect:self model:model];
    }
    if ([self.manager selectedCount]) {
        self.navigationBar.rightTitle = [NSString stringWithFormat:@"下一步(%ld)",[self.manager selectedCount]];
    } else {
        self.navigationBar.rightTitle = @"下一步";
    }
}
#pragma mark - < UICollectionViewDataSource >
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.modelArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GMDatePhotoPreviewViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DatePreviewCellId" forIndexPath:indexPath];
    GMPhotoModel *model = self.modelArray[indexPath.item];
    cell.model = model;
    __weak typeof(self) weakSelf = self;
    [cell setCellDidPlayVideoBtn:^(BOOL play) {
        [weakSelf setSubviewAlphaAnimate:YES];
    }];
    [cell setCellDownloadICloudAssetComplete:^(GMDatePhotoPreviewViewCell *myCell) {
        if ([weakSelf.delegate respondsToSelector:@selector(datePhotoPreviewDownLoadICloudAssetComplete:model:)]) {
            [weakSelf.delegate datePhotoPreviewDownLoadICloudAssetComplete:weakSelf model:myCell.model];
        }
    }];
    [cell setCellTapClick:^{
        [weakSelf setSubviewAlphaAnimate:YES];
    }];
    return cell;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)setSubviewAlphaAnimate:(BOOL)animete duration:(NSTimeInterval)duration {
    BOOL hide = NO;
    if (!self.navigationBar.hidden) {
        hide = YES;
    }
    if (animete) {
//        [[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:UIStatusBarAnimationFade];
        [UIView animateWithDuration:duration animations:^{
            self.navigationBar.hidden = hide;
        } completion:^(BOOL finished) {
        }];
    } else {
//        [[UIApplication sharedApplication] setStatusBarHidden:hide withAnimation:UIStatusBarAnimationFade];
         self.navigationBar.hidden = hide;
    }
    
}
- (void)setSubviewAlphaAnimate:(BOOL)animete {
    [self setSubviewAlphaAnimate:animete duration:0.15];
}
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [(GMDatePhotoPreviewViewCell *)cell resetScale];
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [(GMDatePhotoPreviewViewCell *)cell cancelRequest];
}
#pragma mark - < UICollectionViewDelegate >
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat offsetx = self.collectionView.contentOffset.x;
    NSInteger currentIndex = (offsetx + (width + 20) * 0.5) / (width + 20);
    if (currentIndex > self.modelArray.count - 1) {
        currentIndex = self.modelArray.count - 1;
    }
    if (currentIndex < 0) {
        currentIndex = 0;
    }
    if (self.modelArray.count > 0) {
        GMPhotoModel *model = self.modelArray[currentIndex];
        if (model.subType == GMPhotoModelMediaSubTypeVideo) {

        }else {
            if (!self.manager.configuration.selectTogether) {
                // 照片,视频不能同时选择时
                if (self.manager.selectedVideoArray.count > 0) {

                }else {
                    // 没有选择视频时
                    if ([self.manager beforeSelectPhotoCountIsMaximum] && !model.selected) {
                        // 当选择照片数达到最大数且当前照片没选中时就不能编辑

                    }else {

                    }
                }
            }else {
                // 能同时选择时
                if ([self.manager beforeSelectPhotoCountIsMaximum] && !model.selected) {

                }else {

                }
            }
        }

        self.selectBtn.selected = model.selected;
        if (self.outside) {
//            if ([self.modelArray containsObject:model]) {
//            }else {
//            }
        }else {
#pragma mark - < 单选视频时隐藏选择按钮 >
            if (model.needHideSelectBtn) {
                self.selectBtn.hidden = YES;
                self.selectBtn.userInteractionEnabled = NO;
            }else {
                self.selectBtn.hidden = NO;
                self.selectBtn.userInteractionEnabled = YES;
            }
            if ([[self.manager selectedArray] containsObject:model]) {
            }else {
            }
        }
    }
    self.currentModelIndex = currentIndex;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.modelArray.count > 0) {
        GMDatePhotoPreviewViewCell *cell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
        GMPhotoModel *model = self.modelArray[self.currentModelIndex];
        self.currentModel = model;
        [cell requestHDImage];
    }
}

#pragma mark - < GMDatePhotoEditViewControllerDelegate >
- (void)datePhotoEditViewControllerDidClipClick:(GMDatePhotoEditViewController *)datePhotoEditViewController beforeModel:(GMPhotoModel *)beforeModel afterModel:(GMPhotoModel *)afterModel {
    if (self.outside) {
        [self.modelArray replaceObjectAtIndex:[self.modelArray indexOfObject:beforeModel] withObject:afterModel];
        if ([self.delegate respondsToSelector:@selector(datePhotoPreviewSelectLaterDidEditClick:beforeModel:afterModel:)]) {
            [self.delegate datePhotoPreviewSelectLaterDidEditClick:self beforeModel:beforeModel afterModel:afterModel];
        }
        [self dismissClick];
        return;
    }

    if (beforeModel.selected) {
        [self.manager beforeSelectedListdeletePhotoModel:beforeModel];
    }
    [self.manager beforeSelectedListAddEditPhotoModel:afterModel];

    if ([self.delegate respondsToSelector:@selector(datePhotoPreviewDidEditClick:)]) {
        [self.delegate datePhotoPreviewDidEditClick:self];
    }
}
- (void)dismissClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)deleteClick {
    if (!self.modelArray.count) {
        return;
    }
    NSString *message;
    if (self.currentModel.subType == GMPhotoModelMediaSubTypePhoto) {
        message = @"确定删除这张照片吗?";
    }else {
        message = @"确定删除这个视频吗?";
    }
}
#pragma mark - < 懒加载 >
- (UIView *)dismissTempTopView {
    if (!_dismissTempTopView) {
        _dismissTempTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.gm_w, OCNavigationBar.barHeight)];
        _dismissTempTopView.backgroundColor = [UIColor blackColor];
    }
    return _dismissTempTopView;
}

- (UIView *)customTitleView {
    if (!_customTitleView) {
        _customTitleView = [[UIView alloc] init];
        _customTitleView.backgroundColor = RGBCOLOR_HEX(0x282828);
        [_customTitleView addSubview:self.titleLb];
        [_customTitleView addSubview:self.subTitleLb];
    }
    return _customTitleView;
}
- (UILabel *)titleLb {
    if (!_titleLb) {
        _titleLb = [[UILabel alloc] init];
        _titleLb.textAlignment = NSTextAlignmentCenter;
  
        _titleLb.font = [UIFont gmFont:14];
        _titleLb.textColor = [UIColor blackColor];
    }
    return _titleLb;
}
- (UILabel *)subTitleLb {
    if (!_subTitleLb) {
        _subTitleLb = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.titleLb.frame) + 4, 150, 12)];
        _subTitleLb.textAlignment = NSTextAlignmentCenter;
        _subTitleLb.font = [UIFont gmFont:11];
        _subTitleLb.textColor = [UIColor blackColor];
    }
    return _subTitleLb;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(-10, kTopMargin,self.view.gm_w + 20, self.view.gm_h - kTopMargin - kBottomMargin) collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[GMDatePhotoPreviewViewCell class] forCellWithReuseIdentifier:@"DatePreviewCellId"];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _collectionView;

    
}
- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _flowLayout.minimumInteritemSpacing = 0;
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        if (self.outside) {
            _flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        }else {
            if (@available(iOS 11.0, *)) {
                 _flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
            }
        }
    }
    return _flowLayout;
}

- (NSMutableArray *)modelArray {
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)dealloc {
    GMDatePhotoPreviewViewCell *cell = (GMDatePhotoPreviewViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:self.currentModelIndex inSection:0]];
    [cell cancelRequest];
    if ([UIApplication sharedApplication].statusBarHidden) {
//        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    }
}
@end

@interface GMDatePhotoPreviewViewCell ()<UIScrollViewDelegate,PHLivePhotoViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;
@property (strong, nonatomic) UIImageView *imageView;
@property (assign, nonatomic) CGPoint imageCenter;
@property (strong, nonatomic) UIImage *gifImage;
@property (strong, nonatomic) UIImage *gifFirstFrame;
@property (assign, nonatomic) PHImageRequestID requestID;
@property (strong, nonatomic) PHLivePhotoView *livePhotoView;
@property (assign, nonatomic) BOOL livePhotoAnimating;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) UIActivityIndicatorView *loadingView;
@end

@implementation GMDatePhotoPreviewViewCell
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.requestID = -1;
        [self setup];
    }
    return self;
}
- (void)setup {
    [self.contentView addSubview:self.scrollView];
    [self.scrollView addSubview:self.imageView];
    [self.contentView.layer addSublayer:self.playerLayer];
    [self.contentView addSubview:self.videoPlayBtn];
    [self.contentView addSubview:self.loadingView];
}
- (void)resetScale {
    [self.scrollView setZoomScale:1.0 animated:NO];
}
- (void)againAddImageView {
    [self refreshImageSize];
    [self.scrollView addSubview:self.imageView];
    if (self.model.subType == GMPhotoModelMediaSubTypeVideo) {
        self.videoPlayBtn.hidden = NO;
        [self.contentView.layer addSublayer:self.playerLayer];
        [self.contentView addSubview:self.videoPlayBtn];
        self.videoPlayBtn.alpha = 0;
        [UIView animateWithDuration:0.2 animations:^{
            self.videoPlayBtn.alpha = 1;
        }];
    }
}
- (void)refreshImageSize {
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    CGFloat imgWidth = self.model.imageSize.width;
    CGFloat imgHeight = self.model.imageSize.height;
    CGFloat w;
    CGFloat h;
    
    imgHeight = width / imgWidth * imgHeight;
    if (imgHeight > height) {
        w = height / self.model.imageSize.height * imgWidth;
        h = height;
        self.scrollView.maximumZoomScale = width / w + 0.5;
    }else {
        w = width;
        h = imgHeight;
        self.scrollView.maximumZoomScale = 2.5;
    }
    self.imageView.frame = CGRectMake(0, 0, w, h);
    self.imageView.center = CGPointMake(width / 2, height / 2);
    self.playerLayer.frame = self.imageView.frame;
    self.videoPlayBtn.frame = self.playerLayer.frame;
}
- (void)setModel:(GMPhotoModel *)model {
    _model = model;
    [self cancelRequest];
    self.playerLayer.player = nil;
    self.player = nil;
    [self.loadingView stopAnimating];
    
    [self resetScale];
    
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    CGFloat imgWidth = self.model.imageSize.width;
    CGFloat imgHeight = self.model.imageSize.height;
    CGFloat w;
    CGFloat h;
    
    imgHeight = width / imgWidth * imgHeight;
    if (imgHeight > height) {
        w = height / self.model.imageSize.height * imgWidth;
        h = height;
        self.scrollView.maximumZoomScale = width / w + 0.5;
    }else {
        w = width;
        h = imgHeight;
        self.scrollView.maximumZoomScale = 2.5;
    }
    self.imageView.frame = CGRectMake(0, 0, w, h);
    self.imageView.center = CGPointMake(width / 2, height / 2);
    self.playerLayer.frame = self.imageView.frame;
    self.videoPlayBtn.frame = self.playerLayer.frame;
    
    self.imageView.hidden = NO;
    __weak typeof(self) weakSelf = self;
    if (model.type == GMPhotoModelMediaTypeCameraPhoto || model.type == GMPhotoModelMediaTypeCameraVideo) {
        if (model.networkPhotoUrl) {

        }else {
            self.imageView.image = model.thumbPhoto;
            model.tempImage = nil;
        }
    }else {
        if (model.type == GMPhotoModelMediaTypeLivePhoto) {
            if (model.tempImage) {
                self.imageView.image = model.tempImage;
                model.tempImage = nil;
            }else {
                self.requestID = [GMPhotoTools getPhotoForPHAsset:model.asset size:CGSizeMake(self.gm_w * 0.5, self.gm_h * 0.5) completion:^(UIImage *image, NSDictionary *info) {
                    weakSelf.imageView.image = image;
                }];
            }
        }else {
            if (model.previewPhoto) {
                self.imageView.image = model.previewPhoto;
                model.tempImage = nil;
            }else {
                if (model.tempImage) {
                    self.imageView.image = model.tempImage;
                    model.tempImage = nil;
                }else {
                    PHImageRequestID requestID;
                    if (imgHeight > imgWidth / 9 * 17) {
                        requestID = [GMPhotoTools getPhotoForPHAsset:model.asset size:CGSizeMake(self.gm_w * 0.6, self.gm_h * 0.6) completion:^(UIImage *image, NSDictionary *info) {
                            weakSelf.imageView.image = image;
                        }];
                    }else {
                        requestID = [GMPhotoTools getPhotoForPHAsset:model.asset size:CGSizeMake(model.endImageSize.width * 0.8, model.endImageSize.height * 0.8) completion:^(UIImage *image, NSDictionary *info) {
                            weakSelf.imageView.image = image;
                        }];
                    }
                    self.requestID = requestID;
                }
            }
        }
    }
    if (model.subType == GMPhotoModelMediaSubTypeVideo) {
        self.playerLayer.hidden = NO;
        self.videoPlayBtn.hidden = YES;
    }else {
        self.playerLayer.hidden = YES;
        self.videoPlayBtn.hidden = YES;
    }
}
- (void)requestHDImage {
    if (self.requestID) {
        [[PHImageManager defaultManager] cancelImageRequest:self.requestID];
        self.requestID = -1;
    }
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;
    CGFloat imgWidth = self.model.imageSize.width;
    CGFloat imgHeight = self.model.imageSize.height;
    CGSize size;
    __weak typeof(self) weakSelf = self;
    if (imgHeight > imgWidth / 9 * 17) {
        size = CGSizeMake(width * 1.5, height * 1.5);
    }else {
        size = CGSizeMake(self.model.endImageSize.width * 2.5, self.model.endImageSize.height * 2.5);
    }
    if (self.model.type == GMPhotoModelMediaTypeLivePhoto) {
        if (_livePhotoView.livePhoto) {
            [self.livePhotoView stopPlayback];
            [self.livePhotoView startPlaybackWithStyle:PHLivePhotoViewPlaybackStyleFull];
            return;
        }

        self.requestID = [GMPhotoTools getLivePhotoForAsset:self.model.asset size:self.model.endImageSize startRequestICloud:^(PHImageRequestID iCloudRequestId) {

            weakSelf.requestID = iCloudRequestId;
        } progressHandler:^(double progress) {

        } completion:^(PHLivePhoto *livePhoto) {
            [weakSelf downloadICloudAssetComplete];
            weakSelf.livePhotoView.frame = weakSelf.imageView.frame;
            [weakSelf.scrollView addSubview:weakSelf.livePhotoView];
            weakSelf.imageView.hidden = YES;
            weakSelf.livePhotoView.livePhoto = livePhoto;
            [weakSelf.livePhotoView startPlaybackWithStyle:PHLivePhotoViewPlaybackStyleFull];
        } failed:^{

        }];
    }else if (self.model.type == GMPhotoModelMediaTypePhoto) {
        self.requestID = [GMPhotoTools getHighQualityFormatPhoto:self.model.asset size:size startRequestIcloud:^(PHImageRequestID cloudRequestId) {

            weakSelf.requestID = cloudRequestId;
        } progressHandler:^(double progress) {

        } completion:^(UIImage *image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf downloadICloudAssetComplete];
                weakSelf.imageView.image = image;
            });
        } failed:^(NSDictionary *info) {
            dispatch_async(dispatch_get_main_queue(), ^{

            });
        }];
    }else if (self.model.type == GMPhotoModelMediaTypePhotoGif) {
        if (self.gifImage) {
            self.imageView.image = self.gifImage;
        }else {
            if (self.model.asset) {
                self.requestID = [GMPhotoTools getImageData:self.model.asset startRequestIcloud:^(PHImageRequestID cloudRequestId) {
                    dispatch_async(dispatch_get_main_queue(), ^{

                        weakSelf.requestID = cloudRequestId;
                    });
                } progressHandler:^(double progress) {
                    dispatch_async(dispatch_get_main_queue(), ^{

                    });
                } completion:^(NSData *imageData, UIImageOrientation orientation) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf downloadICloudAssetComplete];
                        UIImage *gifImage = [UIImage animatedGIFWithData:imageData];
                        if (gifImage.images.count == 0) {
                            weakSelf.gifFirstFrame = gifImage;
                        }else {
                            weakSelf.gifFirstFrame = gifImage.images.firstObject;
                        }
                        weakSelf.model.tempImage = nil;
                        weakSelf.imageView.image = gifImage;
                        weakSelf.gifImage = gifImage;
                    });
                } failed:^(NSDictionary *info) {
                    dispatch_async(dispatch_get_main_queue(), ^{

                    });
                }];
            }else {
                UIImage *gifImage = [UIImage animatedGIFWithData:self.model.gifImageData];
                if (gifImage.images.count == 0) {
                    self.gifFirstFrame = gifImage;
                }else {
                    self.gifFirstFrame = gifImage.images.firstObject;
                }
                self.model.tempImage = nil;
                self.imageView.image = gifImage;
                self.gifImage = gifImage;
            }
        }
    }
    if (self.player != nil) return;
    if (self.model.type == GMPhotoModelMediaTypeVideo) {
        if (self.model.avAsset) {
            [self.loadingView stopAnimating];
            self.videoPlayBtn.hidden = NO;
            self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:self.model.avAsset]];
            self.playerLayer.player = weakSelf.player;
            [[NSNotificationCenter defaultCenter] addObserver:weakSelf selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:weakSelf.player.currentItem];
        }else {
            if (self.model.asset) {
                self.requestID = [GMPhotoTools getAVAssetWithPHAsset:self.model.asset startRequestIcloud:^(PHImageRequestID cloudRequestId) {
                    [weakSelf.loadingView startAnimating];
                    weakSelf.videoPlayBtn.hidden = YES;
                    weakSelf.requestID = cloudRequestId;
                } progressHandler:^(double progress) {
;
                } completion:^(AVAsset *asset) {
                    [weakSelf downloadICloudAssetComplete];
                    weakSelf.model.avAsset = asset;
                    [weakSelf.loadingView stopAnimating];
                    weakSelf.videoPlayBtn.hidden = NO;
                    weakSelf.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:asset]];
                    weakSelf.playerLayer.player = weakSelf.player;
                    [[NSNotificationCenter defaultCenter] addObserver:weakSelf selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:weakSelf.player.currentItem];
                } failed:^(NSDictionary *info) {
                    [weakSelf.loadingView stopAnimating];
                    weakSelf.videoPlayBtn.hidden = NO;
                }];
            }else {
                [self.loadingView stopAnimating];
                self.videoPlayBtn.hidden = NO;
                self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:[AVAsset assetWithURL:self.model.fileURL]]];
                self.playerLayer.player = weakSelf.player;
                [[NSNotificationCenter defaultCenter] addObserver:weakSelf selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:weakSelf.player.currentItem];
            }
        }
    }else if (self.model.type == GMPhotoModelMediaTypeCameraVideo ) {
        self.videoPlayBtn.hidden = NO;
        self.player = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithURL:self.model.videoURL]];
        self.playerLayer.player = self.player;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayerAndShowNaviBar) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    }
}
- (void)downloadICloudAssetComplete {

}
- (void)pausePlayerAndShowNaviBar {

    [self.player.currentItem seekToTime:CMTimeMake(0, 1)];
    [self.player play];
}
- (void)cancelRequest {
    if (self.requestID) {
        [[PHImageManager defaultManager] cancelImageRequest:self.requestID];
        self.requestID = -1;
    }
    self.videoPlayBtn.hidden = YES;
    if (self.model.type == GMPhotoModelMediaTypeLivePhoto) {
        if (_livePhotoView.livePhoto) {
            self.livePhotoView.livePhoto = nil;
            [self.livePhotoView removeFromSuperview];
            self.imageView.hidden = NO;
            [self stopLivePhoto];
        }
    }else if (self.model.type == GMPhotoModelMediaTypePhoto) {
        
    }else if (self.model.type == GMPhotoModelMediaTypePhotoGif) {
        if (!self.stopCancel) {
            self.imageView.image = nil;
            self.gifImage = nil;
            self.imageView.image = self.gifFirstFrame;
        }else {
            self.stopCancel = NO;
        }
    }
    if (self.model.subType == GMPhotoModelMediaSubTypeVideo) {
        if (self.player != nil && !self.stopCancel) {
            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
            [self.player pause];
            self.videoPlayBtn.selected = NO;
            [self.player seekToTime:kCMTimeZero];
            self.playerLayer.player = nil;
            self.player = nil;
        }
        self.stopCancel = NO;
    }
}
- (void)singleTap:(UITapGestureRecognizer *)tap {
    if (self.cellTapClick) {
        self.cellTapClick();
    }
}
- (void)doubleTap:(UITapGestureRecognizer *)tap {
    if (_scrollView.zoomScale > 1.0) {
        [_scrollView setZoomScale:1.0 animated:YES];
    } else {
        CGFloat width = self.frame.size.width;
        CGFloat height = self.frame.size.height;
        CGPoint touchPoint;
        if (self.model.type == GMPhotoModelMediaTypeLivePhoto) {
            touchPoint = [tap locationInView:self.livePhotoView];
        }else {
            touchPoint = [tap locationInView:self.imageView];
        }
        CGFloat newZoomScale = self.scrollView.maximumZoomScale;
        CGFloat xsize = width / newZoomScale;
        CGFloat ysize = height / newZoomScale;
        [self.scrollView zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES];
    }
}
#pragma mark - < PHLivePhotoViewDelegate >
- (void)livePhotoView:(PHLivePhotoView *)livePhotoView willBeginPlaybackWithStyle:(PHLivePhotoViewPlaybackStyle)playbackStyle {
    self.livePhotoAnimating = YES;
}
- (void)livePhotoView:(PHLivePhotoView *)livePhotoView didEndPlaybackWithStyle:(PHLivePhotoViewPlaybackStyle)playbackStyle {
    [self stopLivePhoto];
}
- (void)stopLivePhoto {
    self.livePhotoAnimating = NO;
    [self.livePhotoView stopPlayback];
}
#pragma mark - < UIScrollViewDelegate >
- (nullable UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if (self.model.subType == GMPhotoModelMediaSubTypeVideo) {
        return nil;
    }
    if (self.model.type == GMPhotoModelMediaTypeLivePhoto) {
        return self.livePhotoView;
    }else {
        return self.imageView;
    }
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGFloat offsetX = (scrollView.frame.size.width > scrollView.contentSize.width) ? (scrollView.frame.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.frame.size.height > scrollView.contentSize.height) ? (scrollView.frame.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    if (self.model.type == GMPhotoModelMediaTypeLivePhoto) {
        self.livePhotoView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
    }else {
        self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
    }
}
- (void)didPlayBtnClick:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        [self.player play];
    }else {
        [self.player pause];
    }
    if (self.cellDidPlayVideoBtn) {
        self.cellDidPlayVideoBtn(button.selected);
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    self.scrollView.frame = self.bounds;
    self.scrollView.contentSize = CGSizeMake(self.gm_w, self.gm_h);

}
#pragma mark - < 懒加载 >
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.bouncesZoom = YES;
        _scrollView.minimumZoomScale = 1;
        _scrollView.multipleTouchEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.scrollsToTop = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _scrollView.delaysContentTouches = NO;
        _scrollView.canCancelContentTouches = YES;
        _scrollView.alwaysBounceVertical = NO;
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        [_scrollView addGestureRecognizer:tap1];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
        tap2.numberOfTapsRequired = 2;
        [tap1 requireGestureRecognizerToFail:tap2];
        [_scrollView addGestureRecognizer:tap2];
    }
    return _scrollView;
}
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
    }
    return _imageView;
}
- (PHLivePhotoView *)livePhotoView  API_AVAILABLE(ios(9.1)){
    if (!_livePhotoView) {
        if (@available(iOS 9.1, *)) {
            _livePhotoView = [[PHLivePhotoView alloc] init];
        } else {
            // Fallback on earlier versions
        }
        _livePhotoView.clipsToBounds = YES;
        _livePhotoView.contentMode = UIViewContentModeScaleAspectFill;
        _livePhotoView.delegate = self;
    }
    return _livePhotoView;
}
- (UIButton *)videoPlayBtn {
    if (!_videoPlayBtn) {
        _videoPlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_videoPlayBtn setImage:[UIImage imageNamed:@"multimedia_videocard_play"] forState:UIControlStateNormal];
        [_videoPlayBtn setImage:[[UIImage alloc] init] forState:UIControlStateSelected];
        [_videoPlayBtn addTarget:self action:@selector(didPlayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _videoPlayBtn.hidden = YES;
    }
    return _videoPlayBtn;
}
//- (GMCircleProgressView *)progressView {
//    if (!_progressView) {
//        _progressView = [[GMCircleProgressView alloc] init];
//        _progressView.hidden = YES;
//    }
//    return _progressView;
//}
- (UIActivityIndicatorView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_loadingView stopAnimating];
    }
    return _loadingView;
}
- (AVPlayerLayer *)playerLayer {
    if (!_playerLayer) {
        _playerLayer = [[AVPlayerLayer alloc] init];
        _playerLayer.hidden = YES;
        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return _playerLayer;
}
- (void)dealloc {
    [self cancelRequest];
}
@end

