//
//  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 "OffcnZYJTestDataStorageView.h"
#import "AppDelegate+OffcnIMPush.h"

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@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 (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;//压测
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"demo";
    
    self.changeEnvironmentBtn.selected = [OffcnIMSDKiOS defaultService].isTest;
    
    self.sendIDTextField.text = @"ce0819db8391f1e7258a71cc9e2c3235";
    self.sendTokenTextField.text = @"fadbce3f4929b6bdee0617fee34e32ae";
    self.recvIDTextField.text = @"ceb7383519c5b6a1c8579553f01ad9c4";
    
    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]];
}
-(void)loop{
    NSString *randomStr = [NSString stringWithFormat:@"zyj%d",arc4random_uniform(1000000)];
    [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypeText text:randomStr filePath:nil Finished:^(BOOL success, OffcnIMSendMsgModel *sendMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSLog(@"发送消息成功,消息：%@",randomStr);
        }else{
            NSLog(@"发送消息失败,消息：%@,errorMessage:%@",randomStr,errorMessage);
        }
    } ProgressPercent:^(NSString *key, float percent) {
                       
        NSLog(@"key == %@,percent == %.2f", key,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);
        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"];
        }
        
        [AppDelegate manualSendLocalNotificationWithModel:IMModel];
//        [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 == OffcnIMConnectStatusSuccess){
            errorMessage = @"连接成功";
        }else if (status == OffcnIMConnectStatusFail){
            errorMessage = @"连接失败，请重新连接";
        }else if (status == OffcnIMConnectStatusBreak){
            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] disConnectIMServer];
}
- (IBAction)sendMegAction:(UIButton *)sender {
     //暂无
    [self tipMessageWithTitle:@"暂无此功能" message:@""];
}
 
//发送本地通知
- (IBAction)sendLocalNotiAction:(UIButton *)sender {
    //暂无
    [self tipMessageWithTitle:@"暂无此功能" message:@""];
}

- (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 Finished:^(BOOL success, OffcnIMSendMsgModel *sendMsgModel, NSString *errorMessage) {
        
        if (success) {
            [weakSelf tipMessageWithTitle:@"发送消息成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"发送消息失败" message:errorMessage];
        }
    } ProgressPercent:^(NSString *key, float percent) {
                       
        NSLog(@"key == %@,percent == %.2f", key,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 *msg = @"";
            for (int i=0; i<unreadMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = unreadMsgModel.msg_list[i];
                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"];
                }
                
                msg = [msg stringByAppendingString:@"\r\n"];
                msg = [msg stringByAppendingString:@"\r\n"];
            }
            
            OffcnZYJTestDataStorageView *storageView = [[OffcnZYJTestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = msg;
            [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:1599222612718 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, OffcnIMRecentMsgModel *recentMsgModel, NSString *errorMessage) {
        
        if (success) {
            NSString *msg = @"";
            for (int i=0; i<recentMsgModel.sessions.count; i++) {
                OffcnIMSessionModel *model = recentMsgModel.sessions[i];
                
                if (model.last_msg.msg_type == 1) {
                    msg = [msg stringByAppendingString:model.last_msg.msg_content.msg?model.last_msg.msg_content.msg:@"nil"];
                }else{
                    msg = [msg stringByAppendingString:model.last_msg.msg_content.url?model.last_msg.msg_content.url:@"nil"];
                }
                
                msg = [msg stringByAppendingString:@"\r\n"];
                msg = [msg stringByAppendingString:@"\r\n"];
            }
            
            OffcnZYJTestDataStorageView *storageView = [[OffcnZYJTestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = msg;
            [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 *msg = @"";
            for (int i=0; i<historyMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = historyMsgModel.msg_list[i];
                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"];
                }
                
                msg = [msg stringByAppendingString:@"\r\n"];
                msg = [msg stringByAppendingString:@"\r\n"];
            }
            
            OffcnZYJTestDataStorageView *storageView = [[OffcnZYJTestDataStorageView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-20)];
            storageView.msg = msg;
            [storageView showView];
        }else{
            [weakSelf tipMessageWithTitle:@"获取会话历史消息列表失败" message:errorMessage];
        }
    }];
}
- (IBAction)registeredUser:(UIButton *)sender {
    //注册用户设备
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] registerDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf tipMessageWithTitle:@"注册用户设备成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"注册用户设备失败" message:errorMessage];
        }
    }];
}
- (IBAction)UnRegisteredUser:(UIButton *)sender {
    //注销用户设备
    __weak typeof(self) weakSelf = self;
    [[OffcnIMSDKiOS defaultService] unregisterDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf tipMessageWithTitle:@"注销用户设备成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"注销用户设备失败" message:errorMessage];
        }
    }];
}

- (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 Finished:^(BOOL success, OffcnIMSendMsgModel *sendMsgModel, NSString *errorMessage) {
 
        if (success) {
            [weakSelf tipMessageWithTitle:@"上传成功" message:@""];
        }else{
            [weakSelf tipMessageWithTitle:@"上传失败" message:errorMessage];
        }
    } ProgressPercent:^(NSString *key, float percent) {
                          
        NSLog(@"key == %@,percent == %.2f", key,percent);
    }];
}
- (IBAction)uploadFile:(UIButton *)sender {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"ZYJFMDBIMChat.db"];
    __weak typeof(self) weakSelf = self;
   [[OffcnIMSDKiOS defaultService] sendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:OffcnSDKMsgTypeFile text:nil filePath:filePath Finished:^(BOOL success, OffcnIMSendMsgModel *sendMsgModel, NSString *errorMessage) {

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


#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];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message 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.
}
@end
