//
//  NewTopicTextView.m
//  smartRhino
//
//  Created by niuzhen on 2019/12/17.
//  Copyright © 2019 tederen. All rights reserved.
//

#import "NewTopicTextView.h"

@interface NewTopicTextView ()

@end

@implementation NewTopicTextView

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setCusView];
}
- (instancetype)init
{
    if (self = [super init]) {
        [self setCusView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if( (self = [super initWithFrame:frame]) )
    {
        [self setCusView];
    }
    return self;
}
- (void)setCusView
{
    if (!self.placeholder) {
        [self setPlaceholder:@""];
    }
    
    if (!self.placeholderColor) {
        [self setPlaceholderColor:UIColorHex(0xC5C5C5)];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    
    if (_placeHolderLabel == nil )
    {
        _placeHolderLabel = [[UILabel alloc] init];
        _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _placeHolderLabel.numberOfLines = 0;
        _placeHolderLabel.font = [UIFont systemFontOfSize:16];
        _placeHolderLabel.backgroundColor = [UIColor clearColor];
        _placeHolderLabel.textColor = self.placeholderColor;
        _placeHolderLabel.alpha = 0;
        _placeHolderLabel.tag = 999;
        [self addSubview:_placeHolderLabel];
    }
    _placeHolderLabel.text = self.placeholder;
    [_placeHolderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_offset(UIEdgeInsetsMake(5, 5, 5, 5));
    }];
    [self sendSubviewToBack:_placeHolderLabel];
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    _placeHolderLabel.text = _placeholder;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textChanged:(NSNotification *)notification
{
    if([[self placeholder] length] == 0)
    {
        return;
    }
    
    [self.placeHolderLabel setText:self.placeholder];
    
    [UIView animateWithDuration:0.2 animations:^{
        if([[self text] length] == 0)
        {
            [(UILabel *)[self viewWithTag:999] setAlpha:1];
        }
        else
        {
            [(UILabel *)[self viewWithTag:999] setAlpha:0];
        }
    }];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self textChanged:nil];
}

- (void)drawRect:(CGRect)rect
{
    if( [[self placeholder] length] > 0 )
    {
    
    }
    
    if( [[self text] length] == 0 && [[self placeholder] length] > 0 )
    {
        [(UILabel *)[self viewWithTag:999] setAlpha:1];
    }
    
    [super drawRect:rect];
}
@end