//
//  ALGroupEditVerbController.m
//  GMAlpha
//
//  Created by zhb on 2018/11/13.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALGroupEditVerbController.h"
#import "UITextView+Placeholder.h"

@interface ALGroupEditVerbController ()<UITextViewDelegate>
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *numLabel;
@property (nonatomic, copy) NSString *verbText;
@property (nonatomic, assign) NSInteger groupId;
@property (nonatomic, strong) NSDictionary *attributedDict;
@property (nonatomic, strong) UIView *navItemView;
@end

@implementation ALGroupEditVerbController
@synthesize viewModel;

#pragma mark - life cycle

- (void)dealloc{
    [self removeKVO];
}

- (instancetype)initWithGroupId:(NSInteger)groupId {
    self = [super init];
    if (self) {
        self.groupId = groupId;
        self.viewModel.groupId = groupId;
    }
    return self;
}

- (void)initController{
    [super initController];
    self.viewModel = [[ALGroupEditViewModel alloc] init];
    self.verbText = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR_HEX(0xF4F3F8);
    [self addKVO];
    self.navigationBar.title = @"小组简介";
    self.navigationBar.rightTitle = @"完成";
    [self.navigationBar.rightButton setTitleColor:[UIColor colorWithHexString:@"2D9AFF"] forState:UIControlStateNormal];
    [self setupSubViews];
    [self showLoading:nil];
    [self.viewModel fetchRemoteData];
}

- (void)setupSubViews {
    [self.view addSubview:self.whiteView];
    [self.whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(OCNavigationBar.barHeight);
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.height.mas_equalTo(300);
    }];
    
    //self.whiteView的子视图
    [self.whiteView addSubview:self.textView];
    [self.whiteView addSubview:self.numLabel];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(14);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
    }];
    [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.textView.mas_bottom);
        make.bottom.mas_equalTo(-15);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(20);
    }];
}

#pragma mark - UITextView delegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.text.length > 200) {
        return NO;
    }else {
        return YES;
    }
}

//- (void)textViewDidChange:(UITextView *)textView {
//    NSString *inputString = (textView.text ? : @"");
//    textView.attributedText = [[NSAttributedString alloc] initWithString:inputString attributes:self.attributedDict];
//}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.verbText = (textView.text ? : @"");
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"fetchDataSuccess"] && object == self.viewModel) {
        [self hideLoading];
        self.textView.editable = YES;
        self.verbText = self.viewModel.contentObject.desc;
        if ([self.verbText isNonEmpty]) {
            self.textView.attributedText = [[NSAttributedString alloc] initWithString:self.verbText attributes:self.attributedDict];
        }
        self.numLabel.text = [NSString stringWithFormat:@"%ld/200", self.verbText.length];
    }
}

#pragma mark - 事件
- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    [self.view endEditing:YES];
    [self requestGroupUpdate];
}

#pragma mark - 网络

// 更新group
- (void)requestGroupUpdate {
    NSDictionary *params = @{
                             @"group_id": SafeNumber(@(self.groupId)),
                             @"desc": self.verbText
                             };
    __weak __typeof(self)weakSelf = self;
    [self showLoading:nil];
    [GMNetworking requestOCWithApi:API_V1_GROUP_UPDATE method:GMHTTPMethodPost parameters:params completion:^(GMResponseOC * response) {
        [weakSelf hideLoading];
        if (response.isSuccess == NO) return;
        if ([self.delegate respondsToSelector:@selector(groupEditVerbControllerWillPopping)]) {
            [self.delegate groupEditVerbControllerWillPopping];
        }
        [weakSelf popViewControllerAnimated:YES completion:nil];
    }];
}

#pragma mark - private methods
- (void)addKVO
{
    [self.viewModel addObserver:self forKeyPath:@"fetchDataSuccess" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)removeKVO{
    // 因为fetchDataSuccess是在viewDidLoad中监听的，所以需要一个判断
    if ([self isViewLoaded]) {
        [self.viewModel removeObserver:self forKeyPath:@"fetchDataSuccess"];
    }
}

#pragma mark - getters and setters
- (UIView *)whiteView {
    if (!_whiteView) {
        _whiteView = [[UIView alloc] init];
        _whiteView.backgroundColor = UIColor.whiteColor;
    }
    return _whiteView;
}
- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.textColor = UIColor.headlineText;
        _textView.font = [UIFont gmFont:15];
        _textView.placeholder = @"编辑小组简介吧!";
        _textView.placeholderColor = UIColor.auxiliaryTextExtraLight;
        _textView.delegate = self;
        _textView.editable = NO;
        _textView.typingAttributes = self.attributedDict;
    }
    return _textView;
}

- (UILabel *)numLabel {
    if (!_numLabel) {
        _numLabel = [[UILabel alloc] init];
        _numLabel.textColor = UIColor.auxiliaryTextLight;
        _numLabel.textAlignment = NSTextAlignmentRight;
        _numLabel.font = [UIFont gmFont:13];
        _numLabel.text = @"0/200";
    }
    return _numLabel;
}

- (NSDictionary *)attributedDict {
    if (!_attributedDict) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 7;// 字体的行间距
        _attributedDict = @{
                                   NSForegroundColorAttributeName:UIColor.headlineText,
                                   NSFontAttributeName:[UIFont gmFont:15],
                                   NSParagraphStyleAttributeName:paragraphStyle
                                   };
        
    }
    return _attributedDict;
}

- (UIView *)navItemView {
    if (!_navItemView) {
        _navItemView = [[UIView alloc] init];
        _navItemView.backgroundColor = UIColor.redColor;
    }
    return _navItemView;
}


@end
