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

#import "OffcnNetworkExecutor.h"
#import "DataSafe.h"
#import "SDConfigrationNetwork.h"
#import "ZYJMJExtension.h"
#import "OffcnIMZYJFMDBHandler.h"
#import "OffcnIMSocketManager.h"

@implementation OffcnNetworkExecutor
+ (void)cancelAllOperations{
    [[OffcnBaseNetworking sharedInstance] cancelAllOperations];
}

//sendAsynchronousRequest
+ (void)requesImgJsonWithUrlStr:(NSString *)urlStr Finished:(void(^)(BOOL success,id response,NSString *message))finished{

    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]  completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        if (!connectionError) {
            if (!data) {
                data = [NSData data];
            }
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            finished(YES,dic,nil);
        }else{
            finished(NO,nil,connectionError.localizedDescription);
        }
    }];
}

//发送消息
+ (void)requestSendMsgWithMsg_fromID:(NSString *)msg_fromID msg_toID:(NSString *)msg_toID msg_type:(NSInteger)msg_type tid:(NSString *)tid msg:(NSMutableDictionary *)msgDic Finished:(void(^)(BOOL success,OffcnIMSendMsgModel *sendMsgModel,BaseResponse *baseResponse))finished{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:msg_fromID forKey:@"msg_from"];
    [dic setObjectOnSafe:msg_toID forKey:@"msg_to"];
    [dic setObjectOnSafe:[NSNumber numberWithInteger:msg_type] forKey:@"msg_type"];
    [dic setObjectOnSafe:msgDic forKey:@"msg"];
    [dic setObjectOnSafe:tid forKey:@"tid"];

    [OffcnBaseNetworking postToURL:sendMsgURL bodyParams:dic finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {
            
            OffcnIMSendMsgModel *SendMsgModel = [OffcnIMSendMsgModel mj_ZYJobjectWithKeyValues:baseResponse.responseObject];
            
            OffcnIMMsgModel *MsgModel = [[OffcnIMMsgModel alloc] init];
            OffcnIMBodyModel *BodyModel = [[OffcnIMBodyModel alloc] init];
            BodyModel.msg_from = msg_fromID;
            BodyModel.msg_to = msg_toID;
            BodyModel.msg_id = SendMsgModel.msg_id;
            BodyModel.send_time = SendMsgModel.send_time;
            BodyModel.session_id = SendMsgModel.session_id;
            BodyModel.tid = SendMsgModel.tid;
            BodyModel.msg_seq = [[[tid componentsSeparatedByString:@"__"] lastObject] integerValue];
            BodyModel.isSentSuccess = 1;
            BodyModel.msg_type = msg_type;
            if (msg_type == 1) {
                MsgModel.msg = [msgDic objectForKeyOnSafe:@"msg"];
            }else{
                MsgModel.dur = [[msgDic objectForKeyOnSafe:@"dur"] longLongValue];
                MsgModel.name = [msgDic objectForKeyOnSafe:@"name"];
                MsgModel.md5 = [msgDic objectForKeyOnSafe:@"md5"];
                MsgModel.url = [msgDic objectForKeyOnSafe:@"url"];
                MsgModel.thumb_url = [msgDic objectForKeyOnSafe:@"thumb_url"];
                MsgModel.cover_url = [msgDic objectForKeyOnSafe:@"cover_url"];
                MsgModel.ext = [msgDic objectForKeyOnSafe:@"ext"];
                MsgModel.w = [[msgDic objectForKeyOnSafe:@"w"] longLongValue];
                MsgModel.h = [[msgDic objectForKeyOnSafe:@"h"] longLongValue];
                MsgModel.size = [[msgDic objectForKeyOnSafe:@"size"] longLongValue];
            }
            BodyModel.msg = MsgModel;
            
            [[OffcnIMZYJFMDBHandler sharedInstance] updateChatInfoIsSendStatusToFMDBWithModel:BodyModel isSuccess:nil];
            [[OffcnIMZYJFMDBHandler sharedInstance] chatlistCacheInfo:BodyModel callback:nil];
            
            finished(YES,SendMsgModel,nil);
        }else{

            finished(NO,nil,baseResponse);
        }
    }];
}

//用户信息标记已读
+ (void)requestMarkMsgReadWithMsg_fromID:(NSString *)msg_fromID msg_toID:(NSString *)msg_toID msg_seq:(NSInteger)msg_seq Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:msg_fromID forKey:@"msg_from"];
    [dic setObjectOnSafe:msg_toID forKey:@"msg_to"];
    [dic setObjectOnSafe:[NSNumber numberWithInteger:msg_seq] forKey:@"msg_seq"];

    [OffcnBaseNetworking postToURL:markMsgReadURL bodyParams:dic finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {

            OffcnIMBodyModel *BodyModel = [[OffcnIMBodyModel alloc] init];
            BodyModel.msg_from = msg_fromID;
            BodyModel.msg_to = msg_toID;
            BodyModel.msg_seq = msg_seq;
            BodyModel.isRead = 1;
            [[OffcnIMZYJFMDBHandler sharedInstance] updateChatInfoIsRead:BodyModel callBack:^(BOOL isSuccess) {
                
            }];
            
            finished(YES,baseResponse.responseObject,nil);
        }else{

            finished(NO,nil,baseResponse);
        }
    }];
}


//{
//    "msg_list" =     (
//                {
//            msg =             {
//                msg = "\U6211\U662f\U4e00\U53ea\U5c0f\U9752\U9f99";
//            };
//            "msg_from" = ce0819db8391f1e7258a71cc9e2c3235;
//            "msg_id" = "13e266f3-e139-11ea-88a4-4a5555fb6ab4";
//            "msg_seq" = 1597744585;
//            "msg_to" = jfdfjei0343;
//            "msg_type" = 1;
//            "send_time" = "2020-08-18 17:56:25";
//        },
//    );
//}

//获取会话未读消息列表
+ (void)requestGetSessionUnreadMsgWithFromID:(NSString *)fromID toID:(NSString *)toID Finished:(void(^)(BOOL success,OffcnIMUnreadMsgModel *unreadMsgModel,BaseResponse *baseResponse))finished{

    NSString *url = [NSString stringWithFormat:@"%@?from=%@&to=%@",getSessionUnreadMsgURL,fromID,toID];
    [OffcnBaseNetworking getFromURL:url params:nil finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {
            
            OffcnIMUnreadMsgModel *unreadMsgModel = [OffcnIMUnreadMsgModel mj_ZYJobjectWithKeyValues:baseResponse.responseObject];
            
            for (int i=0; i<unreadMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = unreadMsgModel.msg_list[i];
                if ([model.msg_from isEqualToString:[OffcnIMSocketManager defaultService].msg_fromId]) {
                    model.bymyself = 1;
                }else{
                    model.bymyself = 0;
                }
                model.isSentSuccess = 1;
                model.isRead = 0;
                
                [[OffcnIMZYJFMDBHandler sharedInstance] updateChatInfoCacheInfo:model callback:^(BOOL isSuccess) {
                    
                }];
            }
            
            finished(YES,unreadMsgModel,nil);
        }else{
            finished(NO,nil,baseResponse);
        }
    }];
}


//{
//    sessions =     (
//                {
//            "last_msg" =             {
//                "msg_content" =                 {
//                    msg = 1233;
//                };
//                "msg_from" = ce0819db8391f1e7258a71cc9e2c3235;
//                "msg_to" = ceb7383519c5b6a1c8579553f01ad9c4;
//                "msg_type" = 1;
//                "send_time" = "2020-09-09 13:30:41";
//            };
//            "session_id" = 37f7344c5b7f94592882951e280d61676386ff86;
//            to = ceb7383519c5b6a1c8579553f01ad9c4;
//            type = 1;
//        }
//    );
//}
//获取用户最近会话记录
+ (void)requestGetRecentSessionsWithAccid:(NSString *)accid Finished:(void(^)(BOOL success,OffcnIMRecentMsgModel *recentMsgModel,BaseResponse *baseResponse))finished{

    NSString *url = [NSString stringWithFormat:@"%@?accid=%@",getRecentSessionsURL,accid];
    [OffcnBaseNetworking getFromURL:url params:nil finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {
            //接口缺少返回msg_from，然后解析存数据库
            OffcnIMRecentMsgModel *recentMsgModel = [OffcnIMRecentMsgModel mj_ZYJobjectWithKeyValues:baseResponse.responseObject];
            
            for (int i=0; i<recentMsgModel.sessions.count; i++) {
                OffcnIMSessionModel *SessionModel = recentMsgModel.sessions[i];
                
                OffcnIMMsgModel *MsgModel = [[OffcnIMMsgModel alloc] init];
                OffcnIMBodyModel *BodyModel = [[OffcnIMBodyModel alloc] init];
                BodyModel.msg_from = SessionModel.last_msg.msg_from;
                BodyModel.msg_to = SessionModel.last_msg.msg_to;
                BodyModel.session_id = SessionModel.session_id;
                BodyModel.msg_type = SessionModel.last_msg.msg_type;
                BodyModel.send_time = SessionModel.last_msg.send_time;
                BodyModel.tid = @"";
                BodyModel.msg_id = @"";
                BodyModel.msg_seq = 0;
                BodyModel.isSentSuccess = 1;
                if ([BodyModel.msg_from isEqualToString:[OffcnIMSocketManager defaultService].msg_fromId]) {
                    BodyModel.bymyself = 1;
                }else{
                    BodyModel.bymyself = 0;
                }
                BodyModel.isRead = 1;
                if (BodyModel.msg_type == 1) {
                    MsgModel.msg = SessionModel.last_msg.msg_content.msg;
                }else{
                    MsgModel.dur = SessionModel.last_msg.msg_content.dur;
                    MsgModel.name = SessionModel.last_msg.msg_content.name;
                    MsgModel.md5 = SessionModel.last_msg.msg_content.md5;
                    MsgModel.url = SessionModel.last_msg.msg_content.url;
                    MsgModel.thumb_url = SessionModel.last_msg.msg_content.thumb_url;
                    MsgModel.cover_url = SessionModel.last_msg.msg_content.cover_url;
                    MsgModel.ext = SessionModel.last_msg.msg_content.ext;
                    MsgModel.w = SessionModel.last_msg.msg_content.w;
                    MsgModel.h = SessionModel.last_msg.msg_content.h;
                    MsgModel.size = SessionModel.last_msg.msg_content.size;
                }
                BodyModel.msg = MsgModel;
                [[OffcnIMZYJFMDBHandler sharedInstance] updateChatlistCacheInfo:BodyModel callback:^(BOOL isSuccess) {
                    
                }];
            }
            
            finished(YES,recentMsgModel,nil);
        }else{
            finished(NO,nil,baseResponse);
        }
    }];
}


//{
//    "msg_list" =     (
//                {
//            msg =             {
//                msg = "\U4f60\U597d";
//            };
//            "msg_from" = jfdfjei0343;
//            "msg_id" = "a0c76912-ddec-11ea-88a4-4a5555fb6ab4";
//            "msg_seq" = 1597381897;
//            "msg_to" = ce0819db8391f1e7258a71cc9e2c3235;
//            "msg_type" = 1;
//            "send_time" = "2020-08-14 13:11:36";
//        },
//    );
//}

//获取会话历史消息列表
+ (void)requestGetSessionHistoryMsgWithFromID:(NSString *)fromID toID:(NSString *)toID msg_seq:(NSString *)msg_seq Finished:(void(^)(BOOL success,OffcnIMHistoryMsgModel *historyMsgModel,BaseResponse *baseResponse))finished{

    NSString *url = [NSString stringWithFormat:@"%@?from=%@&to=%@&msg_seq=%@",getSessionHistoryMsgURL,fromID,toID,msg_seq];
    [OffcnBaseNetworking getFromURL:url params:nil finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {
            
            OffcnIMHistoryMsgModel *historyMsgModel = [OffcnIMHistoryMsgModel mj_ZYJobjectWithKeyValues:baseResponse.responseObject];
            
            for (int i=0; i<historyMsgModel.msg_list.count; i++) {
                OffcnIMBodyModel *model = historyMsgModel.msg_list[i];
                if ([model.msg_from isEqualToString:[OffcnIMSocketManager defaultService].msg_fromId]) {
                    model.bymyself = 1;
                }else{
                    model.bymyself = 0;
                }
                model.isSentSuccess = 1;
                model.isRead = 1;
                
                [[OffcnIMZYJFMDBHandler sharedInstance] updateChatInfoCacheInfo:model callback:^(BOOL isSuccess) {
                    
                }];
            }
            
            finished(YES,historyMsgModel,nil);
        }else{
            finished(NO,nil,baseResponse);
        }
    }];
}

//获取七牛Token
+ (void)requestUploadTokenFinished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{

    [OffcnBaseNetworking getFromURL:uploadToken params:nil finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {
            finished(YES,baseResponse.responseObject,nil);
        }else{
            finished(NO,nil,baseResponse);
        }
    }];
}

//注册用户设备
+ (void)requestRegisterDevicesWithAccid:(NSString *)accid device_token:(NSString *)device_token Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:accid forKey:@"accid"];
    [dic setObjectOnSafe:@"ios" forKey:@"device"];
    [dic setObjectOnSafe:device_token forKey:@"device_token"];

    [OffcnBaseNetworking postToURL:registerDevices bodyParams:dic finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {

            finished(YES,baseResponse.responseObject,nil);
        }else{

            finished(NO,nil,baseResponse);
        }
    }];
}

//注销用户设备
+ (void)requestUnregisterDevicesWithAccid:(NSString *)accid device_token:(NSString *)device_token Finished:(void(^)(BOOL success,id response,BaseResponse *baseResponse))finished{

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObjectOnSafe:accid forKey:@"accid"];
    [dic setObjectOnSafe:@"ios" forKey:@"device"];
    [dic setObjectOnSafe:device_token forKey:@"device_token"];

    [OffcnBaseNetworking postToURL:unregisterDevices bodyParams:dic finished:^(BaseResponse *baseResponse) {
        if (baseResponse.isSuccess) {

            finished(YES,baseResponse.responseObject,nil);
        }else{

            finished(NO,nil,baseResponse);
        }
    }];
}

@end
