CNLiveCompleteInfoView.m 14.3 KB
//
//  CNLiveCompleteInfoView.m
//  CNLiveLoginModule
//
//  Created by 153993236@qq.com on 11/12/2019.
//  Copyright (c) 2019 153993236@qq.com. All rights reserved.
//

#import "CNLiveCompleteInfoView.h"
#import "CNLiveLoginTextField.h"
#import "YYKit.h"
#import "QMUIKit.h"

#import <CNLiveUserSystemSDK/CNLiveUserSystemCenter.h>
#import <CNLiveUserSystemSDK/CNLiveUserSystemTypeDef.h>
#import "CNUserInfoManager.h"
#import "CNLiveEnvironment.h"
#import "CNLiveManager.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "XFCameraController.h"
#import "TZImagePickerController.h"

#import "TIMAdapter.h"
#import "CommonLibrary.h"
#import "NBSAppAgent.h"
#import "CNLiveBusinessTools.h"
#import "CNLiveCategory.h"

#import "CNLiveLoginRequestModel.h"

@interface CNLiveCompleteInfoView()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,QMUIAlertControllerDelegate>{
    UIImage *_image;
}

@property (nonatomic, weak) UIButton *head;
@property (nonatomic, weak) CNLiveLoginTextField *nickname;
@property (nonatomic, weak) UIButton *next;
@property (nonatomic, strong) IMALoginParam *loginParam;

@end
@implementation CNLiveCompleteInfoView
static NSInteger const rowHeight = 40;
static NSInteger const space = 40;
static const NSInteger timeValue = 1.5;

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        [self createSubviews:frame];
        _loginParam = [[IMALoginParam alloc] init];
        _image = nil;
    }
    return self;
    
}

- (void)createSubviews:(CGRect)frame{
    UIButton *head = [UIButton buttonWithType:UIButtonTypeCustom];
    head.frame = CGRectMake((frame.size.width-80)/2.0, 0, 80, 80);
    head.layer.cornerRadius = 40;
    head.layer.masksToBounds = YES;
    head.adjustsImageWhenHighlighted = NO;
    UIImage *image = [self getImageWithImageName:@"login_camera" bundleName:@"CNLiveLoginModule" targetClass:[self class]];
    [head setImage:image forState:UIControlStateNormal];
    [head addTarget:self action:@selector(headDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:head];
    self.head = head;
    
    CNLiveLoginTextField *nickname = [[CNLiveLoginTextField alloc] initWithFrame:CGRectMake(0, head.bottom+space, frame.size.width, rowHeight)];
    nickname.keyboardType = UIKeyboardTypeNumberPad;
    if(CNUserShareManager.isLogin&&CNUserShareModel.mobile.length >= 11){
        nickname.text = [CNUserShareModel.mobile stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    nickname.placeholder = @"请输入昵称";
    nickname.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
    nickname.placeholderColor = [UIColor colorWithRed:173/255.0 green:173/255.0 blue:173/255.0 alpha:1.0];
    nickname.font = [UIFont systemFontOfSize:16];
    nickname.textAlignment = NSTextAlignmentLeft;
    [nickname addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    nickname.clearButtonMode = UITextFieldViewModeWhileEditing;
    nickname.delegate = self;
    [self addSubview:nickname];
    self.nickname = nickname;
    
    UIButton *next = [UIButton buttonWithType:UIButtonTypeCustom];
    next.frame = CGRectMake(nickname.left, nickname.bottom+space, nickname.width, rowHeight);
    [next setTitle:@"下一步" forState:UIControlStateNormal];
    [next setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    next.titleLabel.font = [UIFont systemFontOfSize:15.0];
    next.backgroundColor = [UIColor colorWithRed:35/255.0 green:212/255.0 blue:30/255.0 alpha:1.0];
    next.layer.cornerRadius = 20;
    next.layer.masksToBounds = YES;
    next.adjustsImageWhenHighlighted = NO;
    [next addTarget:self action:@selector(nextDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:next];
    self.next = next;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
    
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if ([textField isEqual:_nickname]) {
        return YES;
    }
    else {
        return YES;
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    if (![_nickname.text isEqualToString:@""]) {
        _next.enabled = YES;
    }
    else {
        _next.enabled = NO;
    }
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:_nickname]) {
        NSInteger maxTextLength  = 20;
        if(string.length == 0) {
            //判断是不是删除键
            return YES;
        }
        else if(textField.text.length >= maxTextLength) {
            NSLog(@"输入的字符个数大于20,忽略输入");
            return NO;
        }
        else if (textField.text.length + string.length > maxTextLength){
            NSInteger length = textField.text.length;
            NSInteger needLen = maxTextLength - length;
            textField.text = [textField.text stringByAppendingString:[string substringToIndex:needLen]];
            return NO;
        }
        else{
            return YES;
        }
    }
    else{
        return YES;
    }
}

#pragma mark - Action
- (void)headDidClicked:(UIButton *)btn{
    btn.userInteractionEnabled = NO;
    __weak typeof(self) weakSelf = self;
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"拍照" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        btn.userInteractionEnabled = YES;
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) return ;
        __strong typeof(strongSelf) weakSelf = strongSelf;
        [CNLiveAuthorizationManager getAVAuthorizationStatus:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(!strongSelf) return ;
            XFCameraController *cameraController = [[XFCameraController alloc] init];
            cameraController.isCanShootVideo = NO;
            cameraController.modalPresentationStyle = UIModalPresentationFullScreen;
            __weak XFCameraController *weakCameraController = cameraController;
            __weak typeof(strongSelf) weakSelf = strongSelf;
            cameraController.takePhotosCompletionBlock = ^(UIImage *image, NSError *error) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if(!strongSelf) return ;
                strongSelf->_image = image;
                [strongSelf modifyIcon];
//                [strongSelf.head setImage:image forState:UIControlStateNormal];
               
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakCameraController dismissViewControllerAnimated:YES completion:nil];
                });
            };
            [(UIViewController *)self.delegate presentViewController:cameraController animated:YES completion:nil];
        }];

    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"从手机相册中选择" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        btn.userInteractionEnabled = YES;
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) return ;
        __strong typeof(strongSelf) weakSelf = strongSelf;
        [CNLiveAuthorizationManager getPHAuthorizationStatus:^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(!strongSelf) return ;
            TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:strongSelf];
            picker.modalPresentationStyle = UIModalPresentationFullScreen;
            picker.allowPickingVideo = NO;
            picker.allowPreview = NO;
            __weak typeof(strongSelf) weakSelf = strongSelf;
            [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if(!strongSelf) return ;
                strongSelf->_image = [photos firstObject];
                [strongSelf modifyIcon];
//                [strongSelf.head setImage:[photos firstObject] forState:UIControlStateNormal];
            }];
            [(UIViewController *)strongSelf.delegate presentViewController:picker animated:YES completion:nil];
        }];

    }];
    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
          __strong typeof(weakSelf) strongSelf = weakSelf;
          if(!strongSelf) return ;

      }];
           
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    alertController.delegate = self;
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:cancel];
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.alertTitleAttributes];
           
    titleAttributs[NSForegroundColorAttributeName] = [UIColor colorWithRed:35/255.0 green:212/255.0 blue:30/255.0 alpha:1.0];
    
    NSMutableDictionary *cancelAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.alertTitleAttributes];
    cancelAttributs[NSForegroundColorAttributeName] = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];

    action1.buttonAttributes = titleAttributs;
    action2.buttonAttributes = titleAttributs;
    cancel.buttonAttributes = cancelAttributs;

    [alertController showWithAnimated:YES];

}

- (void)didHideAlertController:(QMUIAlertController *)alertController{
    self.head.userInteractionEnabled = YES;
}

#pragma mark - 响应方法
- (void)nextDidClicked:(UIButton *)btn{
    [_nickname resignFirstResponder];
    if ([_nickname.text isEqualToString:@""]) {
        [QMUITips showError:@"请输入昵称" inView:self.superview hideAfterDelay:timeValue];
        return;
    }
    self.next.userInteractionEnabled = NO;
    [self.superview endEditing:YES];
    [self modifyNickName];
}

// 修改头像
- (void)modifyIcon {
    [QMUITips showLoading:@"修改中" inView:self.superview];
    [CNLiveUserSystemCenter uploadIconWithUid:CNUserShareModel.uid icon:_image success:^(id result) {
        [QMUITips hideAllToastInView:self.superview animated:YES];
        NSLog(@"result:%@",result);
        NSString *deFaceUrl = result[@"data"][@"faceUrl"];
        NSString *faceUrl = @"";
        if ([deFaceUrl containsString:@"/mobile/images/mobilehead/default/"]) {
            faceUrl = CNLiveNetAddDefaultHead;
        }else{
            faceUrl = deFaceUrl;
        }
        CNUserShareModel.faceUrl = faceUrl;
        [self.head setImage:self->_image forState:UIControlStateNormal];
        
    } failure:^(NSDictionary *errorDic) {
        [QMUITips hideAllToastInView:self.superview animated:YES];
        [QMUITips showError:errorDic[@"errorMessage"] inView:self.superview hideAfterDelay:timeValue];
    }];
    
}

// 修改名字
- (void)modifyNickName {
    [QMUITips showLoading:@"修改中" inView:self.superview];
    __weak typeof(self) weakSelf = self;
    [CNLiveUserSystemCenter modifyUserInfoType:UserInfoTypeNickName uid:CNUserShareModel.uid modifyInfo:_nickname.text success:^(id result) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) return;
        strongSelf.next.userInteractionEnabled = YES;
        CNUserShareModel.nickname = strongSelf.nickname.text;
        [QMUITips hideAllToastInView:strongSelf.superview animated:YES];
        if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(loginSuccess:result:)]) {
            [strongSelf.delegate loginSuccess:strongSelf result:result];
        }
        
        [QMUITips showLoading:@"正在连接服务器..." inView:strongSelf.superview];
        [strongSelf syncIM];
        
    } failure:^(NSDictionary *errorDic) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf) return;
        strongSelf.next.userInteractionEnabled = YES;
        [QMUITips hideAllToastInView:strongSelf.superview animated:YES];
        [QMUITips showError:[errorDic objectForKey:@"errorMessage"] inView:strongSelf.superview hideAfterDelay:timeValue];
    }];
    
}

// 连接IM
- (void)syncIM {
    [CNLiveLoginRequestModel getTIMLoginToken:CNUserShareModel.uid successBlock:^(NSString *token) {
        self.loginParam.identifier = CNUserShareModel.uid;
        self.loginParam.userSig = token;
        self.loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];

        [[IMAPlatform sharedInstance] login:self.loginParam succ:^{
            [QMUITips hideAllToastInView:self.superview animated:YES];
            [NBSAppAgent setUserIdentifier:[CNLiveBusinessTools getSidIdfv]];
            [self.loginParam saveToLocal];
//            [[AppDelegate sharedAppDelegate] registNotification];
            [[IMAPlatform sharedInstance] configHost:self.loginParam];

//            [[AppDelegate sharedAppDelegate] enterMainUI];

            //游客浏览后登陆
//            [self showTouristsLoginTipsView];

            [[IMAPlatform sharedInstance].host asyncSetAllowType:TIM_FRIEND_NEED_CONFIRM succ:^{
                NSLog(@"asyncSetAllowType Suc");
                [self.loginParam saveToLocal];
            } fail:^(int code, NSString *msg) {
                NSLog(@"asyncSetAllowType failed : %@", msg);
            }];

        } fail:^(int code, NSString *msg) {
            NSLog(@"login failed : %@", msg);
            [QMUITips hideAllToastInView:self.superview animated:YES];
            [QMUITips showError:msg inView:self.superview hideAfterDelay:timeValue];
        }];

    } failedBlock:^(int code, NSString *errorMsg) {
        NSLog(@"token code:%d     error:%@", code, errorMsg);
        [QMUITips hideAllToastInView:self.superview animated:YES];
        [QMUITips showError:errorMsg inView:self.superview hideAfterDelay:timeValue];
    }];
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end