//
//  SLMessageViewController.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/1.
//

#import "SLMessageViewController.h"
#import "YMChatServiceView.h"
#import "MessageModel.h"
#import "SLNuisdkPlay.h"
#import "SLFriensInfoVc.h"

@interface SLMessageViewController ()

@property (nonatomic, strong) YMChatServiceView *chatServiceView;

@property (nonatomic, strong) SLNuisdkPlay *nuisdkPlay;

@end

@implementation SLMessageViewController

- (void)dealloc {
    [self.nuisdkPlay stopNuisdkPlay];
    self.nuisdkPlay = nil;
}

- (void)configNavigationBar {
    UIImage *creatImage =[UIImage imageNamed:@"icon_pyq_more_back"];
    YMBarButtonItem *rightBarItem =[[YMBarButtonItem alloc]initWithImage:creatImage style:YMBarButtonItemPlain target:self action:@selector(moreBtnClick)];
    rightBarItem.titleInsets = UIEdgeInsetsMake(0, 0, 0, 20);
    self.navigationBar.rightBarButtonItem = rightBarItem;
}

- (void)moreBtnClick {
    SLFriensInfoVc *vc = [SLFriensInfoVc loadViewControllewWithNib];
    vc.friendModel = self.friendModel;
    [self navPushViewController:vc animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.friendModel.userName;
    [self configNavigationBar];
    NSString *key = [NSString stringWithFormat:@"%@--to--%@",[SLGlobalInfo SharedInstance].loginInfo.user.userId, self.friendModel.userId];
    NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if (arr) {
        NSArray *models = [MessageModel mj_objectArrayWithKeyValuesArray:arr];
        self.chatServiceView.messageView.chatDataManager = [NSMutableArray arrayWithArray:models];
    }
    self.chatServiceView.friendModel = self.friendModel;
    self.chatServiceView.messageView.friendModel = self.friendModel;
    [self.chatServiceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kNavBarHeight);
        make.left.bottom.right.equalTo(self.view);
    }];
    self.mikeInputView = [[SLMikeInputView alloc] initWithFrame:CGRectZero];
    WS(weakSelf);
    self.mikeInputView.nuiSpeechRecognizer.recognizerResultBlock = ^(NSString * _Nonnull text, NSString * _Nonnull voicePath) {
        MessageModel *model = [MessageModel initWithSendText:text isReceive:NO showMike:YES showText:NO isMike:YES voicePath:voicePath];
        model.toId = weakSelf.friendModel.userId;
        [weakSelf.chatServiceView.messageView appendMessage:model];
    };
    self.mikeInputView.hidden = YES;
    [self.view addSubview:self.mikeInputView];
    [self.view bringSubviewToFront:self.mikeInputView];
    [self.view bringSubviewToFront:self.navigationBar];
    
    [self nuisdkPlay];
    [self.KVOController observe:self.mikeInputView.contentView keyPath:@"hidden" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        if (![change[NSKeyValueChangeNewKey] boolValue]) {
            [weakSelf.nuisdkPlay stopNuisdkPlay];
        }
    }];
    //
    self.chatServiceView.messageView.broadcastBlock = ^(MessageModel * _Nonnull msgModel) {
        if (!msgModel.isReceive && msgModel.showMike) {
            [weakSelf.nuisdkPlay playSendVoice:msgModel];
        }else {
            [weakSelf.nuisdkPlay startTTSWith:msgModel.sendText roleModel:[SLGlobalInfo SharedInstance].roleModel finshBlock:^{

            }];
        }
    };
//    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/Chat/GetChatRecord" parameter:@{@"friendId" : self.friendModel.userId} success:^(id responseObject) {
//
//    } failure:^(SPRequestError *error) {
//        
//    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name: UIApplicationDidEnterBackgroundNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self saveChatData];
}

- (void)backBarButtonPressed:(id)pressed {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveChatData {
    NSString *key = [NSString stringWithFormat:@"%@--to--%@",[SLGlobalInfo SharedInstance].loginInfo.user.userId, self.friendModel.userId];
    NSArray *dictArr = [NSObject mj_keyValuesArrayWithObjectArray:self.chatServiceView.messageView.chatDataManager];
    [[NSUserDefaults standardUserDefaults] setObject:dictArr forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.hiddenMikeSegment) {
        [self.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.tag == SLMikeSegMentBgTag) {
                [obj removeFromSuperview];
                obj = nil;
            }
        }];
    }
}

#pragma mark --键盘弹出
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
        //取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - kSCREEN_HEIGHT + kSafeAreaBottom;
    //执行动画
    CGFloat messageMaxY = [self.chatServiceView.messageView getBotttomCellMaxY];
    void (^animation)(void) = ^void(void) {
        if (messageMaxY - transformY > kSCREEN_HEIGHT - kNavBarHeight - CGRectGetHeight(self.chatServiceView.chatBottomView.frame)) {
            CGFloat transformY1 = -(messageMaxY - transformY - (kSCREEN_HEIGHT - kNavBarHeight - CGRectGetHeight(self.chatServiceView.chatBottomView.frame)));
            CGFloat mainTransformY = MAX(transformY1, transformY);//聊天view
            CGFloat bottomTransformY = transformY - mainTransformY;//输入view
            self.chatServiceView.transform = CGAffineTransformMakeTranslation(0, mainTransformY);
            self.chatServiceView.chatBottomView.transform = CGAffineTransformMakeTranslation(0,bottomTransformY);
        }else {
            self.chatServiceView.chatBottomView.transform = CGAffineTransformMakeTranslation(0, transformY);
        }
    };
    if (duration > 0) {
        [UIView animateWithDuration:duration animations:animation];
    } else {
        animation();
    }
}

#pragma mark --键盘收回
- (void)keyboardDidHide:(NSNotification *)notification {
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    void (^animation)(void) = ^void(void) {
        self.chatServiceView.transform = CGAffineTransformMakeTranslation(0, 0);
        self.chatServiceView.chatBottomView.transform = CGAffineTransformMakeTranslation(0, 0);
    };
    if (duration > 0) {
        [UIView animateWithDuration:duration animations:animation];
    } else {
        animation();
    }
}

- (void)applicationEnterBackground {
    [self saveChatData];
}

- (YMChatServiceView *)chatServiceView
{
    if (!_chatServiceView) {
        _chatServiceView = [[YMChatServiceView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:_chatServiceView];
    }
    return _chatServiceView;
}

- (SLNuisdkPlay *)nuisdkPlay {
    if (!_nuisdkPlay) {
        _nuisdkPlay = [[SLNuisdkPlay alloc] init];
    }
    return _nuisdkPlay;
}

- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
