//
//  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;
    [self.view bringSubviewToFront:self.navigationBar];
}

- (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];
    dispatch_async(dispatch_queue_create("sl.cache.chat.date", DISPATCH_QUEUE_CONCURRENT), ^{
        NSString *key = [NSString stringWithFormat:@"%@--to--%@",[SLGlobalInfo SharedInstance].loginInfo.user.userId, self.friendModel.userId];
        NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:key];
        if (arr.count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSArray *models = [MessageModel mj_objectArrayWithKeyValuesArray:arr];
                self.chatServiceView.messageView.chatDataManager = [NSMutableArray arrayWithArray:models];
                [self.chatServiceView.messageView.messageCollectionView reloadData];
            });
        }
    });
    
    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);
    }];

    
    WS(weakSelf);
//    [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];
    dispatch_async(dispatch_queue_create("sl.save.chat.date", DISPATCH_QUEUE_CONCURRENT), ^{
        [[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;
    
    UICollectionView *scrollView = self.chatServiceView.messageView.messageCollectionView;

    CGFloat messageMaxY = scrollView.contentSize.height;
    //    CGFloat messageMaxY = [self.chatServiceView.messageView getBotttomCellMaxY];
    CGFloat msgHeigh = kSCREEN_HEIGHT - kNavBarHeight - CGRectGetHeight(self.chatServiceView.chatBottomView.frame);
    if (messageMaxY > msgHeigh) {
        CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
        [scrollView setContentOffset:bottomOffset animated:YES];
    }
    //执行动画
    void (^animation)(void) = ^void(void) {
        if (messageMaxY - transformY > msgHeigh) {
            CGFloat transformY1 = -(messageMaxY - transformY - msgHeigh);
            CGFloat mainTransformY = MAX(transformY1, transformY);//聊天view
            if (messageMaxY < msgHeigh) {
                mainTransformY -= 50.0;
            }
            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;
}

- (SLMikeInputView *)mikeInputView {
    if (!_mikeInputView) {
        _mikeInputView = [[SLMikeInputView alloc] initWithFrame:CGRectZero];
        WS(weakSelf);
        _mikeInputView.nuiSpeechRecognizer.recognizerResultBlock = ^(NSString * _Nonnull text, NSString * _Nonnull voicePath) {
            MessageModel *model = [MessageModel initWithSendText:text isReceive:NO showMike:YES showText:NO isMike:YES voicePath:voicePath];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (model.audioDuration < 1.2) {
                    [ZFToast ShowWithMessage:@"说话时间太短！"];
                }else {
                    model.toId = weakSelf.friendModel.userId;
                    [weakSelf.chatServiceView.messageView appendMessage:model];
                }
            });
        };
        [self.view addSubview:_mikeInputView];
        [self.view bringSubviewToFront:self.mikeInputView];
    }
    return _mikeInputView;
}

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

@end
