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

#import "ViewController.h"
#import "OffcnIMSDKiOS.h"
#import "OffcnNetworkExecutor.h"
#import <oimcore/oimcoreAdapter.h>

#import <QiniuSDK.h>
#import "QNTransactionManager.h"

@interface ViewController ()<OIMCoreDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *changeEnvironmentBtn;


@property (strong, nonatomic) NSString *fromId;
@property (strong, nonatomic) NSString *toId;
@property (assign, nonatomic) OffcnSDKMsgType msg_type;
@property (strong, nonatomic) NSMutableDictionary *dataDic;

@property (strong, nonatomic) OIMCoreAdapter *adapter;

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

@implementation ViewController

#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 {
    NSString *param = @"{\"server_ip\":\"39.102.42.185\", \"server_port\":6000, \"user_id\":\"ce0819db8391f1e7258a71cc9e2c3235\",\"app_id\":\"offcn_live\", \"device_type\":\"ios\", \"token\":\"fadbce3f4929b6bdee0617fee34e32ae\"}";
    self.adapter = [OIMCoreAdapter sharedOIMCore];
    self.adapter.delegate = self;
    [self.adapter Initialize];
    [self.adapter ConnectImServerWithParam:param];
}
-(void)OnOImCoreMessageWithMessage:(const char *_Nonnull)message msgLength:(int)len{
//    "{\"type\":1,\"body\":{\"session_id\":\"a05517f0-ddec-11ea-88a4-4a5555fb6ab4\",\"msg_id\":\"d5f9b600-e28f-11ea-88a4-4a5555fb6ab4\",\"version\":1,\"send_time\":\"2020-08-20 10:49:58\",\"msg_seq\":1597891798,\"msg_from\":\"jfdfjei0343\",\"msg_scope\":1,\"msg_type\":1,\"msg_content\":{\"msg\":\"随机数298\"}}}"
}

//Z_CONN_IM_SRV_OK,连接成功
//Z_CONN_IM_SRV_FAILED,连接失败
//Z_CONN_IM_SRV_BROKEN,连接断开
//Z_DISCONN_IM_SRV_OK,手动断开成功
-(void)OnOImCoreEventWithCode:(int)code context:(const char *)context{
    if (code == 1 || code == 2) {
        [self.adapter DisConnectImServer];
    }
}

- (IBAction)disconnectAction:(UIButton *)sender {
    [self.adapter DisConnectImServer];
}
- (IBAction)sendMegAction:(UIButton *)sender {

}
 
//发送本地通知
- (IBAction)sendLocalNotiAction:(UIButton *)sender {
    
}

- (IBAction)sendMeg:(UIButton *)sender {
    //发送消息
    [OffcnNetworkExecutor requestSendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:self.msg_type msg:self.dataDic Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)noReadListAction:(UIButton *)sender {
    //获取会话未读消息列表
    [OffcnNetworkExecutor requestGetSessionUnreadMsgWithFromID:self.fromId toID:self.toId Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)readedAction:(UIButton *)sender {
    //用户信息标记已读
    [OffcnNetworkExecutor requestMarkMsgReadWithMsg_fromID:self.fromId msg_toID:self.toId Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)recentVChatAction:(UIButton *)sender {
    //获取用户最近会话记录
    [OffcnNetworkExecutor requestGetRecentSessionsWithAccid:self.fromId Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)historyMegListAction:(UIButton *)sender {
    //获取会话历史消息列表,msg_seq当前时间的时间戳
    [OffcnNetworkExecutor requestGetSessionHistoryMsgWithFromID:self.fromId toID:self.toId msg_seq:@"" Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)registeredUser:(UIButton *)sender {
    [OffcnNetworkExecutor requestRegisterDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}
- (IBAction)UnRegisteredUser:(UIButton *)sender {
    [OffcnNetworkExecutor requestUnregisterDevicesWithAccid:self.fromId device_token:[OffcnIMSDKiOS defaultService].deviceToken Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
    }];
}

- (IBAction)getImage:(UIButton *)sender {
    [self gotoImageLibrary];
}

- (IBAction)uploadFile:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    [OffcnNetworkExecutor requestUploadTokenFinished:^(BOOL success, id response, BaseResponse *baseResponse) {
        
        NSString *token = [NSString stringWithFormat:@"%@",response];
        weakSelf.QNToken = token;
        NSLog(@"七牛token---%@",token);
        NSData *imageData = UIImageJPEGRepresentation(weakSelf.pickImage, 0.5);
        [weakSelf uploadToQNWithQNToken:weakSelf.QNToken fileData:imageData];
    }];
}
-(void)uploadToQNWithQNToken:(NSString *)QNToken fileData:(NSData *)fileData{
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *uploadOption = [[QNUploadOption alloc] initWithMime:nil progressHandler:^(NSString *key, float percent) {
        NSLog(@"percent == %.2f", percent);
    }params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:fileData key:nil token:self.QNToken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSLog(@"info ===== %@", info);
        NSLog(@"key ===== %@", key);
        NSLog(@"resp ===== %@", resp);
        
        //发送消息
        NSString *dataStr = [NSString stringWithFormat:@"http://test-offcncloud-im.eoffcn.com/%@",resp[@"key"]];
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithObject:dataStr forKey:@"msg"];
        [OffcnNetworkExecutor requestSendMsgWithMsg_fromID:self.fromId msg_toID:self.toId msg_type:self.msg_type msg:dataDic Finished:^(BOOL success, id response, BaseResponse *baseResponse) {
            
        }];
    }option:uploadOption];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"demo";
    
    self.changeEnvironmentBtn.selected = [OffcnIMSDKiOS defaultService].isTest;
    
    self.toId = @"ce0819db8391f1e7258a71cc9e2c3235";
    self.fromId = @"jfdfjei0343";
    self.msg_type = OffcnSDKMsgTypeText;
    self.dataDic = [NSMutableDictionary dictionaryWithObject:@"我是一只小青龙" forKey:@"msg"];
}

#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 {
        //访问图片库错误
    }
}


//可旋转屏幕
- (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
