//
//  AIChatAgentController.m.h
//  ChatAgentApp
//
//  Created by Sun,Jian(ACU-T102) on 2018/12/31.
//  Copyright © 2018年 Sun,Jian(ACU-T102). All rights reserved.
//

#import "AIChatAgentController.h"
#import <MobileCoreServices/MobileCoreServices.h>

#import <BaiduChatAgent/BaiduChatAgentDelegate.h>
#import <BaiduChatAgent/BaiduChatAgentDefines.h>
#import <BaiduChatAgent/BaiduChatAgent.h>
#import <BaiduRtcRoom/RTCRemoteVideoView.h>
#import "BDCloudRTCBaseDefine.pch"
#import "BaiduAgentApi.h"
#import "AIChatInputBar.h"
#import "AIChatUploadImageView.h"
#import "AIChatCameraPreviewView.h"
#import "BCALicenseManager.h"

#import "BCAFuncallHandler.h"
#ifdef DEBUG
#import "BCAFuncallDemoContent.h"
#endif

#define W ([UIScreen mainScreen].bounds.size.width)
#define H ([UIScreen mainScreen].bounds.size.height)
#define LINE_SPACE 20

static NSString *const AGETN_MATH_PREFIX = @"<-正常对话->";

static CGFloat const IMAGE_ITEM_HEIGHT = 150;

@interface AIMsgItem : NSObject
@property (nonatomic, assign) BOOL remoteUser;
@property (nonatomic, copy) NSString *message;
@property (nonatomic, assign) NSInteger timeStamp;
@property (nonatomic, assign) NSInteger rowHeight;
@property (nonatomic, copy) NSString *funcallSessionId;
@property (nonatomic, strong) BCAFuncallResultView *funcallResultView;

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSURL *imageUrl;
@property (nonatomic, assign) UploadStatus uploadStatus;

@end
@implementation AIMsgItem
- (instancetype)initParam:(BOOL)remote msg:(NSString *)message heigth:(NSInteger)height{
    if (self = [super init]) {
        self.remoteUser = remote;
        self.message = message;
        self.rowHeight = height;
    }
    return  self;
}
@end

@interface AIChatAgentController ()<BaiduChatAgentDelegate, BaiduAgentApiEventDelegate, RTCRemoteVideoViewDelegate,
    BCAFuncallHandlerDelegate,
    AIChatInputBarDelegate,
    UINavigationControllerDelegate, UIImagePickerControllerDelegate,
    AIChatCameraPreviewViewDelegate
>

@property (nonatomic, weak) id<AIChatAgentControllerDelegate> delegate;
@property (nonatomic, strong) UISwipeGestureRecognizer *swipeGesture;
@property (nonatomic, strong) AgentEngineParams *baiduChatAgentParms;
@property (nonatomic, strong) BaiduChatAgent *baiduChatAgent;
@property (nonatomic, copy) NSString *tokenAgent;
@property (nonatomic, copy) NSString *appId;
@property (nonatomic, copy) NSString *userId;
@property (nonatomic, copy) NSString *paramStr;
@property (nonatomic, copy) NSMutableArray<AIMsgItem *> *messageArr;
@property(nonatomic, strong) BaiduAgentApi *agentHttpApi;

@property (nonatomic, strong) AIMsgItem *mLastAgentBean;
@property (nonatomic, strong) AIMsgItem *mLastAsrBean;
@property (nonatomic, strong) AIMsgItem *mTextAsrBean;

@property (nonatomic, strong) UILabel *transparentLabelAgent;
@property (nonatomic, strong) UILabel *transparentLabelAsr;
@property (nonatomic, strong) UILabel *labInstanceidSessionId;
@property (nonatomic, strong) AIChatInputBar *inputBar;

@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) RTCRemoteVideoView *szrVideoView;
@property (nonatomic, strong) AIChatCameraPreviewView *localPreviewView;
@property (nonatomic, assign) BOOL isHD;

@property (nonatomic, strong) BCAFuncallHandler *funcallHandler;

@end

@implementation AIChatAgentController

- (instancetype)initWithParams:(id<AIChatAgentControllerDelegate>)delegate
                          conf:(NSString *)param
                           app:(NSString *)aapID
                          user:(NSString *)userId
                            hd:(BOOL)isHD {
    if (self = [super init]) {
        self.delegate = delegate;
        self.agentHttpApi = [[BaiduAgentApi alloc] initWithParams:param delegate:self];
        
        self.appId = [aapID length] > 0 ? aapID : BDCloudDefaultRTCAppID;
        self.userId = userId;
        self.paramStr = param;
        self.isHD = isHD;
    }
    return self;
}

- (void)AgentInitAndRtcCall{
    BaiduAgentApiStartRequest *req = [[BaiduAgentApiStartRequest alloc] init];
    req.appId = self.appId;
    req.quicStart = YES;
    req.config = self.paramStr;
    self.isHD = self.isHD;
    
    [self.agentHttpApi sendStartRequest:req block:^(BaiduAgentApiStartResponse *res) {
        self.dateFormatter = [[NSDateFormatter alloc] init];
        self.tokenAgent = res.token;
        self.baiduChatAgentParms = [[AgentEngineParams alloc] init];
        self.baiduChatAgentParms.appId = req.appId;
        self.baiduChatAgentParms.config = res.context;
        self.baiduChatAgentParms.instanceId = res.instanceId;
        self.baiduChatAgentParms.verbose = NO;
        self.baiduChatAgentParms.enableVoiceInterrupt = YES;
        
        // 请替换成您的 licenseKey
        self.baiduChatAgentParms.licenseKey = [BCALicenseManager licenseKeyForAppID:req.appId];
        self.baiduChatAgentParms.userId = self.userId;
        
        self.mLastAgentBean = nil;
        self.mLastAsrBean = nil;
        self.baiduChatAgent = [[BaiduChatAgent alloc] initWithParams:self.baiduChatAgentParms delegate:self];
        if (self.baiduChatAgent) {
            if (self.isHD) {
                [self.baiduChatAgent setDigitalDisplay:self.szrVideoView];
            }
            [self.baiduChatAgent presetLoudSpeaker:YES];
            [self.baiduChatAgent call:self.tokenAgent instanceId:self.baiduChatAgentParms.instanceId];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.labInstanceidSessionId.text = [NSString stringWithFormat:@"roomID:%ld", self.baiduChatAgentParms.instanceId];
        });
    }];
}

#pragma BaiduAgentApiStopResponse event
- (void) BaiduAgentApiConnectFailed {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showTooltipForButton];
    });
}

- (void)showTooltipForButton {
    [self alertTitle:@"没有网络权限，机器人不会正常工作，\r\n请允许权限后重新登陆" andMessage:@"" andOK:@"确定" andCancle:@"取消" andBlock:^(UIAlertAction * _Nonnull action) {
                      
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.21 green:0.56 blue:0.8 alpha:1.0];
    self.navigationItem.title = @"chat";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSForegroundColorAttributeName:[UIFont systemFontOfSize:18]}];
    
    //导航栏左侧按钮
    UIButton *backbutton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [backbutton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(back) forControlEvents:UIControlEventAllTouchEvents];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backItem;
    
   /* UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, W, H - 108)];
    view.backgroundColor = [UIColor blackColor];
    view.tag = 101;*/
    //[self.view addSubview:self.AnimationViewRemote];
    
    if (self.isHD) {
        //数字人显示
        self.szrVideoView = [[RTCRemoteVideoView alloc] initWithDelegate:self];
        // remoteVideoView1.renderStuckInterval = 300;
        self.szrVideoView.videoView.frame = CGRectMake(0, 0, W, H - 88);
        [self.szrVideoView.videoView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:self.szrVideoView.videoView];
    }
        
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, W, H - 88) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //设置分割线(设置为无样式)
    _tableView.separatorStyle = UITableViewCellAccessoryNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.contentInset = UIEdgeInsetsMake(44, 0, 44, 0);
    
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
//    [self.view addSubview:view];
//    [self.view bringSubviewToFront:view];
    
    self.inputBar = [[AIChatInputBar alloc] initWithFrame:CGRectZero];
    self.inputBar.delegate = self;
    [self.view addSubview:self.inputBar];
    
    //设置聊天信息数值
    _messageArr = [NSMutableArray arrayWithObjects:[[AIMsgItem alloc] initParam:YES msg:@"你好，我是ChatAgent" heigth:83], nil];
    
    //_messageRole = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:1], nil];
    
    _rowHeightArr = [[NSMutableArray alloc] init];
    for (AIMsgItem *msgItem in _messageArr) {
        //因为boundingRectWithSize: options: attributes: context: 函数中参数三需要使用字典数组
        //P1:文本显示的最大宽度和最大高度
        //P2:计算的类型 NSStringDrawingUsesLineFragmentOrigin 绘制文本时使用，一般使用这项
        //P3:文本属性
        //P4:包括一些信息，例如如何调整字间距以及缩放。该参数一般可为 nil
        NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:18]};
        CGSize size = [msgItem.message boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.41) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
        //聊天框高度，+ 为了保持会话之间的距离
        int height = size.height + LINE_SPACE;
        _rowHeight = [NSNumber numberWithInt:height];
        //存储在数组里，设置行高时使用
        [_rowHeightArr addObject:_rowHeight];
    }
    //监视键盘回收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisAppear:) name:UIKeyboardWillHideNotification object:nil];
    
//    // 创建一个左滑手势识别器
//    self.swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
//    // 设置手势的方向为左滑
//    self.swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
//    // 将手势识别器添加到当前视图控制器的view上
//    [self.view addGestureRecognizer:self.swipeGesture];
    self.transparentLabelAgent = [[UILabel alloc] initWithFrame:CGRectMake(W * 0.02, H * 0.02, W * 0.4,  H * 0.06)];
    self.transparentLabelAgent.text = @"Agent: 断句完成";
    self.transparentLabelAgent.textColor = [UIColor blueColor]; // 设置文本颜色为白色，以便在透明背景下可见
    self.transparentLabelAgent.backgroundColor = [UIColor clearColor]; // 设置背景色为清除色，即透明
    self.transparentLabelAgent.alpha = 1.0; // 设置alpha值为1，保证不会因为alpha值的影响而看起来更透明
    [self.view addSubview:self.transparentLabelAgent];
    
    self.transparentLabelAsr = [[UILabel alloc] initWithFrame:CGRectMake(W * 0.5, H * 0.02, W * 0.4,  H * 0.06)];
    self.transparentLabelAsr.text = @"Local: 断句完成";
    self.transparentLabelAsr.textColor = [UIColor blueColor]; // 设置文本颜色为白色，以便在透明背景下可见
    self.transparentLabelAsr.backgroundColor = [UIColor clearColor]; // 设置背景色为清除色，即透明
    self.transparentLabelAsr.alpha = 1.0; // 设置alpha值为1，保证不会因为alpha值的影响而看起来更透明
    [self.view addSubview:self.transparentLabelAsr];
    
    self.labInstanceidSessionId = [[UILabel alloc] initWithFrame:CGRectMake(W * 0.2, H * 0.06, W * 0.7,  H * 0.04)];
    self.labInstanceidSessionId.text = [NSString stringWithFormat:@"sessionID:%ld", self.baiduChatAgentParms.instanceId];
    self.labInstanceidSessionId.textColor = [UIColor redColor]; // 设置文本颜色为白色，以便在透明背景下可见
    self.labInstanceidSessionId.backgroundColor = [UIColor clearColor]; // 设置背景色为清除色，即透明
    self.labInstanceidSessionId.alpha = 1.0; // 设置alpha值为1，保证不会因为alpha值的影响而看起来更透明
    [self.view addSubview:self.labInstanceidSessionId];
    //[_tableView bringSubviewToFront:self.transparentLabelAgent];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
    tapGesture.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGesture];
    
    [self AgentInitAndRtcCall]; //启动服务器Agent and rtc端侧交互端
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.baiduChatAgent muteMic:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    // app 内离开页面，暂停互动对话
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        [self.baiduChatAgent muteMic:YES];
    }
}

- (void)viewSafeAreaInsetsDidChange {
    [super viewSafeAreaInsetsDidChange];
    
    // 安全区域变化时更新
    [self updateInputBarFrame];
}

- (void)updateInputBarFrame {
    CGFloat safeAreaBottom = 0.f;
    if (@available(iOS 11.0, *)) {
        safeAreaBottom = kSafeAreaBottom;
    }
    if (self.inputBar.isKeyboardShow) {
        safeAreaBottom = 0.f;
    }
    CGFloat barHeight = kInputBarHeight + safeAreaBottom; // 根据实际需要调整高度
    CGRect barFrame = CGRectMake(0, H - barHeight, W, barHeight);
    self.inputBar.frame = barFrame;
}

// 处理滑动手势的方法
- (void)handleSwipe:(UISwipeGestureRecognizer *)gesture {
    if (gesture.direction == UISwipeGestureRecognizerDirectionLeft) {
        // 左滑触发的代码
        NSLog(@"左滑触发");
    }
}

- (void)dismissKeyboard:(UITapGestureRecognizer *)gesture {
    CGPoint touchPoint = [gesture locationInView:self.view];
    
    BOOL touchInInputBar = CGRectContainsPoint(self.inputBar.frame, touchPoint) ||
                          [self.inputBar hitTest:[self.view convertPoint:touchPoint toView:self.inputBar] withEvent:nil] != nil;
    
    if (!touchInInputBar) {
        [self.inputBar.textField resignFirstResponder];
    }
}

- (void)pauseChatViewController {
    NSLog(@"Agent Pause!!");
    [self.baiduChatAgent interrupt];
}

- (void)popChatViewController {
    [_delegate viewControllerDidFinish:self];
}

- (void)inputBarActionWithTag:(BUTTON_TAG)tag {
    switch (tag) {
        case BUTTON_TAG_QUIT:
            [self popChatViewController];
            break;
        case BUTTON_TAG_PAUSE:
            [self pauseChatViewController];
            break;
        case BUTTON_TAG_CAMERA:
            [self openCameraPreview];
            [self.inputBar hideMediaPanel];
            break;
        case BUTTON_TAG_PHOTO:
            [self openPhotoLibrary];
            [self.inputBar hideMediaPanel];
            break;
        default:
            break;
    }
}

- (void)inputBarDidSendText:(NSString *)text {
    //if (self.mLastAsrBean == nil) {
        NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:18]};
        CGSize size = [text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
        self.mTextAsrBean = [[AIMsgItem alloc] initParam:NO msg:text heigth:(size.height + LINE_SPACE)];
        [self AddSendMessage:self.mTextAsrBean];
    //}
    
    if (self.baiduChatAgent) {
        [self.baiduChatAgent sendTextToAIAgent:text];
    }
}

- (void)AddSendMessage:(AIMsgItem*) Item{
    [_messageArr addObject:Item];
    NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:18]};
    //自适应高度，并计算
    CGSize size = [self.inputBar.textField.text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
    int height = size.height + LINE_SPACE;
    _rowHeight = [NSNumber numberWithInt:height];
    [_rowHeightArr addObject:_rowHeight];
    //_messageArr.count - 1 ： 显示的最后一行
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_messageArr.count - 1) inSection:0];
    //加入一个cell
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    //更新tableView
    [_tableView reloadData];
    
    //滚动界面（随着消息发送上移）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AIMsgItem *item = _messageArr[indexPath.row];
    if (item.funcallResultView) {
        return [self cellForTableView:tableView funcallResultMsgItem:item];
    }
    if (item.imageUrl) {
        return [self cellForTableView:tableView uploadImageMsgItem:item];
    }
    
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    } else {
        //tableView的复用，如果不删除，会出现bug
        //删除cell所有的子视图
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    //分割线风格（无显示）
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BOOL boRemote = YES;
    if ([_messageRole[indexPath.row] integerValue] == 1 ) {
        boRemote = YES;
    } else {
        boRemote = NO;
    }
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterFullStyle];

    NSDate *currentDate = [NSDate date];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];

//    NSLog(@"current date string: %@", dateString);
    
//    [self.dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [self.dateFormatter setDateStyle:NSDateFormatterFullStyle];


    [self.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    
    NSString *dateString1 = [self.dateFormatter stringFromDate:[NSDate date]];

//    NSLog(@"Date%@", dateString1);
    
    //一人一句话
    //if (indexPath.row % 2 == 0){
    if (item.remoteUser) {
        //设置头像
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"chat_left_agent_ic.png"]];
        imageView.frame = CGRectMake(W * 0.01, W * 0.01, W * 0.1, W * 0.1);
        [cell.contentView addSubview:imageView];
        
        //设置对话框
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = item.message;
        label.font = [UIFont systemFontOfSize:18];
        label.textColor = [UIColor lightGrayColor];
        NSDictionary *attri = @{NSFontAttributeName:label.font};
        
        //自适应高度
        CGSize size = [label.text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
        label.frame = CGRectMake(W * 0.13, W * 0.05, size.width, size.height);
        
        //设置聊天气泡
        UIImageView *imageViewBubble = [[UIImageView alloc] init];
        imageViewBubble.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.0];
        imageViewBubble.frame = CGRectMake(W * 0.12, W * 0.03, size.width + W * 0.05, size.height + W * 0.03);
        
        [cell.contentView addSubview:imageViewBubble];
        [cell.contentView addSubview:label];
        //设置透明属性
        imageViewBubble.backgroundColor = [UIColor clearColor];
        label.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        
    } else {
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chat_right_me_ic.png"]];
        imageView.frame = CGRectMake(W * 0.89, W * 0.01, W * 0.1, W * 0.1);
        [cell.contentView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.text = item.message;
        label.font = [UIFont systemFontOfSize:18];
        label.textColor = [UIColor  systemTealColor];
        NSDictionary *attri = @{NSFontAttributeName:label.font};
        CGSize size = [label.text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
        label.frame = CGRectMake(W * 0.86 - size.width, W * 0.05, size.width, size.height);
        
        UIImageView *imageViewBubble = [[UIImageView alloc] init];
        imageViewBubble.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.0];
        imageViewBubble.frame = CGRectMake(W * 0.82 - size.width, W * 0.03, size.width + W * 0.05, size.height + W * 0.03);
        
        [cell.contentView addSubview:imageViewBubble];
        [cell.contentView addSubview:label];
        
        //设置透明属性
        imageViewBubble.backgroundColor = [UIColor clearColor];
        label.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
    }
    // 设置layer的背景色为半透明
    
    // 创建一个自定义的背景视图
       UIView *backgroundView = [[UIView alloc] initWithFrame:cell.bounds];
       backgroundView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5]; // 半透明白色背景
       backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
       
    //cell.backgroundView = backgroundView;
       
    return cell;
}

//显示简单的键盘回收
- (void)keyboardWillDisAppear:(NSNotification *)notification{
    //第一个参数是动画持续时间
    //第二个参数是方法，这里让视图恢复原来的位置就好
    [UIView animateWithDuration:1 animations:^{self.view.transform = CGAffineTransformMakeTranslation(0, 0); }];
    
}

- (void)keyboardWillAppear:(NSNotification *)notification{
    //计算键盘高度
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = keyboardFrame.origin.y;
    //视图整体上升
    [UIView animateWithDuration:1.0 animations:^{self.view.transform = CGAffineTransformMakeTranslation(0, keyboardY - self.view.frame.size.height); }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _messageArr.count;
}

//设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //将NSNumber型的height转换为CGFloat型
     //CGFloat height = [_rowHeightArr[indexPath.row] floatValue];
    CGFloat height = _messageArr[indexPath.row].rowHeight;
    return height;
}

- (void)back{
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    BaiduAgentApiStopRequest* req = [[BaiduAgentApiStopRequest alloc] init];
    req.appId = self.appId;
    req.instanceId = self.baiduChatAgentParms.instanceId;
    [self.agentHttpApi sendStopRequest:req block:^(BaiduAgentApiStopResponse * res) {
        NSLog(@"sendStopRequest done!");
    }];
    NSLog(@"RTCViewCallViewController dealloc!");
    if (self.baiduChatAgent) {
        [self.baiduChatAgent destroy];
        self.baiduChatAgent = nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma BaiduChatAgentDelegate methord
/**
 *  错误信息回调
 *  @param errCode 错误号码
 *  @param errMsg  错误消息提示
 *  @param extInfo 附加信息
 */
- (void)onError:(NSInteger)errCode errMsg:(NSString *)errMsg extInfo:(nullable NSDictionary*)extInfo {
    NSLog(@"agent onError(%@) %@", @(errCode), errMsg);
}

/**
 * 状态变化
 */
- (void)onCallStateChange:(NSInteger)state {
    
}

/**
 * 链接状态变化
 */
- (void)onConnectionStateChange:(NSInteger)state {
    
}

/**
 * 用户端音频ASR结果
 */
- (void)onUserAsrSubtitle:(NSString *)text isFinal:(BOOL)isFinal {
    NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:18]};
    //自适应高度，并计算
    CGSize size = [text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
    int height = size.height + LINE_SPACE;
    _rowHeight = [NSNumber numberWithInt:height];
    
    NSLog(@"[BaiduChatAgent_ASR][%ld] onUserAsrSubtitle: %@  is %d  height:%ld", [[NSDate date] timeIntervalSince1970] * 1000,
            text, isFinal, [_rowHeight integerValue]);
    if (!isFinal) {
        //[_messageArr addObject:[[AIMsgItem alloc] initParam:YES msg:@"你好，我是ChatAgent"]];
        if (self.mLastAsrBean == nil) {
            self.mLastAsrBean = [[AIMsgItem alloc] initParam:NO msg:text heigth:height];
            [self AddSendMessage:self.mLastAsrBean];
        } else {
            self.mLastAsrBean.message = text;
            self.mLastAsrBean.rowHeight = height;
            [_tableView reloadData];
        }
    } else {
       if (nil == self.mLastAsrBean) {
           self.mLastAsrBean = [[AIMsgItem alloc] initParam:NO msg:text heigth:height];
       } else {
           self.mLastAsrBean.message = text;
           self.mLastAsrBean.rowHeight = height;
       }

       [_tableView reloadData];
       self.mLastAsrBean = nil;
    }
}

/**
 * AI智能体结果 //Answer
 */
- (void)onAIAgentSubtitle:(NSString *)text isFinal:(BOOL)isFinal {
    
    NSDictionary *attri = @{NSFontAttributeName:[UIFont systemFontOfSize:18]};
    //自适应高度，并计算
    NSLog(@"onAIAgentSubtitle: %@  is %d ", text, isFinal);
    if (!isFinal) {
        //[_messageArr addObject:[[AIMsgItem alloc] initParam:YES msg:@"你好，我是ChatAgent"]];
        if (self.mLastAgentBean == nil) {
            CGSize size = [text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) options:NSStringDrawingUsesLineFragmentOrigin attributes:attri context:nil].size;
            self.mLastAgentBean = [[AIMsgItem alloc] initParam:YES msg:text heigth:(size.height + LINE_SPACE)];
            [self AddSendMessage:self.mLastAgentBean];
        } else {
            self.mLastAgentBean.message = [NSString stringWithFormat:@"%@%@", self.mLastAgentBean.message, text];
            CGSize size = [self.mLastAgentBean.message boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58)
                                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                                 attributes:attri
                                                                    context:nil].size;
            self.mLastAgentBean.rowHeight = size.height + LINE_SPACE;
            [_tableView reloadData];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_messageArr.count - 1) inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
    } else {
        if (nil == self.mLastAgentBean) {

            CGSize size = [text boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58)
                                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                                 attributes:attri
                                                                    context:nil].size;
            
            self.mLastAgentBean = [[AIMsgItem alloc] initParam:YES msg:text
                                                        heigth:(size.height + LINE_SPACE)];
            self.mLastAgentBean.rowHeight = size.height + LINE_SPACE;
            [self AddSendMessage:self.mLastAgentBean];
        } else {
            self.mLastAgentBean.message =  text;
            CGSize size = [self.mLastAgentBean.message boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58) 
                                                                    options:NSStringDrawingUsesLineFragmentOrigin 
                                                                 attributes:attri
                                                                    context:nil].size;
            self.mLastAgentBean.rowHeight = size.height + LINE_SPACE;

            [_tableView reloadData];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_messageArr.count - 1) inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }
        self.mLastAgentBean = nil;
    }
}

/**
 * AI智能体音频状态变化
 */
- (void)onAIAgentAudioStateChange:(AGentAudioState)newState {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (AGENT_STOPPED == newState) {
            self.transparentLabelAgent.text = @"Agent: 断句完成";
            self.transparentLabelAgent.textColor = [UIColor blueColor];
        } else {
            self.transparentLabelAgent.text = @"Agent: speaking";
            self.transparentLabelAgent.textColor = [UIColor redColor];
        }});
    
    int state = newState == AGENT_STOPPED ? 0 : 1;
    [self.funcallHandler onAgentAudioStateChange:state];
}

/**
 * 用户声音状态变化
 */
- (void)onUserAudioStateChange:(AGentAudioState)newState {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if (AGENT_STOPPED == newState) {
            self.transparentLabelAsr.text = @"Local: 断句完成";
            self.transparentLabelAsr.textColor = [UIColor blueColor];
        } else {
            self.transparentLabelAsr.text = @"Local: speaking";
            self.transparentLabelAsr.textColor = [UIColor redColor];
        }
    });
}

/**
 * 智能体音频能量
 */
- (void)onAIAgentAudioLevel:(NSInteger)level {
//    NSLog(@"onAIAgentAudioLevel:%ld", level);
}

/**
 * 用户音频能量
 */
- (void)onUserAudioLevel:(NSInteger)level {
//    NSLog(@"onUserAudioLevel:%ld", level);
}

/**
 * 用户音频能量
 */
- (void) onFunctionCall:(NSString*)sessionId param:(NSString*) params {
#ifdef DEBUG
    params = [BCAFuncallDemoContent contentWithSessionId:sessionId defaultContent:params];
#endif
    NSLog(@"onFunctionCall:%@", params);
    
    if (!self.funcallHandler) {
        self.funcallHandler = [[BCAFuncallHandler alloc] init];
        self.funcallHandler.delegate = self;
    }
    
    BCAFuncallResult ret = [self.funcallHandler executeFuncallWithSessionId:sessionId params:params];
    if (ret == BCAFuncallResultFail) {
        [self.baiduChatAgent sendFunctionCallResult:sessionId result:@"执行失败"];
    }
}

- (void)onUploadFileStatus:(AgentErrorCode)code fileName:(NSString *)filename {
    NSLog(@"[Agent] onUploadFileStatus: %@", @(code));
    for (AIMsgItem *item in self.messageArr) {
        if ([[item.imageUrl lastPathComponent] isEqualToString:filename]) {
            item.uploadStatus = UploadStatusSuccess;
            [self.tableView reloadData];
            break;
        }
    }
}

- (void)onAgentIntent:(NSString *)type extInfo:(NSDictionary *)extInfo {
    NSLog(@"[Agent] onAgentIntent: %@, ext: %@", type, extInfo);
    [self openPhotoLibrary];
}

- (void)onAgentLicenseStatus:(int)status {
    NSLog(@"[Agent] onAgentLicenseStatus: %@", @(status));
    if (status != 0) {
        [self alertTitle:@"授权失败，请退出重试" andMessage:@"" andCancleBlock:^(UIAlertAction *action) {
            [self popChatViewController];
        }];
    }
}

#pragma mark - Funccall

- (void)funcallHandler:(id<BCAFuncallHandler>)handler executeFinished:(NSString *)sessionId
               message:(NSString *)message error:(NSError *)error {
    NSString *result = @"执行完成";
    
    if (error) {
        NSLog(@"onFunctionCall session: %@ fail: %@", sessionId, error);
        result = error.localizedDescription.length > 0 ? error.localizedDescription : @"执行失败";
    } else {
        NSLog(@"onFunctionCall session: %@ succ", sessionId);
        result = message.length ? message : @"执行成功";
    }
    
    [self.baiduChatAgent sendFunctionCallResult:sessionId result:result];
    
    if (error) {
        return;
    }
    
    // 按需处理，这里尝试展示交互视图
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showFuncallResultView:handler];
    });
}

- (void)funcallHandler:(id<BCAFuncallHandler>)handler sendTextToTTS:(NSString *)text {
    //[self.baiduChatAgent sendTextToTTS:text];
}

- (UIViewController *)funcallHandlerChatViewController:(id<BCAFuncallHandler>)handler {
    return self;
}

- (void)showFuncallResultView:(id<BCAFuncallHandler>)handler {
    BCAFuncallResultView *cardView = [handler funcallResultView];
    if (!cardView) {
        return;
    }
    
    // 创建数据源
    CGSize cardSize = [cardView boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58)];
    AIMsgItem *item = [[AIMsgItem alloc] initParam:YES msg:nil heigth:cardSize.height];
    item.funcallSessionId = handler.funcallItem.sessionId;
    item.funcallResultView = cardView;
    item.rowHeight = cardSize.height + LINE_SPACE;
    [_messageArr addObject:item];
    
    [self.tableView reloadData];
    
    // 滚动界面
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_messageArr.count - 1) inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (UITableViewCell *)cellForTableView:(UITableView *)tableView funcallResultMsgItem:(AIMsgItem *)item {
    NSString *identifier = item.funcallSessionId;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        
        // 头像
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"chat_left_agent_ic.png"]];
        imageView.frame = CGRectMake(W * 0.01, W * 0.05, W * 0.1, W * 0.1);
        [cell.contentView addSubview:imageView];
        
        // 结果视图
        BCAFuncallResultView *view = item.funcallResultView;
        CGSize cardSize = [view boundingRectWithSize:CGSizeMake(W * 0.6, H * 0.58)];
        view.frame = CGRectMake(W * 0.13, W * 0.07, cardSize.width, cardSize.height);
        [view layoutSubviews];
        [cell.contentView addSubview:view];
    }
    return cell;
}

- (UITableViewCell *)cellForTableView:(UITableView *)tableView uploadImageMsgItem:(AIMsgItem *)item {
    static NSString *cellId = @"image_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        
        // 头像
        UIImageView *headView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"chat_right_me_ic.png"]];
        headView.frame = CGRectMake(W * 0.89, W * 0.01, W * 0.1, W * 0.1);
        [cell.contentView addSubview:headView];
        
        // 图像上传组件
        CGFloat imageW = IMAGE_ITEM_HEIGHT * 2;
        CGRect frame = CGRectMake(W * 0.86 - imageW, W * 0.01, imageW, IMAGE_ITEM_HEIGHT);
        AIChatUploadImageView *imageView = [[AIChatUploadImageView alloc] initWithFrame:frame];
        imageView.tag = 101;
        [cell.contentView addSubview:imageView];
    }
    
    AIChatUploadImageView *imageView = [cell.contentView viewWithTag:101];
    if ([imageView isKindOfClass:[AIChatUploadImageView class]]) {
        imageView.image = item.image;
        imageView.status = item.uploadStatus;
    }
    return cell;
}

#pragma mark - RTCRemoteVideoViewDelegate

- (void)remoteVideoView:(RTCRemoteVideoView *)videoView didChangeVideoSize:(CGSize)size {
    
}

- (void)remoteVideoView:(RTCRemoteVideoView *)videoView videoRenderStuck:(NSInteger)duration {
    
}

- (void)remoteVideoView:(RTCRemoteVideoView *)videoView superResolutionEnabled:(BOOL)enabled reason:(SrEnabledReason)reason {
    
}

#pragma mark - AIChatCameraPreviewViewDelegate & Camera

- (void)openCameraPreview {
    if (!self.localPreviewView) {
        self.localPreviewView = [[AIChatCameraPreviewView alloc] initWithFrame:self.view.bounds];
        self.localPreviewView.delegate = self;
        [self.baiduChatAgent setLocalDisplay:self.localPreviewView.rtcVideoView];
    }
    
    [self.view addSubview:self.localPreviewView];
    [self.view bringSubviewToFront:self.localPreviewView];
    
    [self.baiduChatAgent startCameraPreview];
}

- (void)cameraPreviewTriggerSwitchCamera {
    [self.baiduChatAgent switchCamera];
}

- (void)cameraPreviewTriggerClose {
    [self.baiduChatAgent stopCameraPreview];
    [self.localPreviewView removeFromSuperview];
    self.localPreviewView = nil;
}

#pragma mark - UIImagePickerControllerDelegate & Image

- (void)openPhotoLibrary {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        NSLog(@"相册不可用");
        return;
    }

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = @[(NSString *)kUTTypeImage];
    picker.allowsEditing = NO;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)handleSelectedImage:(UIImage *)image url:(NSURL *)url {
    NSLog(@"handleSelectedImage，size: %@, url: %@", NSStringFromCGSize(image.size), url);
    BOOL ret = [self.baiduChatAgent uploadFile:url.path expire:60];
    AIMsgItem *item = [[AIMsgItem alloc] initParam:NO msg:nil heigth:(IMAGE_ITEM_HEIGHT + W * 0.05)];
    item.image = image;
    item.imageUrl = url;
    item.uploadStatus = UploadStatusWait;
    
    if (!ret) {
        NSLog(@"upload file fail");
        item.uploadStatus = UploadStatusFail;
    }
    [self.messageArr addObject:item];
    [self.tableView reloadData];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
    NSURL *imageUrl;
    if (@available(iOS 13.0, *)) {
        imageUrl = info[UIImagePickerControllerImageURL];
    } else {
        imageUrl = info[UIImagePickerControllerMediaURL];
    }
    if (!selectedImage) return;
    
    [self handleSelectedImage:selectedImage url:imageUrl];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
