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

#import "ALCreateTopicHeaderView.h"
#import "ALCreateDiaryObject.h"
#define itemWidth (MAINSCREEN_WIDTH - 20 * 2 - 7 - ONE_PIXEL) / 4
#define margin (2 + ONE_PIXEL)

@interface ALCreateDiaryImageCollectionCell()
@property (nonatomic, strong) GMButton *deleteImageBtn;
@property (nonatomic, strong) GMImageView *photoView;
@property (nonatomic, strong) GMButton *playVideoBtn;
@end
@implementation ALCreateDiaryImageCollectionCell
- (void)setup {
    [super setup];
    _photoView = [[GMImageView alloc] init];
    _photoView.contentMode = UIViewContentModeScaleAspectFill;
    _photoView.layer.cornerRadius = 2;
    _photoView.layer.masksToBounds = YES;
    [self.contentView addSubview:_photoView];
    
    _playVideoBtn = [GMButton buttonWithType:UIButtonTypeCustom];
    [_playVideoBtn setImage:[UIImage imageNamed:@"diary_video_cover"] forState:UIControlStateNormal];
    [self.contentView addSubview:_playVideoBtn];
    
    _deleteImageBtn = [GMButton buttonWithType:UIButtonTypeCustom];
    [_deleteImageBtn setImage:[UIImage imageNamed:@"image_delete"] forState:UIControlStateNormal];
    [self.contentView addSubview:_deleteImageBtn];
    
    [_photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [_playVideoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [_deleteImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(1);
        make.right.mas_equalTo(-1);
        make.height.mas_equalTo(ONE_PIXEL + 15);
        make.width.mas_equalTo(ONE_PIXEL + 15);
    }];
}
@end


@interface ALCreateTopicHeaderView()<UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource> {
    NSInteger count; // 图片和视频的总个数
}

@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (nonatomic, strong) GMLabel *placeholderLabel;
@property (nonatomic, strong) GMLabel *bottomLabel;
@end
@implementation ALCreateTopicHeaderView

- (void)setup {
    [super setup];
    
    self.backgroundColor = UIColor.whiteColor;
 
    _titleTextView = [[UITextView alloc] init];
    _titleTextView.textContainerInset = UIEdgeInsetsMake(-2, -2, 0, -4);
    _titleTextView.delegate = self;
    _titleTextView.hasCloseButton = YES;
    [self addSubview:_titleTextView];
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 4 + ONE_PIXEL;// 字体的行间距
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont gmFont:16],
                                 NSForegroundColorAttributeName : UIColor.headlineText,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    _titleTextView.typingAttributes = attributes;
    
    _placeholderLabel = [GMLabel labelWithTextAlignment:NSTextAlignmentLeft backgroundColor:UIColor.clearColor textColor:UIColor.auxiliaryTextLight fontSize:15];
    _placeholderLabel.text = @"想把我说给你听";
    [_titleTextView addSubview:_placeholderLabel];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _picturesView = [[GMCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _picturesView.backgroundColor = UIColor.whiteColor;
    _picturesView.delegate = self;
    _picturesView.dataSource = self;
    [_picturesView registerClass:[ALCreateDiaryImageCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([ALCreateDiaryImageCollectionCell class])];
    [self addSubview:_picturesView];
    
    [_titleTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(18);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-20);
        make.height.mas_greaterThanOrEqualTo(165);
    }];
    
    [_placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(3);
        make.top.mas_equalTo(1);
    }];
    
    [_picturesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleTextView.mas_bottom);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_greaterThanOrEqualTo(itemWidth);
        make.height.mas_lessThanOrEqualTo(itemWidth * 3 + 5);
    }];
    
    
    GMView *bottomView =[[GMView alloc] init];
    bottomView.backgroundColor = UIColor.background;
    [self addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.picturesView.mas_bottom).offset(20);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
        make.bottom.mas_equalTo(0);
    }];
    
    _bottomLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextDark fontSize:14];
    _bottomLabel.font = [UIFont boldSystemFontOfSize:14];
    _bottomLabel.text = @"发送至";
    [bottomView addSubview:_bottomLabel];
    [_bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(15);
        make.top.mas_equalTo(5);
        make.bottom.mas_equalTo(-5);
    }];

}
- (void)setIsHideLabel:(BOOL)isHideLabel
{
    if (isHideLabel == YES)
    {
        _bottomLabel.hidden = YES;
    }
    else
    {
        _bottomLabel.hidden = NO;
    }
}
- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    _placeholderLabel.text = placeholder;
}

- (void)setObject:(ALCreateDiaryObject *)object {
    _object = object;
    if (_object.videoModel.fileURL) {
        count = _object.images.count + 1;
    } else {
        count = _object.images.count;
    }

//    self.titleTextView.text = object.content;
    [self.picturesView reloadData];
    
    NSInteger rowCount = 1;
    if (count < 10) {
        rowCount = ceil((count + 1) / 4.0);
    } else {
        rowCount = ceil(count / 4.0);
    }
    
    [_picturesView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleTextView.mas_bottom).offset(24);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_equalTo(rowCount * itemWidth + margin * (rowCount - 1));
    }];
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    _placeholderLabel.hidden = textView.text.length != 0;
}
- (void)textViewDidChange:(UITextView *)textView {
    // 过滤掉空格和回车
    NSString *content = [[textView.text trimInnerReturn] trimSpace];
    _object.content = content;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {

}
//获取当前时间戳
- (CGFloat)currentTime{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time = [date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    return time;
}

- (UITableView *)myTableView {
    UIView *tableView = self.superview;
    while (![tableView isKindOfClass:[UITableView class]] && tableView) {
        tableView = tableView.superview;
    }
    return (UITableView *)tableView;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return count < 10 ? count + 1 : count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ALCreateDiaryImageCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ALCreateDiaryImageCollectionCell class]) forIndexPath:indexPath];
    [cell.deleteImageBtn addTarget:self action:@selector(deleteImageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    if (indexPath.row == 0 && (_object.videoModel.fileURL)) {
        cell.playVideoBtn.hidden = NO;
    } else {
        cell.playVideoBtn.hidden = YES;
    }
    if (indexPath.row + 1 > count) {
        cell.deleteImageBtn.hidden = YES;
    } else {
        cell.deleteImageBtn.hidden = NO;
    }
    if (indexPath.row + 1 > count) { // 最后一个添加图片的按钮
        cell.photoView.image = [UIImage imageNamed:@"diary_add_pics_video"];
    } else {
        if (_object.videoModel.fileURL) { // 有视频的时候，视频在第一个显示
            if (indexPath.row == 0) {
                if ([_object.videoCover isNonEmpty]) {
                    [cell.photoView sd_setImageWithURL:[NSURL URLWithString:_object.videoCover]];
                } else {
                    cell.photoView.image = _object.videoModel.thumbPhoto;
                }
            } else {
                GMPhotoModel *imageObj = _object.images[indexPath.row - 1];
                if (!imageObj.thumbPhoto) { // 草稿箱请求下来的URL
                    [cell.photoView sd_setImageWithURL:[NSURL URLWithString:imageObj.image] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                        imageObj.thumbPhoto = image;
                        imageObj.previewPhoto = image;
                    }];
                } else { // 本地图片
                    cell.photoView.image = imageObj.thumbPhoto;
                }
            }
        } else { // 只有图片
            GMPhotoModel *imageObj = _object.images[indexPath.row];
            if (!imageObj.thumbPhoto) { // 草稿箱请求下来的URL
                [cell.photoView sd_setImageWithURL:[NSURL URLWithString:imageObj.image] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    imageObj.thumbPhoto = image;
                    imageObj.previewPhoto = image;
                }];
            } else { // 本地图片
                cell.photoView.image = imageObj.thumbPhoto;
            }
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row + 1 > count) {
        // 添加图片
        if ([self.delegate respondsToSelector:@selector(addPicturesOrVideo)]) {
            [self.delegate addPicturesOrVideo];
        }
    } else {
        // 编辑图片
        if ([self.delegate respondsToSelector:@selector(editPictureAtCollectionIndex:)]) {
            [self.delegate editPictureAtCollectionIndex:indexPath.row];
        }
    }
}

- (void)deleteImageBtnAction:(UIButton *)sender {
    ALCreateDiaryImageCollectionCell *cell = (ALCreateDiaryImageCollectionCell *)sender.superview.superview;
    NSIndexPath *indexPath = [_picturesView indexPathForCell:cell];
    
    if ([self.delegate respondsToSelector:@selector(deletePictureAtCollectionIndex:)]) {
        [self.delegate deletePictureAtCollectionIndex:indexPath.row];
    }
}

//动态设置每个Item的尺寸大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(itemWidth, itemWidth);
}

//动态设置每个分区的EdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//动态设置每行的间距大小
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return margin;
}

//动态设置每列的间距大小
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return margin;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self hideKeyboard];
}

- (void)hideKeyboard {
    [self.titleTextView resignFirstResponder];
}

@end
