//
//  SLCreatMomentsVc.m
//  SLAiELTS
//
//  Created by Gusont on 2023/4/6.
//

#import "SLCreatMomentsVc.h"
#import "SLAddressBookVc.h"

#import "PlaceholderTextView.h"
#import "ZLPhotoBrowerView.h"
#import "SLRemidLookView.h"

#import "SLFriendsModel.h"

@interface SLCreatMomentsVc ()

@property (weak, nonatomic) IBOutlet PlaceholderTextView *textView;
@property (weak, nonatomic) IBOutlet ZLPhotoBrowerView *photoBrowerView;
@property (weak, nonatomic) IBOutlet SLRemidLookView *remidLookView;
@property (weak, nonatomic) IBOutlet UILabel *textNumberLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *photoHeightConst;

@property (nonatomic, strong) NSMutableArray *photoBrowerModels;

@property (nonatomic, strong) NSMutableArray<SLFriendsModel *> *selFriendsArr;

@end

@implementation SLCreatMomentsVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *backImage =[UIImage imageNamed:@"icon_nav_back"];
    YMBarButtonItem *backBarButtonItem =[[YMBarButtonItem alloc]initWithImage:backImage style:YMBarButtonItemPlain target:self action:@selector(backBarButtonPressed:)];
    backBarButtonItem.imageInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    backBarButtonItem.title = @"取消";
    self.navigationBar.leftBarButtonItem = backBarButtonItem;
    
    self.textView.placeholder = @"请输入...";
    self.textView.font = [UIFont systemFontOfSize:14];
    self.textView.textColor = SL333Color;
    self.photoBrowerView.maxSelectCount = 9;
    self.photoBrowerView.lineCount = 3;
    self.photoBrowerModels = [NSMutableArray array];
    self.photoBrowerView.dataArray = self.photoBrowerModels;
    WS(weakSelf);
    self.photoBrowerView.selectedData = ^(NSMutableArray<ZLPhotoBrowerModel *> *photoBrowerModels) {
        weakSelf.photoBrowerModels = photoBrowerModels;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            float collectViewHeight = weakSelf.photoBrowerView.collectionView.collectionViewLayout.collectionViewContentSize.height;
            weakSelf.photoHeightConst.constant = collectViewHeight;
        });
    };
    switch (self.photoSelType) {
        case SLNotPhoto:
            self.photoHeightConst.constant = 0.f;
            break;
        case SLPhotoLibrary:
        case SLCancel:
        {
            __block UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT)];
            bgView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:bgView];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [bgView removeFromSuperview];
                bgView = nil;
            });
            [self.photoBrowerView actionSheetAndClickSelPhotoLibrary:self.photoSelType == SLPhotoLibrary];
        }
            break;
        default:
            break;
    }
    
    YMBarButtonItem *rightBarItem = [[YMBarButtonItem alloc] initWithTitle:@"发布  " target:self action:@selector(preserveBtnClick)];
    rightBarItem.titleInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    self.navigationBar.rightBarButtonItem = rightBarItem;
    [self.remidLookView.selBtn handleEvent:UIControlEventTouchUpInside withBlock:^{
        SLAddressBookVc *vc = [SLAddressBookVc loadViewControllewWithNib];
        vc.isSelFriend = YES;
        vc.selFriendsArr = weakSelf.selFriendsArr;
        vc.selFriendsBlock = ^(NSArray *arr) {
            weakSelf.selFriendsArr = [NSMutableArray arrayWithArray:arr];
            [weakSelf.remidLookView.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [obj removeFromSuperview];
                obj = nil;
            }];
            weakSelf.remidLookView.scrollView.contentSize = CGSizeMake(arr.count * 44, 32);
            [arr enumerateObjectsUsingBlock:^(SLFriendsModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIImageView *imageView = [[UIImageView alloc] init];
                NSString *userImg = [NSString stringWithFormat:@"%@%@",[SLHttpCenter SharedInstance].serverUrl, obj.userHead];
                [imageView sd_setImageWithURL:[NSURL URLWithString:userImg] placeholderImage:[UIImage imageNamed:@"icon_ellipse"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                }];
                imageView.contentMode = UIViewContentModeScaleAspectFill;
                imageView.layer.cornerRadius = 16;
                imageView.clipsToBounds = YES;
                imageView.frame = CGRectMake(44 * idx, 0, 32, 32);
                [weakSelf.remidLookView.scrollView addSubview:imageView];
            }];
        };
        vc.title = @"@好友";
        [weakSelf navPushViewController:vc animated:YES];
    }];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSString *toBeString = [textView.text stringByReplacingCharactersInRange:range withString:text];
//    if (toBeString.length > 500) {
//        return NO;
//    }
    self.textNumberLabel.text = [NSString stringWithFormat:@"%ld/500",toBeString.length];
    return YES;
}

- (void)preserveBtnClick {
    WS(weakSelf);
    void(^InsertFriendCircle)(NSString *imgUrls) = ^(NSString *imgUrls){
        if (!imgUrls.length && !weakSelf.textView.text.length) {
            [ZFToast ShowWithMessage:@"请输入内容或选择图片"];
            return;
        }
        __block NSString *remindAis = @"";
        [weakSelf.selFriendsArr enumerateObjectsUsingBlock:^(SLFriendsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            remindAis = [remindAis stringByAppendingFormat:@"%@,",obj.userId];
        }];
        NSDictionary *parameter = @{@"content":weakSelf.textView.text ?: @"", @"imgUrl" : imgUrls ?: @"", @"remindAis" : remindAis};
        [[SLHttpCenter SharedInstance] postWithUrl:@"/api/Friend/InsertFriendCircle" parameter:parameter success:^(id responseObject) {
            [ZFToast ShowWithMessage:@"发布成功"];
            if (weakSelf.creatMomentSuccess) {
                weakSelf.creatMomentSuccess();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } failure:^(SPRequestError *error) {
            
        }];
    };
    if (self.photoBrowerModels.count) {
        [[SLHttpCenter SharedInstance] postWithSubmitUrl:@"/api/User/UploadFiles" parameter:@{} formDataHandel:^(id<AFMultipartFormData>  _Nonnull formData) {
            [self.photoBrowerModels enumerateObjectsUsingBlock:^(ZLPhotoBrowerModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSData *imgData = [UIImage resetSizeOfImageData:[UIImage imageWithData:obj.imageData] maxSize:1024.f];
                [formData appendPartWithFileData:imgData name:@"file" fileName:obj.imageName mimeType:@"image/png"];
            }];
        } success:^(id responseObject) {
            NSString *url = [responseObject objectForKey:@"data"];
            InsertFriendCircle(url);
        } failure:^(SPRequestError *error) {
            
        }];
    }else {
        InsertFriendCircle(@"");
    }
}

- (NSMutableArray<SLFriendsModel *> *)selFriendsArr {
    if (!_selFriendsArr) {
        _selFriendsArr = [NSMutableArray array];
    }
    return _selFriendsArr;
}

@end
