//
//  SLRoleLabelViewController.m
//  SLAiELTS
//
//  Created by Gusont on 2023/2/28.
//

#import "SLRoleLabelViewController.h"
#import "SLMessageViewController.h"
#import "SLRegistViewController.h"


#import "SLPageControlSlideRound.h"
#import "SLInterestView.h"
#import "SLRoleLabelView.h"
#import "SLRoleCreatSucView.h"

#import "RoleModel.h"
#import "IQKeyboardManager.h"

@interface SLRoleLabelViewController ()

@property (nonatomic, strong) SLPageControlSlideRound *secPageControl;

@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *skipBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nextBtnConst;

@property (nonatomic, assign) NSInteger curSelIndex;

@property (nonatomic, strong) NSMutableArray *rolesTypes;

//views
@property (nonatomic, strong) NSMutableDictionary *roleLabelData;

@property (nonatomic, strong) UIView *roleView;

@property (nonatomic, strong) RoleModel *roleModel;

@end

@implementation SLRoleLabelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self addRoleViews];
    [self.secPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.backBtn.mas_bottom).offset(0 * KScaleW);
        make.height.mas_equalTo(0);
        make.left.mas_equalTo(self.backBtn);
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self loadData];
    });
    self.navigationBar.hidden = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable =NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable =YES;
}

- (void)addRoleViews {
    self.roleModel = [[RoleModel alloc] init];
    self.roleView = [[UIView alloc] initWithFrame:CGRectZero];
    self.rolesTypes = [NSMutableArray arrayWithArray:@[@(SLUserInfo),@(SLRoleInterset) ,@(SLRoleLanguage), @(SLRoleName)]];
    //添加views
    [self.rolesTypes enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj integerValue] == SLRoleInterset) {
            SLInterestView *interestView = [[SLInterestView alloc] initWithFrame:CGRectZero];
            [self.roleLabelData addEntriesFromDictionary:@{obj : interestView}];
        }else {
            SLRoleLabelView *roleLabelView = [[SLRoleLabelView alloc] initWithFrame:CGRectZero];
            [roleLabelView confignWithRoleType:[obj integerValue] :self.roleModel];
            [self.roleLabelData addEntriesFromDictionary:@{obj : roleLabelView}];
        }
    }];
    
    [self.view addSubview:self.roleView];
    [self.roleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.secPageControl.mas_bottom).offset(2);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.nextBtn.mas_top);
    }];
    
    UIView *firstView = [self.roleLabelData objectForKey:@(SLUserInfo)];
    [self.roleView addSubview:firstView];
    [firstView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.roleView);
    }];
}

- (void)loadData {
    WS(weakSelf);
    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/User/GetInterestList" parameter:@{} success:^(id responseObject) {
        NSArray *interestList = [responseObject objectForKey:@"data"];
        NSArray *interestListModel = [InterestModel mj_objectArrayWithKeyValuesArray:interestList];
        SLInterestView *interestView = (SLInterestView *)[weakSelf.roleLabelData objectForKey:@(SLRoleInterset)];
        [interestView confignIntersetBtn:interestListModel];
    } failure:^(SPRequestError *error) {

    }];
}

- (IBAction)backBtnClick:(id)sender {
//    [self.navigationController popViewControllerAnimated:YES];
    self.curSelIndex = self.curSelIndex - 2;
    [self nextBtnClick:nil];
}

- (IBAction)nextBtnClick:(id)sender {
    [self.view endEditing:YES];
    if (self.curSelIndex > -1)
    {
        id roleModelType = [self.rolesTypes objectAtIndex:self.curSelIndex];
        if ([roleModelType integerValue] == SLRoleInterset) {
            if (![self saveRoleIntersets]) {
                [ZFToast ShowWithMessage:@"请选择标签"];
                return;
            }
        }
        if ([roleModelType integerValue] == SLUserInfo) {
            if (!self.roleModel.userHead.length) {
                [ZFToast ShowWithMessage:@"请上传头像"];
                return;
            }
            if (!self.roleModel.userName.length) {
                [ZFToast ShowWithMessage:@"请输入昵称"];
                return;
            }
            if (!self.roleModel.birthday.length) {
                [ZFToast ShowWithMessage:@"请选择出生日期"];
                return;
            }
        }
        if ([roleModelType integerValue] == SLRoleName) {
            if (!self.roleModel.dataName.length) {
                [ZFToast ShowWithMessage:@"请输入AI助教名称"];
                return;
            }
        }
    }
    
    if (self.curSelIndex == self.secPageControl.count - 1) {
        self.roleModel.userId = [SLGlobalInfo SharedInstance].loginInfo.user.userId;
        self.roleModel.aiSex = self.roleModel.dataSex;
        self.roleModel.aiName = self.roleModel.dataName;
        NSDictionary *dict = [self.roleModel mj_keyValues];
        //InitializeSet
        //InsertAiData
        [[SLHttpCenter SharedInstance] postWithUrl:@"/api/User/InitializeSet" parameter:dict success:^(id responseObject) {
            SLRoleCreatSucView *roleCreatSucView = [[SLRoleCreatSucView alloc] initWithFrame:self.view.frame];
            roleCreatSucView.sucBlock = ^{
                AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                [appDelegate setTabWithRootWindow];
            };
            [roleCreatSucView alertShow];
        } failure:^(SPRequestError *error) {
            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [appDelegate setTabWithRootWindow];
        }];
        return;
    }
    NSLog(@"--==%ld",self.curSelIndex);
    [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    if (self.curSelIndex < self.secPageControl.count - 1 || self.curSelIndex < 0) {
        self.curSelIndex ++;
    }
    id curRoleModelType = [self.rolesTypes objectAtIndex:self.curSelIndex];
    [self.secPageControl slideRoundSelectIndex:self.curSelIndex];
    [self.roleView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    UIView * view = [self.roleLabelData objectForKey:curRoleModelType];
    [self.roleView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.roleView);
    }];
    if (self.curSelIndex == self.secPageControl.count - 1) {
        [self.nextBtn setTitle:@"确 定" forState:UIControlStateNormal];
        [self.view bringSubviewToFront:self.nextBtn];
    }
    [self.skipBtn setTitle:[NSString stringWithFormat:@"%ld/%ld",self.curSelIndex + 1,self.secPageControl.count] forState:UIControlStateNormal];
    self.backBtn.hidden = self.curSelIndex < 1 ;
}

- (IBAction)skipBtnClick:(id)sender {
    
}

- (BOOL)saveRoleIntersets {
    SLInterestView *interestView = [self.roleLabelData objectForKey:@(SLRoleInterset)];
    __block NSMutableString *interestStr = [NSMutableString string];
    [interestView.interestArr enumerateObjectsUsingBlock:^(InterestModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSeleted) {
            [interestStr appendString:[NSString stringWithFormat:@"%@,",obj.interestId]];
        }
    }];
    if (interestStr.length) {
        self.roleModel.interests = interestStr;
//        NSString *userId = [SLGlobalInfo SharedInstance].loginInfo.user.userId ?: @"";
//        [[SLHttpCenter SharedInstance] postWithUrl:@"/api/User/AddUserInterest" parameter:@{@"userId" : userId, @"interIds" : interestStr} success:^(id responseObject) {
//
//        } failure:^(SPRequestError *error) {
//
//        }];
    }
    return interestStr.length;
}

- (SLPageControlSlideRound *)secPageControl
{
    if (!_secPageControl) {
        _secPageControl = [[SLPageControlSlideRound alloc] initWithFrame:CGRectMake(24, self.view.bounds.size.height - 20, self.view.bounds.size.width - 48, 20)];
        [self.view addSubview:_secPageControl];
        _secPageControl.spaceWithRound =7.0f;
        _secPageControl.dotAlpha = 1.0;
        _secPageControl.clipsToBounds = YES;
        CGFloat w = CGRectGetWidth(_secPageControl.frame);
        NSInteger count = self.rolesTypes.count;
        _secPageControl.sizeOfRound =CGSizeMake(w / count - 1, 4.0f);
        _secPageControl.selctSizeOfRound =CGSizeMake(w / count - 1, 4.0f);
        _secPageControl.alignment = SlideRoundAlignmentLeft;
        _secPageControl.count = count;
        _secPageControl.hidden = NO;
        [_secPageControl slideRoundSelectIndex:0];
    }
    return _secPageControl;
}

- (NSMutableDictionary *)roleLabelData {
    if (!_roleLabelData) {
        _roleLabelData = [NSMutableDictionary dictionary];
    }
    return _roleLabelData;
}

@end
