//
//  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"
#import "SLWebSocketManager.h"

@interface SLMessageViewController ()<WebSocketManagerDelegate>

@property (nonatomic, strong) YMChatServiceView *chatServiceView;

@property (nonatomic, strong) SLNuisdkPlay *nuisdkPlay;

@property (weak, nonatomic) IBOutlet UIView *addFriendBgView;

@end

@implementation SLMessageViewController

- (void)dealloc {
    [self.nuisdkPlay stopNuisdkPlay];
    self.nuisdkPlay = nil;
    [SLWebSocketManager SharedInstance].delegate = 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)stopNuisdkPlay {
    [self.nuisdkPlay stopNuisdkPlay];
    [self.chatServiceView.messageView.chatDataManager enumerateObjectsUsingBlock:^(MessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.onBroadcast) {
            obj.onBroadcast = NO;
            [self.chatServiceView.messageView.messageCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]]];
        }
    }];
}

- (NSString *)replaceHasPrefix:(NSString *)fixStr str:(NSString *)str {
    if ([str hasPrefix:fixStr]) {
        NSString *newStr = [str substringFromIndex:fixStr.length];
        return [self replaceHasPrefix:fixStr str:newStr];
    }
    return str;
}

-(void)webSocketDidReceiveChatMessage:(NSString *)string {
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    id resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//what is about webSocket heart
    if ([[resultDic objectForKey:@"Type"] isEqualToString:@"ChatMessageDto"]) {
        SLSocketMessage *msgModel = [SLSocketMessage mj_objectWithKeyValues:[resultDic objectForKey:@"Data"]];
        if ([self.friendModel.userId isEqualToString:msgModel.AIId]) {
            NSString *str = [self replaceHasPrefix:@"\n" str:msgModel.Message];
            MessageModel *model = [MessageModel initWithSendText:str isReceive:YES showMike:msgModel.MessageType showText:!msgModel.MessageType isMike:msgModel.MessageType];
            [self.chatServiceView.messageView appendRequestMessage:model];
        }else {
            [[SLMessageManager SharedInstance] saveSocketChatMessageWith:resultDic];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.friendModel.userName;
    [SLWebSocketManager SharedInstance].delegate = self;
    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];
                [models enumerateObjectsUsingBlock:^(MessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    obj.onBroadcast = NO;
                    if (obj.showMike) {
                        obj.showText = NO;
                    }
                    obj.showTrans = NO;
                }];
                self.chatServiceView.messageView.chatDataManager = [NSMutableArray arrayWithArray:models];
                [self.chatServiceView.messageView.messageCollectionView reloadData];
            });
        }
        [self requestData];
    });
    
    if (@available(iOS 11.0, *)) {
        self.chatServiceView.messageView.messageCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    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 configNavigationBar];
    [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) {
        NSInteger idx = [weakSelf.chatServiceView.messageView.chatDataManager indexOfObject:msgModel];
        if (!msgModel.isReceive && msgModel.showMike) {
            [weakSelf.nuisdkPlay playSendVoice:msgModel finshBlock:^{
                msgModel.onBroadcast = NO;
                [weakSelf.chatServiceView.messageView.messageCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]]];
            }];
        }else {
            RoleModel *model = [RoleModel mj_objectWithKeyValues:[[SLGlobalInfo SharedInstance].roleModel mj_JSONObject]];
            model.aiSex = weakSelf.friendModel.sex;
            [weakSelf.nuisdkPlay startTTSWith:msgModel.sendText roleModel:model finshBlock:^{
                msgModel.onBroadcast = NO;
                [weakSelf.chatServiceView.messageView.messageCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]]];
            }];
        }
    };
    
    
    [[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];
    if (!self.friendModel.isFriend) {
        self.addFriendBgView.hidden = self.friendModel.isFriend;
        [self.view bringSubviewToFront:self.addFriendBgView];
    }
}

- (void)requestData {
    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/Chat/GetChatRecord" parameter:@{@"friendId" : self.friendModel.userId} success:^(id responseObject) {
        NSArray *chatModels = self.chatServiceView.messageView.chatDataManager;
        if (chatModels.count) {
            MessageModel *msgModel = chatModels.lastObject;
            NSArray *arr = [responseObject objectForKey:@"data"];
            NSArray *msgRecives = [SLMessageReceiveModel mj_objectArrayWithKeyValuesArray:arr];
            __block NSInteger addIdx = 0;
            NSMutableArray *marr = [NSMutableArray arrayWithArray:chatModels];
            [msgRecives enumerateObjectsUsingBlock:^(SLMessageReceiveModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.message isEqualToString:msgModel.sendText] && addIdx == 0) {
                    NSString *timeStr = [NSString stringWithFormat:@"%f",msgModel.sendTime * 1000];
                    NSString *formtTime = [NSString timeFromFormatter:@"hh:mm" timeString:timeStr];
                    if ([obj.sendDate isEqualToString:formtTime]) {
                        addIdx = idx;
                    }
                }
                if (addIdx != 0 && idx > addIdx) {
                    if (!obj.interactMode) {
                        MessageModel *model = [MessageModel initWithSendText:obj.message isReceive:obj.interactMode showMike:NO showText:YES isMike:NO];
                        [marr addObject:model];
                    }else {
                        MessageModel *model = [MessageModel initWithSendText:obj.message isReceive:obj.interactMode showMike:obj.messageType showText:!obj.messageType isMike:obj.messageType];
                        [marr addObject:model];
                    }
                    
                }
            }];
            if (marr.count != chatModels.count) {
                self.chatServiceView.messageView.chatDataManager = marr;
                [self.chatServiceView.messageView.messageCollectionView reloadData];
                [self.chatServiceView.messageView scrollToBottom:YES];
            }
        }
        
    } failure:^(SPRequestError *error) {
        
    }];
}

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

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

//设置已读
- (void)setRecordStates {
    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/Chat/SetRecordStates" parameter:@{@"friendId" : self.friendModel.userId} success:^(id responseObject) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SLSetRecordStates" object:nil];
    } failure:^(SPRequestError *error) {
        
    }];
}

- (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;
            }
        }];
    }
}

- (IBAction)addFriendClick:(id)sender {
    [[SLHttpCenter SharedInstance] getWithUrl:@"/api/Contacts/AddContacts" parameter:@{@"userId" : self.friendModel.userId} success:^(id responseObject) {
        [ZFToast ShowWithMessage:@"添加成功"];
        self.addFriendBgView.hidden = YES;
    } failure:^(SPRequestError *error) {

    }];
}

#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.0) {
                    [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
