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

#import "ALCreateGroupController.h"
#import "ALGroupListVController.h"
#import "GMPhotoPickController.h"
#import "ALUpLoadManager.h"

@protocol ALCreateGroupViewDelegate <NSObject>

- (void)nameTextFieldCLickMethod;

@end

@interface ALCreateGroupView: GMView
@property (nonatomic, strong) GMImageView *icon;
@property (nonatomic, strong) GMTextField *nameTextF;
@property (nonatomic, strong) GMButton *rightButton;
@property (nonatomic, strong) GMTextField *rightTextF;
@property (nonatomic, copy) NSString *rightTextFText;
@property (nonatomic, assign) BOOL isPicture;
@property (nonatomic, assign) CGFloat maxLength;
@property (nonatomic, copy) NSString *placeHolder;
/** 是否添加底部线 */
@property (nonatomic, assign) BOOL isAdd;
/** 更改小组名称的UI */
@property (nonatomic, assign) BOOL isChangeGroupName;
/** 重新设置控件的宽度 */
@property (nonatomic, assign) CGFloat nameTextFWidth;

@property (nonatomic, weak) id<ALCreateGroupViewDelegate>delegate;

@end

@interface ALCreateGroupView()  <UITextFieldDelegate>
@end
@implementation ALCreateGroupView

- (void)setup {
    [super setup];
    _maxLength = 12;
    _icon = [[GMImageView alloc] init];
    _icon.image = [UIImage imageNamed:@"create_group_name"];
    [self addSubview:_icon];
    [_icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.centerY.mas_equalTo(0);
        make.width.height.mas_equalTo(20);
    }];
    
    _nameTextF = [[GMTextField alloc] init];
    _nameTextF.delegate =self;
    _nameTextF.enabled = NO;
    _nameTextF.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameTextF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"小组名称" attributes:@{NSForegroundColorAttributeName:UIColor.auxiliaryTextDark,NSFontAttributeName:[UIFont gmFont:17]}];
    [self addSubview:_nameTextF];
    [_nameTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(110);
        make.centerY.mas_equalTo(0);
        make.left.equalTo(self.icon.mas_right).offset(8);
        make.height.mas_equalTo(30);
    }];
    
    _rightTextF = [[GMTextField alloc] init];
    _rightTextF.delegate =self;
    _rightTextF.textColor = RGBCOLOR_HEX(0x333333);
    _rightTextF.textAlignment = NSTextAlignmentRight;
    [self addSubview:_rightTextF];
    [_rightTextF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.nameTextF.mas_right).offset(4);
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(-16);
        make.height.mas_equalTo(30);
    }];
    
    _rightButton = [GMButton buttonWithType:UIButtonTypeCustom];
    [_rightButton setTitleColor:UIColor.auxiliaryTextLight forState:UIControlStateNormal];
    _rightButton.titleLabel.font = [UIFont gmFont:15];
    _rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [_rightButton setTitle:@"" forState:UIControlStateNormal];
    [self addSubview:_rightButton];
    [_rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(0);
    }];
    
}

- (void)setRightTextFText:(NSString *)rightTextFText
{
    self.rightTextF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:rightTextFText attributes:@{NSForegroundColorAttributeName:UIColor.auxiliaryTextLight,NSFontAttributeName:[UIFont gmFont:15]}];
}

- (void)setIsAdd:(BOOL)isAdd
{
    if (isAdd == YES)
    {
        
        UIView *bottomView = [[UIView alloc]init];
        bottomView.backgroundColor = UIColor.separatorLine;
        [self addSubview:bottomView];
        
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(-15);
            make.height.offset(1/[UIScreen mainScreen].scale);
        }];
        
        
    }
}

- (void)setIsChangeGroupName:(BOOL)isChangeGroupName
{
    if (isChangeGroupName == YES)
    {
        self.rightButton.hidden = YES;
    }
    else
    {
        self.rightTextF.hidden = YES;
    }
}

- (void)setNameTextFWidth:(CGFloat)nameTextFWidth
{
    [self.nameTextF mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(nameTextFWidth);
    }];
}

- (void)setPlaceHolder:(NSString *)placeHolder {
    _placeHolder = placeHolder;
    self.nameTextF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{NSForegroundColorAttributeName:UIColor.auxiliaryTextLight,NSFontAttributeName:[UIFont gmFont:17]}];
}
- (void)setIsPicture:(BOOL)isPicture {
    _isPicture = isPicture;
    if (_isPicture) {
        [_rightButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.height.width.mas_equalTo(45);
            make.centerY.mas_equalTo(0);
        }];
        _rightButton.layer.masksToBounds = YES;
        _rightButton.layer.cornerRadius = 22.5;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.rightTextF) {
        if ([self.delegate respondsToSelector:@selector(nameTextFieldCLickMethod)]) {
            [self.delegate nameTextFieldCLickMethod];
        }
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        //so easy
        else if (self.rightTextF.text.length >= _maxLength) {
            self.rightTextF.text = [textField.text substringToIndex:_maxLength];
            [AppDelegate.visibleController toast:@"不可输入更多内容~"];
            return NO;
        }
    }
    return YES;
}

- (void)textFildChangeText:(GMTextField *)textField
{
    if (textField.text.length>_maxLength)
    {
        textField.text = [textField.text substringWithRange:NSMakeRange(0, _maxLength)];
        
        [AppDelegate.visibleController toast:@"不可输入更多内容~"];
    }
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    if(_maxLength <= 0){
//        return YES;
//    }
//
//    UITextRange *selectedRange = [textField markedTextRange];//高亮选择的字
//    UITextPosition *startPos = [textField positionFromPosition:selectedRange.start offset:0];
//    UITextPosition *endPos = [textField positionFromPosition:selectedRange.end offset:0];
//    NSInteger markLength = [textField offsetFromPosition:startPos toPosition:endPos];
//
//    NSInteger confirmlength =  textField.text.length - markLength - range.length;//已经确认输入的字符长度
//    if(confirmlength >= _maxLength ){
//        [AppDelegate.visibleController toast:@"不可输入更多内容~"];
//        return NO;
//    }
//
//    NSInteger allowMaxMarkLength = [self allowMaxMarkLength:_maxLength - confirmlength];
//    if(markLength > allowMaxMarkLength ){// && string.length > 0){
//        return NO;
//    }
//    return YES;
//}

/**
 主要是用于中文输入的场景
 剩余的允许输入的字数较少时，限制拼音字符的输入，提升体验
 */
- (NSInteger)allowMaxMarkLength:(NSInteger)remainLength
{
    NSInteger length = 0;
    if(remainLength > 2){
        length = NSIntegerMax;
    }else if(remainLength > 0){
        length = remainLength * 6;  //一个中文对应的拼音一般不超过6个
    }
    
    return length;
}
@end

@interface ALCreateGroupController ()<UITextViewDelegate,GMPhotoPickDismissDelegate,ALCreateGroupViewDelegate>
@property (nonatomic, strong) GMScrollView *scrContainer;
@property (nonatomic, strong) GMImageView *headerImage;
@property (nonatomic, strong) GMImageView *groupBg;

@property (nonatomic, strong) UITextView *groupDescField;
@property (nonatomic, strong) GMLabel *placeholderLabel;

@property (nonatomic, strong) ALCreateGroupView *pictureView;
@property (nonatomic, strong) ALCreateGroupView *groupNameView;
@property (nonatomic, strong) ALCreateGroupView *groupDescView;
/** 需要上传的icon */
@property (nonatomic, strong) UIImage *iconImage;

@property (nonatomic, copy) NSString *iconKey;

@end

@implementation ALCreateGroupController
- (void)initController {    
    [super initController];
    self.pageName = @"group_create_step_three";

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.title = @"创建小组";
    self.navigationBar.rightTitle = @"提交";
    [self.navigationBar.rightButton setTitleColor:RGBCOLOR_HEX(0x0093ff) forState:(UIControlStateNormal)];
    self.navigationBar.backgroundColor = UIColor.clearColor;
    self.navigationBar.isShowShadow = NO;
    
    _scrContainer = [[GMScrollView alloc] init];
    [self.view addSubview:_scrContainer];
    [_scrContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.right.left.bottom.mas_equalTo(0);
    }];
    
    _headerImage = [[GMImageView alloc] init];
    _headerImage.image = [UIImage imageNamed:@"group_header_iamge"];
    [_scrContainer containerAppendSubview:_headerImage];
    [_headerImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(36.5);
        make.right.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(291, 128));
    }];
    
    _groupBg = [[GMImageView alloc] init];
    _groupBg.userInteractionEnabled = YES;
    _groupBg.image = [UIImage imageNamed:@"group_bg"];
    [_scrContainer containerAppendSubview:_groupBg];
    [_groupBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerImage.mas_bottom);
        make.left.mas_equalTo(9);
        make.right.mas_equalTo(-9);
        make.width.mas_equalTo(MAINSCREEN_WIDTH -18);
        make.height.mas_equalTo(354);
    }];
    
    _pictureView = [[ALCreateGroupView alloc] init];
    _pictureView.isAdd = YES;
    _pictureView.isChangeGroupName = NO;
    _pictureView.placeHolder = @"小组头像";
    _pictureView.icon.image = [UIImage imageNamed:@"group_pic"];
    [_pictureView.rightButton setBackgroundImage:[UIImage imageNamed:@"group_creat_icon"] forState:UIControlStateNormal];
    [_pictureView.rightButton addTarget:self action:@selector(editPortrait) forControlEvents:(UIControlEventTouchUpInside)];
    _pictureView.isPicture = YES;
    [_groupBg addSubview:_pictureView];
    [_pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(70);
    }];
    
    _groupNameView = [[ALCreateGroupView alloc] init];
    _groupNameView.isAdd = YES;
    _groupNameView.placeHolder = @"小组名称";
    _groupNameView.isChangeGroupName = YES;
    _groupNameView.icon.image = [UIImage imageNamed:@"create_group_name"];
    _groupNameView.maxLength = 12;
    _groupNameView.delegate = self;
//    [_groupNameView.rightButton setTitle:@"0/12" forState:UIControlStateNormal];
    [_groupBg addSubview:_groupNameView];
    [_groupNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pictureView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(70);
    }];
    
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc]initWithString:@"小组简介（选填）"];
    [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(4, 4)];
    [attribute addAttribute:NSForegroundColorAttributeName value:UIColor.auxiliaryTextLight range:NSMakeRange(0, 8)];
    
    _groupDescView = [[ALCreateGroupView alloc] init];
    _groupDescView.nameTextF.attributedPlaceholder = attribute;
    _groupDescView.nameTextFWidth = 145;//UIColor.auxiliaryTextLight
    _groupDescView.rightTextF.textColor = UIColor.auxiliaryTextLight;
    _groupDescView.rightTextF.text = @"0/90";
    _groupDescView.rightTextF.font = [UIFont gmFont:15];
    _groupDescView.rightTextF.userInteractionEnabled = NO;
    _groupDescView.isChangeGroupName = YES;
    _groupDescView.icon.image = [UIImage imageNamed:@"organization_icon"];
    _groupDescView.maxLength = 90;
    [_groupBg addSubview:_groupDescView];
    [_groupDescView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.groupNameView.mas_bottom);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    _groupDescField = [[UITextView alloc] init];
    _groupDescField.tintColor = RGBCOLOR_HEX(0x0093ff);
    _groupDescField.textColor = RGBCOLOR_HEX(0x333333);
    _groupDescField.font = [UIFont gmFont:15];
    _groupDescField.delegate = self;
    [_groupBg addSubview:_groupDescField];
    [_groupDescField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.groupDescView.mas_bottom).offset(4);
        make.left.mas_equalTo(40);
        make.right.mas_equalTo(-8);
        make.bottom.mas_equalTo(-5);
    }];
    
    _placeholderLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextLight fontSize:15];
    _placeholderLabel.text = @"点击输入";
    [_groupDescField addSubview:_placeholderLabel];
    [_placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(5);
        make.top.mas_equalTo(7);
    }];
    
    GMLabel *promoteLabel = [GMLabel labelWithTextColor:UIColor.auxiliaryTextLight fontSize:13];
    promoteLabel.textColor = UIColor.auxiliaryTextExtraLight;
    promoteLabel.numberOfLines = 0;
    promoteLabel.text = @"tips：\n1.如果是明星小组，把明星姓名写入小组，更容易被搜索到 \n2.随着小组成员和讨论热度的增加，你的小组会在推荐、搜索中排到更前面的位置，努力吧！";
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 12 - (promoteLabel.font.lineHeight - promoteLabel.font.pointSize);
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    promoteLabel.attributedText = [[NSAttributedString alloc] initWithString:promoteLabel.text attributes:attributes];
    [_scrContainer containerAppendSubview:promoteLabel];
    [promoteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.groupBg.mas_bottom).offset(20);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-20);
    }];
    
}
//小组名称的点击代理 -- 统计
- (void)nameTextFieldCLickMethod
{
    [Phobos track:@"group_create_step_three_click_write_group_name"];
}

- (void)textViewDidChange:(UITextView *)textView
{
    [Phobos track:@"group_create_step_three_click_write_group_intro"];
    if (textView.text.length>90) {
        textView.text = [textView.text substringToIndex:90];
        [self toast:@"最多输入90个字"];
    }
    _groupDescView.rightTextF.text = [NSString stringWithFormat:@"%zd/90",textView.text.length];

}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    _placeholderLabel.hidden = textView.text.length != 0;
}

- (void)rightButtonClicked:(OCNavigationBarButton *)button {
    [Phobos track:@"group_create_step_three_click_done"];
    [self postGroup:button];
}
- (void)postGroup:(OCNavigationBarButton *)button {
    
    if (self.iconImage == nil)
    {
        self.iconImage = [UIImage imageNamed:@"group_default_icon"];
    }
    
    button.userInteractionEnabled = NO;
    __weak typeof(self)weakSelf = self;
    [self showLoading:nil];

    [[ALUpLoadManager shareInstance] setImage:self.iconImage  getTokenType:GetTokenTypeImage fileSuffix:nil block:^(NSString *url) {
        weakSelf.iconKey = url;
        [weakSelf putInfoMethod:button];
    } failBlock:^(NSString *message) {
        [weakSelf putInfoMethod:button];
    }];
}
- (void)putInfoMethod:(OCNavigationBarButton *)button
{
    if (self.groupNameView.rightTextF.text.length == 0) {
        [self toast:@"请您完善小组信息之后再发布"];
        button.userInteractionEnabled = YES;
        return;
    }

    NSDictionary *param = @{@"group_name": self.groupNameView.rightTextF.text,
                            @"group_desc": SafeString(self.groupDescField.text),
                            @"group_icon": SafeString(self.iconKey)
                            };
    __weak __typeof(self)weakSelf = self;
    [GMNetworking requestOCWithApi:API_GROUP_CREATE method:GMHTTPMethodPost parameters:param completion:^(GMResponseOC * responseObject) {
        [weakSelf hideLoading];
        button.userInteractionEnabled = YES;
        if (responseObject.isSuccess) {
            NSDictionary *data = responseObject.data;
            if (data) {
                NSInteger groudId = [data[@"group_id"] integerValue];
                
                ALGroupListVController *listController = [[ALGroupListVController alloc] initWithGroupId:groudId];
                listController.isCreatContro = YES;
                [weakSelf pushViewController:listController];
            }
            [weakSelf toast:@"创建成功"];
        } else {
            [weakSelf toast:responseObject.message];
        }
        
    }];
}
#pragma mark - GMPhotoPickDismissDelegate
- (void)dismissPhotoPick:(NSArray *)images
{
    if (images.count == 1)
    {
        self.iconImage = images.firstObject;
        [self.pictureView.rightButton setImage:images.firstObject forState:(UIControlStateNormal)];
    }
}
#pragma mark--click Method

#pragma mark--上传头像
- (void)editPortrait
{
    [Phobos track:@"group_create_step_three_click_add_picture"];
    GMPhotoPickController *controller = [[GMPhotoPickController alloc] initWithMaxPhotoCount:1];
    controller.dismissDelegate = self;
    controller.root.singleSelection = YES;
    [self presentViewController:controller animated:YES completion:NULL];
}

@end


