//
//  ViewController.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2018/7/25.
//  Copyright © 2018年 中公教育. All rights reserved.
//

#import "ViewController.h"
#import "OffcnIMSDKiOS.h"
#import "OffcnIMSocketManager.h"
#import "OffcnIMPushManager.h"
#import "AppDelegate.h"

#import "OffcnZYJ1TestDataStorageView.h"
#import "LMJDropdownMenu.h"
#import "OffcnIMSqliteTestVC.h"

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate,LMJDropdownMenuDelegate,LMJDropdownMenuDataSource>
{
    NSArray * _menu1OptionTitles;
    NSArray * _menu1TokenOptionTitles;
    NSArray * _menu2OptionTitles;
    NSArray * _nameOptionTitles;
    
    LMJDropdownMenu * menu1;
    LMJDropdownMenu * menu2;
}
@property (weak, nonatomic) IBOutlet UIButton *changeEnvironmentBtn;
@property (weak, nonatomic) IBOutlet UITextField *megTextField;
@property (weak, nonatomic) IBOutlet UITextField *sendIDTextField;
@property (weak, nonatomic) IBOutlet UITextField *sendTokenTextField;
@property (weak, nonatomic) IBOutlet UITextField *recvIDTextField;
@property (weak, nonatomic) IBOutlet UILabel *senderLab;
@property (weak, nonatomic) IBOutlet UILabel *revLab;

@property (strong, nonatomic) NSString *fromId;
@property (strong, nonatomic) NSString *toId;

@property (nonatomic, strong) UIImage *pickImage;
@property (weak, nonatomic) IBOutlet UIImageView *showImage;

@property (nonatomic, strong) NSTimer *timer;//压测

@property (nonatomic, assign)NSInteger msg_seq;//消息时序
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"demo";
    
    self.changeEnvironmentBtn.selected = [OffcnIMSDKiOS defaultService].isTest;
    
    self.sendIDTextField.text = @"704a3ebbfeb9a754ea6fd1106e4862d8";
    self.sendTokenTextField.text = @"ThXLFM/oGZPTks22QjPNnSvkJxD3aqwtLkmbsTlhm4t5p5G+RXCyx8SwRXv6GO1RVM3WGJzCxmef1N3WZ9euRt5tvKs1XLLYIDGe4PIEBqPrvxEReyZv0jSd+XWxE0EF";
    self.senderLab.text = @"发送人:李梦";
    
    self.recvIDTextField.text = @"2a956beb4a21a4b98c42384f3534ee08";
    self.revLab.text = @"接收人:李永裕";
    
    self.sendIDTextField.hidden = YES;
    self.sendTokenTextField.hidden = YES;
    self.recvIDTextField.hidden = YES;
    
    self.fromId = self.sendIDTextField.text;
    self.toId = self.recvIDTextField.text;
    
    if(!self.timer) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loop) userInfo:nil repeats:YES];
    }
    
    [self.timer setFireDate:[NSDate distantFuture]];
    
    [self addMenu];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(appWillTerminate)
                          name:UIApplicationWillTerminateNotification
                        object:nil];
}
-(void)addMenu{
    
        _menu1OptionTitles = @[@"发送人704a3ebbfeb9a754ea6fd1106e4862d8",@"发送人2a956beb4a21a4b98c42384f3534ee08",@"发送人3f09513d254682a25ba0413097099a92",@"发送人1f890295d95b2dea102483373e6a7e3a",@"发送人20a35e2e10996d0e15489297b319fd51"];
        _menu1TokenOptionTitles = @[@"ThXLFM/oGZPTks22QjPNnSvkJxD3aqwtLkmbsTlhm4t5p5G+RXCyx8SwRXv6GO1RVM3WGJzCxmef1N3WZ9euRt5tvKs1XLLYIDGe4PIEBqPrvxEReyZv0jSd+XWxE0EF",@"3csdJWLhE6K9FrQK8Gy7wzroe/icewdVchEm1NrRn148R6m6AwGrBc2FT8dgqybCvc5oVN//Qks=@ip6c.cn.rongnav.com;ip6c.cn.rongcfg.com",@"TlXegSSUiiU6GN6ZhUwGt2LwpiKByYg1GRe0X/Havz1IrPNTu/ait4PWl1zOxiBTG8ju8QEOGl0VnSlJXWAEubMWiD8zcXNM6dN4XRDjafwvs+RgyZXb7z0O4oHauZzyRK/U8pOAkX0=",@"+SSkwImtTQbKvMZu3Je2t1hKcd6MtgL4/0zwzBsh3kNjvs87f03ch82FT8dgqybCHDhIkChdv84=@ip6c.cn.rongnav.com;ip6c.cn.rongcfg.com",@"/L3TZiY2oEoBvEZtn+sHWmLwpiKByYg1GRe0X/Havz1IrPNTu/ait0hda/h0OnT7mlkYUdtmheRmQnKb3HDdzPD8twTxIYaaQWdGktQhAkve0ak/MKLE++3OwGhBJl/nRK/U8pOAkX0="];
        _nameOptionTitles = @[@"李梦",@"李永裕",@"杨瑞娟",@"任志玲",@"殷倩"];
        _menu2OptionTitles = @[@"接收人704a3ebbfeb9a754ea6fd1106e4862d8",@"接收人2a956beb4a21a4b98c42384f3534ee08",@"接收人3f09513d254682a25ba0413097099a92",@"接收人1f890295d95b2dea102483373e6a7e3a",@"接收人20a35e2e10996d0e15489297b319fd51"];
        
        // ----------------------- menu1 ---------------------------
        menu1 = [[LMJDropdownMenu alloc] init];
        menu1.frame = self.sendIDTextField.frame;
        menu1.dataSource = self;
        menu1.delegate   = self;
        
        menu1.layer.borderColor  = [UIColor whiteColor].CGColor;
        menu1.layer.borderWidth  = 1;
        menu1.layer.cornerRadius = 3;
        
        menu1.title           = @"发送人704a3ebbfeb9a754ea6fd1106e4862d8";
        menu1.titleBgColor    = [UIColor colorWithRed:64/255.f green:151/255.f blue:255/255.f alpha:1];
        menu1.titleFont       = [UIFont boldSystemFontOfSize:12];
        menu1.titleColor      = [UIColor whiteColor];
        menu1.titleAlignment  = NSTextAlignmentLeft;
        menu1.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
        
        menu1.optionBgColor       = [UIColor colorWithRed:64/255.f green:151/255.f blue:255/255.f alpha:0.5];
        menu1.optionFont          = [UIFont systemFontOfSize:12];
        menu1.optionTextColor     = [UIColor blackColor];
        menu1.optionTextAlignment = NSTextAlignmentLeft;
        menu1.optionNumberOfLines = 0;
        menu1.optionLineColor     = [UIColor whiteColor];
        menu1.optionIconSize      = CGSizeMake(15, 15);
        [self.view addSubview:menu1];
        
        // ----------------------- menu2 ---------------------------
        menu2 = [[LMJDropdownMenu alloc] init];
        menu2.frame = self.sendTokenTextField.frame;
        menu2.dataSource = self;
        menu2.delegate   = self;

        menu2.layer.borderColor  = [UIColor whiteColor].CGColor;
        menu2.layer.borderWidth  = 1;
        menu2.layer.cornerRadius = 3;

        menu2.title           = @"接收人2a956beb4a21a4b98c42384f3534ee08";
        menu2.titleBgColor    = menu1.titleBgColor;
        menu2.titleFont       = [UIFont boldSystemFontOfSize:12];
        menu2.titleColor      = [UIColor whiteColor];
        menu2.titleAlignment  = NSTextAlignmentLeft;
        menu2.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);

//        menu2.rotateIcon      = [UIImage imageNamed:@"arrowIcon3"];
//        menu2.rotateIconSize  = CGSizeMake(15, 15);

        menu2.optionBgColor       = menu1.optionBgColor;
        menu2.optionFont          = [UIFont systemFontOfSize:12];
        menu2.optionTextColor     = [UIColor blackColor];
        menu2.optionTextAlignment = NSTextAlignmentLeft;
        menu2.optionNumberOfLines = 0;
        menu2.optionLineColor     = [UIColor whiteColor];
        menu2.optionIconSize      = CGSizeMake(15, 15);
        [self.view addSubview:menu2];
}

//压力测试
-(void)loop{
    NSString *randomStr = [NSString stringWithFormat:@"ZYJ1%d",arc4random_uniform(1000000)];
    [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypeText text:randomStr filePath:nil ext:@"123" extIndex:@"1" Finished:^(NSString *extIndex,BOOL success, OffcnIMBodyModel *sendMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSLog(@"发送消息成功,消息：%@",randomStr);
        }else{
            NSLog(@"发送消息失败,消息：%@,errorMessage:%@",randomStr,errorMessage);
        }
    } ProgressPercent:^(NSString *extIndex, NSString *filePath, float percent) {
                       
        NSLog(@"extIndex == %@,filePath == %@,percent == %.2f", extIndex,filePath,percent);
    }];
}
#pragma mark - 切换环境
- (IBAction)clickChangeEnvironmentBtnAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    //中公直播使用测试环境设置为YES，正式环境设置为NO或者去掉这个配置
    [OffcnIMSDKiOS defaultService].isTest = sender.isSelected;

    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:[OffcnIMSDKiOS defaultService].isTest] forKey:kOffcnIMSDKiOS_changeEnvironment];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - 点我退出键盘
- (IBAction)clickExitKeyboardAction:(UIButton *)sender {
    [self.view endEditing:YES];
}
- (IBAction)connectAction:(UIButton *)sender {
    //建立连接
    [[OffcnIMSocketManager defaultService] connectIMServerWithAccount_id:self.fromId token:self.sendTokenTextField.text];
    
    //收到消息回调
    __weak typeof(self) weakSelf = self;
    [OffcnIMSocketManager defaultService].connectReceiveMessage = ^(OffcnIMModel *IMModel) {
        NSLog(@"收到消息---%@，时间：%@",IMModel.body.msg.msg,IMModel.body.send_time);
        self.msg_seq = IMModel.body.msg_seq;
        
        NSString *msg = @"";
        if (IMModel.body.msg_type == 1) {
            msg = [msg stringByAppendingString:IMModel.body.msg.msg?IMModel.body.msg.msg:@"nil"];
        }else{
            msg = [msg stringByAppendingString:IMModel.body.msg.url?IMModel.body.msg.url:@"nil"];
        }
        
        msg = [NSString stringWithFormat:@"%@,未读数%ld,拓展内容:%@",msg,(long)IMModel.body.unread_number,IMModel.body.ext];
        if ([IMModel.body.msg_from isEqualToString:[OffcnIMSocketManager defaultService].msg_fromId]) {
            [weakSelf tipMessageWithTitle:@"通道发送消息" message:msg];
        }else{
            [weakSelf tipMessageWithTitle:@"收到消息" message:msg];
        }
    };
    
    //收到连接状态回调
    [OffcnIMSocketManager defaultService].connectStatus = ^(OffcnIMConnectStatus status, NSString * _Nonnull errorMessage) {
        NSLog(@"收到连接状态---%@,code:%lu,%@",errorMessage,(unsigned long)status,[weakSelf getNowSSSTimeTimestamp]);
        if (status == OffcnIMConnectStatusDisConnectOK) {
            errorMessage = @"主动断开连接成功";
        }else if (status == OffcnIMConnectStatusFail){
//            errorMessage = @"连接失败，请重新连接";
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连接失败，请重新连接" message:errorMessage delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
            });
        }else if (status == OffcnIMConnectStatusBreak){
//            errorMessage = @"连接断开，请重新连接";
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"连接失败，请重新连接" message:errorMessage delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
            });
        }else if (status == OffcnIMConnectStatusKickout){
            errorMessage = @"被挤掉";
        }else if (status == OffcnIMConnectStatusReconnect_success || status == OffcnIMConnectStatusSuccess){
            //标记消息已读接口传最后一条消息时序，再获取未读消息接口，这样保持断开重连后消息的连续性
            errorMessage = @"连接成功";
        }
        
        [weakSelf tipMessageWithTitle:@"收到连接状态" message:errorMessage];
    };
}
//获取当前时间戳(以毫秒为单位)
-(NSString *)getNowSSSTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"]; //

    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
//    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    NSString *timeSp = [formatter stringFromDate:datenow];
    return timeSp;
}

- (IBAction)disconnectAction:(UIButton *)sender {
    //断开连接
    [[OffcnIMSocketManager defaultService] disConnectIMServerForever];
}

//退出当前会话
- (IBAction)sendMegAction:(UIButton *)sender {
    [[OffcnIMSocketManager defaultService] joinSessionWithSession_fromId:@"" session_toId:@"" callBack:^(NSInteger unread_number, NSString * _Nonnull fromUser, NSString * _Nonnull toUser) {
       
    }];
}
 
//进入当前会话
- (IBAction)sendLocalNotiAction:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSocketManager defaultService] joinSessionWithSession_fromId:self.fromId session_toId:self.toId callBack:^(NSInteger unread_number, NSString * _Nonnull fromUser, NSString * _Nonnull toUser) {
        
        [weakSelf tipMessageWithTitle:@"进入当前会话" message:@"未读数清0"];
    }];
}

- (IBAction)sendMeg:(UIButton *)sender {
    //发送消息
    if (!self.megTextField.text.length) {
            [self tipMessageWithTitle:@"请输入消息再发送" message:@""];
            return;
        }
        __weak typeof(self) weakSelf = self;
        [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypeText text:self.megTextField.text filePath:nil ext:@"123" extIndex:@"1" Finished:^(NSString *extIndex,BOOL success, OffcnIMBodyModel *sendMsgModel, NSString *errorMessage) {
            
            if (success) {
                NSString *msg = @"";
                if (sendMsgModel.msg_type == 1) {
                    msg = [msg stringByAppendingString:sendMsgModel.msg.msg?sendMsgModel.msg.msg:@"nil"];
                }else{
                    msg = [msg stringByAppendingString:sendMsgModel.msg.url?sendMsgModel.msg.url:@"nil"];
                }
                
                NSString *allmsg = [NSString stringWithFormat:@"%@,拓展内容:%@",msg,sendMsgModel.ext];
                [weakSelf tipMessageWithTitle:@"接口发送消息" message:allmsg];
    //            [weakSelf tipMessageWithTitle:@"发送消息成功" message:@""];
            }else{
                [weakSelf tipMessageWithTitle:@"发送消息失败" message:errorMessage];
            }
        } ProgressPercent:^(NSString *extIndex, NSString *filePath, float percent) {
                           
            NSLog(@"extIndex == %@,filePath == %@,percent == %.2f", extIndex,filePath,percent);
        }];
}
- (IBAction)noReadListAction:(UIButton *)sender {
    //获取会话未读消息列表
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] getSessionUnreadMsgWithFromID:self.fromId toID:self.toId Finished:^(BOOL success, OffcnIMUnreadMsgModel *unreadMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSString *content = @"";
            for (int i=0; i<unreadMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = unreadMsgModel.msg_list[i];
                
                NSString *sender = [NSString stringWithFormat:@"发送人ID:%@",model.msg_from];
                NSString *rever = [NSString stringWithFormat:@"接收人ID:%@",model.msg_to];
                NSString *time = [NSString stringWithFormat:@"时间:%@",model.send_time];
                NSString *msg = @"";
                if (model.msg_type == 1) {
                    //文本消息
                    msg = [msg stringByAppendingString:model.msg.msg?model.msg.msg:@"nil"];
                }else{
                    //非文本消息
                    msg = [msg stringByAppendingString:model.msg.url?model.msg.url:@"nil"];
                }
                
                NSString *allmsg = [NSString stringWithFormat:@"%@,%@,%@,消息:%@,拓展内容:%@",sender,rever,time,msg,model.ext];
                
                content = [content stringByAppendingString:allmsg];
                content = [content stringByAppendingString:@"\r\n"];
                content = [content stringByAppendingString:@"\r\n"];
            }
            
            OffcnZYJ1TestDataStorageView *storageView = [[OffcnZYJ1TestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = content;
            [storageView showView];
        }else{
            [weakSelf tipMessageWithTitle:@"获取会话未读消息列表失败" message:errorMessage];
        }
    }];
}
- (IBAction)readedAction:(UIButton *)sender {
    //用户信息标记已读
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] markMsgReadWithMsg_fromID:self.fromId msg_toID:self.toId msg_seq:self.msg_seq Finished:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf tipMessageWithTitle:@"标记已读成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"标记已读失败" message:errorMessage];
        }
    }];
}
- (IBAction)recentVChatAction:(UIButton *)sender {
    //获取用户最近会话记录
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] getRecentSessionsWithAccid:self.fromId Finished:^(BOOL success, OffcnIMHistoryMsgModel *historyMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSString *content = @"";
            for (int i=0; i<historyMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = historyMsgModel.msg_list[i];
                
                NSString *sender = [NSString stringWithFormat:@"发送人ID:%@",model.msg_from];
                NSString *rever = [NSString stringWithFormat:@"接收人ID:%@",model.msg_to];
                NSString *time = [NSString stringWithFormat:@"时间:%@",model.send_time];
                NSString *msg = @"";
                if (model.msg_type == 1) {
                    //文本消息
                    msg = [msg stringByAppendingString:model.msg.msg?model.msg.msg:@"nil"];
                }else{
                    //非文本消息
                    msg = [msg stringByAppendingString:model.msg.url?model.msg.url:@"nil"];
                }
                
                NSString *allmsg = [NSString stringWithFormat:@"%@,%@,%@,消息:%@,未读数:%ld,拓展内容:%@",sender,rever,time,msg,(long)model.unread_number,model.ext];
                
                content = [content stringByAppendingString:allmsg];
                content = [content stringByAppendingString:@"\r\n"];
                content = [content stringByAppendingString:@"\r\n"];
            }

            OffcnZYJ1TestDataStorageView *storageView = [[OffcnZYJ1TestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = content;
            [storageView showView];
        }else{
            [weakSelf tipMessageWithTitle:@"获取用户最近会话记录失败" message:errorMessage];
        }
    }];
}
- (IBAction)historyMegListAction:(UIButton *)sender {
    //获取会话历史消息列表
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] getSessionHistoryMsgWithFromID:self.fromId toID:self.toId msg_seq:@"" Finished:^(BOOL success, OffcnIMHistoryMsgModel *historyMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSString *content = @"";
            for (int i=0; i<historyMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = historyMsgModel.msg_list[i];
                
                NSString *sender = [NSString stringWithFormat:@"发送人ID:%@",model.msg_from];
                NSString *rever = [NSString stringWithFormat:@"接收人ID:%@",model.msg_to];
                NSString *time = [NSString stringWithFormat:@"时间:%@",model.send_time];
                NSString *msg = @"";
                if (model.msg_type == 1) {
                    //文本消息
                    msg = [msg stringByAppendingString:model.msg.msg?model.msg.msg:@"nil"];
                }else{
                    //非文本消息
                    msg = [msg stringByAppendingString:model.msg.url?model.msg.url:@"nil"];
                }
                
                NSString *allmsg = [NSString stringWithFormat:@"%@,%@,%@,消息:%@,拓展内容:%@",sender,rever,time,msg,model.ext];
                
                content = [content stringByAppendingString:allmsg];
                content = [content stringByAppendingString:@"\r\n"];
                content = [content stringByAppendingString:@"\r\n"];
            }
            
            OffcnZYJ1TestDataStorageView *storageView = [[OffcnZYJ1TestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = content;
            [storageView showView];
        }else{
            [weakSelf tipMessageWithTitle:@"获取会话历史消息列表失败" message:errorMessage];
        }
    }];
}
- (IBAction)registeredUser:(UIButton *)sender {
    [OffcnIMPushManager registerOffcnUserNotification];
    
    __weak typeof(self) weakSelf = self;
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.deviceTokenCallback = ^{
        NSString *oldFromId = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_fromid];
        NSString *oldToken = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_token];
        if (oldFromId) {
            [[OffcnIMSDKiOS defaultService] unregisterDevicesWithAccid:oldFromId device_token:oldToken Finished:^(BOOL success, id response, NSString *errorMessage) {
                if (success) {
                    [weakSelf tipMessageWithTitle:@"注销推送成功" message:@""];
                    //注册推送
                    [[OffcnIMSDKiOS defaultService] registerDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, NSString *errorMessage) {
                        if (success) {
                            [[NSUserDefaults standardUserDefaults] setValue:self.fromId forKey:kOffcnIMSDKiOS_fromid];
                            [[NSUserDefaults standardUserDefaults] setValue:[OffcnIMSDKiOS defaultService].deviceToken forKey:kOffcnIMSDKiOS_token];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                            
                            [weakSelf tipMessageWithTitle:@"注册推送成功" message:@""];
                        }else{
                            [weakSelf tipMessageWithTitle:@"注册推送失败" message:errorMessage];
                        }
                    }];
                }else{
                    [weakSelf tipMessageWithTitle:@"注销推送失败" message:errorMessage];
                }
            }];
        }else{
            //注册推送
            [[OffcnIMSDKiOS defaultService] registerDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, NSString *errorMessage) {
                if (success) {
                    [[NSUserDefaults standardUserDefaults] setValue:self.fromId forKey:kOffcnIMSDKiOS_fromid];
                    [[NSUserDefaults standardUserDefaults] setValue:[OffcnIMSDKiOS defaultService].deviceToken forKey:kOffcnIMSDKiOS_token];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [weakSelf tipMessageWithTitle:@"注册推送成功" message:@""];
                }else{
                    [weakSelf tipMessageWithTitle:@"注册推送失败" message:errorMessage];
                }
            }];
        }
    };
}
- (IBAction)UnRegisteredUser:(UIButton *)sender {
    //注销推送
    [OffcnIMPushManager unregisterForOffcnUserRemoteNotifications];
    __weak typeof(self) weakSelf = self;
    
    NSString *oldFromId = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_fromid];
    NSString *oldToken = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_token];
    [[OffcnIMSDKiOS defaultService] unregisterDevicesWithAccid:oldFromId device_token:oldToken Finished:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf tipMessageWithTitle:@"注销推送成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"注销推送失败" message:errorMessage];
        }
    }];
}

-(void)appWillTerminate{
//    [self UnRegisteredUser:nil];
}
- (IBAction)getImage:(UIButton *)sender {
    //获取相册图片
    [self gotoImageLibrary];
}

- (IBAction)uploadImage:(UIButton *)sender {
    //上传
    __weak typeof(self) weakSelf = self;
       NSString *filePath = [self getImagePath:self.pickImage];
       [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypePicture text:nil filePath:filePath ext:@"123" extIndex:@"1" Finished:^(NSString *extIndex,BOOL success, OffcnIMBodyModel *sendMsgModel, NSString *errorMessage) {
    
           if (success) {
               [weakSelf tipMessageWithTitle:@"上传成功" message:@""];
           }else{
               [weakSelf tipMessageWithTitle:@"上传失败" message:errorMessage];
           }
       } ProgressPercent:^(NSString *extIndex, NSString *filePath, float percent) {
                          
           NSLog(@"extIndex == %@,filePath == %@,percent == %.2f", extIndex,filePath,percent);
       }];
}
- (IBAction)uploadFile:(UIButton *)sender {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
     NSString *filePath = [path stringByAppendingPathComponent:@"ZYJ1FMDBIMChat.db"];
     __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypeFile text:nil filePath:filePath ext:@"123" extIndex:@"1" Finished:^(NSString *extIndex,BOOL success, OffcnIMBodyModel *sendMsgModel, NSString *errorMessage) {

        if (success) {
            [weakSelf tipMessageWithTitle:@"上传成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"上传失败" message:errorMessage];
        }
    } ProgressPercent:^(NSString *extIndex, NSString *filePath, float percent) {
                       
        NSLog(@"extIndex == %@,filePath == %@,percent == %.2f", extIndex,filePath,percent);
    }];
}
- (IBAction)pressureTest:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    if (sender.isSelected) {
        [self.timer setFireDate:[NSDate distantPast]];
    }else{
        [self.timer setFireDate:[NSDate distantFuture]];
    }
}

//查看数据库
- (IBAction)lookDatabase:(UIButton *)sender {
    OffcnIMSqliteTestVC *SqliteTestVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"OffcnIMSqliteTestVC"];
    SqliteTestVC.fromId = self.fromId;
    SqliteTestVC.toId = self.toId;
    [self.navigationController pushViewController:SqliteTestVC animated:YES];
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    self.pickImage = info[UIImagePickerControllerOriginalImage];
    self.showImage.image = self.pickImage;
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

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

- (void)gotoImageLibrary{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        //访问相册错误
        NSLog(@"访问相册错误");
        [self tipMessageWithTitle:@"访问相册错误" message:@""];
    }
}
//照片获取本地路径转换
-(NSString *)getImagePath:(UIImage *)Image{
    NSString *filePath = nil;
    NSData *data = nil;
    if (UIImagePNGRepresentation(Image) == nil) {
        data = UIImageJPEGRepresentation(Image, 1.0);
    } else {
        data = UIImagePNGRepresentation(Image);
    }

    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];

    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *ImagePath = [[NSString alloc] initWithFormat:@"/theFirstImage.png"];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];

    //得到选择后沙盒中图片的完整路径
    filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
}

-(void)tipMessageWithTitle:(NSString *)title message:(NSString *)message{
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.view endEditing:YES];
        
        NSString *msg = [NSString stringWithFormat:@"%@:%@",title,message];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    });
}

//可旋转屏幕
- (BOOL)shouldAutorotate {
    return NO;
}
/** 返回直接支持的方向 */
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LMJDropdownMenu DataSource
- (NSUInteger)numberOfOptionsInDropdownMenu:(LMJDropdownMenu *)menu{
    if (menu == menu1) {
        return _menu1OptionTitles.count;
    } else if (menu == menu2) {
        return _menu2OptionTitles.count;
    } else {
        return 0;
    }
}
- (CGFloat)dropdownMenu:(LMJDropdownMenu *)menu heightForOptionAtIndex:(NSUInteger)index{
    if (menu == menu1) {
        return 40;
    } else if (menu == menu2) {
        return 40;
    } else {
        return 0;
    }
}
- (NSString *)dropdownMenu:(LMJDropdownMenu *)menu titleForOptionAtIndex:(NSUInteger)index{
    if (menu == menu1) {
        return _menu1OptionTitles[index];
    } else if (menu == menu2) {
        return _menu2OptionTitles[index];
    } else {
        return @"";
    }
}
#pragma mark - LMJDropdownMenu Delegate
- (void)dropdownMenu:(LMJDropdownMenu *)menu didSelectOptionAtIndex:(NSUInteger)index optionTitle:(NSString *)title{
    if (menu == menu1) {
        self.sendIDTextField.text = _menu1OptionTitles[index];
        self.sendTokenTextField.text = _menu1TokenOptionTitles[index];
        self.senderLab.text = [NSString stringWithFormat:@"发送人:%@",_nameOptionTitles[index]];
//        NSLog(@"你选择了(you selected)：menu1，index: %ld - title: %@", index, title);
    } else if (menu == menu2) {
        self.recvIDTextField.text = _menu2OptionTitles[index];
        self.revLab.text = [NSString stringWithFormat:@"接收人:%@",_nameOptionTitles[index]];
//        NSLog(@"你选择了(you selected)：menu2，index: %ld - title: %@", index, title);
    }
    
    
    self.fromId = [self.sendIDTextField.text stringByReplacingOccurrencesOfString:@"发送人" withString:@""];
    self.toId = [self.recvIDTextField.text stringByReplacingOccurrencesOfString:@"接收人" withString:@""];
    
    menu2.hidden = NO;
}
- (void)dropdownMenuWillShow:(LMJDropdownMenu *)menu{
    if (menu == menu1) {
        menu2.hidden = YES;
    } else if (menu == menu2) {
        
    }
}
- (void)dropdownMenuDidHidden:(LMJDropdownMenu *)menu{
    if (menu == menu1) {
        menu2.hidden = NO;
    } else if (menu == menu2) {
        
    }
}

- (void)dealloc {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
@end
