//
//  ACNetwork.m
//  AntsContract
//
//  Created by Ray on 12/26/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "ACNetwork.h"
#import "AppDelegate.h"

#import "RAUtils.h"
#import "ZipArchive.h"

#import "config.h"
#import "AESCrypt.h"




@implementation ACNetwork

+(NSMutableDictionary*) prepare_addtional_params:(NSMutableDictionary* ) params
{
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(appDelegate.user!=nil)
        [params setValue:[AESCrypt AES128Encrypt:appDelegate.user key:@"usai2010"] forKey:@"user"];
    if(appDelegate.password!=nil)
        [params setValue:[AESCrypt AES128Encrypt:appDelegate.password key:@"usai2010"] forKey:@"password"];
    

    
    [params setValue:appDelegate.build forKey:@"app_ver"];
    
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* short_version =[infoDict objectForKey:@"CFBundleShortVersionString"];
    [params setValue:short_version forKey:@"app_short_ver"];
    
    UIDevice * dev = [UIDevice currentDevice];
    NSUUID* uuid =dev.identifierForVendor;
#if TARGET_IPHONE_SIMULATOR//模拟器
    [params setValue:@"simulator_uuid" forKey:@"deviceid"];
#elif TARGET_OS_IPHONE//真机
    [params setValue:uuid.UUIDString forKey:@"deviceid"];
#endif
    
    return params;
}

+(NSData*)get_json : (NSString*) url parameters:(NSMutableDictionary *) params //delegate:(id < NSURLConnectionDelegate >)delegate
{
    
    
    
    
//    NSString* e=[AESCrypt AES128Encrypt:@"密码学中的高级加密标准（Advanced Encryption Standard，AES），又称 高级加密标准Rijndael加密法，是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES，已经被多方分析且广为全世界所使用。经过五年的甄选流程，高级加密标准由美国国家标准与技术研究院 （NIST）于2001年11月26日发布于FIPS PUB 197，并在2002年5月26日成为有效的标准。2006年，高级加密标准已然成为对称密钥加密中最流行的算法之一。 " key:@"usai2010"];
//    DebugLog(e);
//    NSString* d=[AESCrypt decrypt:@"VzB4+lENfbzWX7ggHh2Os1P69l5YBzKmM51yqA37AfoKgPY8bJgdK8M4WvF+wDyOsLWP\/o8H5+bHMivQp1u8wM2QV7SYzgzPwV85QKtYWIzEgLe9T0HO69EdutWz7k1rdAT\/mftsRin0Hy5SHk7txTZT\/zPH5X+FQiExCTFm5Zus39HYvp+VxCX4+kYeymn8B63AUd3mRQyscUvDjfgU2olKR\/TP8PV3g+VQMZxpKfol3P1iOtz3XQlHZV0pM6SAf+SwT0sPfrdn6CZFfNQlrKA9QjMrnBdMeSCquSIWXnmLv6okzvnlJnT0SjvJuUeqNdBC5EZ0ACnhI0MrXVZEsq1EuM9al7oPzvU5EZbjZpmx+fSFIkMzTT8bYClTnG1bsL1MCcU4pSODDorUj8zalA==" password:@"usai2010"];
    params = [self prepare_addtional_params:params];
    
    return [super get_json:url parameters:params err_recorder:URL_ERR_LOG result_handler:^NSMutableDictionary *(NSMutableDictionary *jsobj) {
        int result=[[jsobj valueForKey:@"result"] intValue];
//        UIApplication * app = [UIApplication sharedApplication];
//        AppDelegate *appDelegate = (AppDelegate *)[app delegate];

        switch (result) {
            case 0:
                [jsobj setValue:MSG_USERAUTH_ERROR forKey:@"err_msg"];
                break;
            case 1:
                [jsobj setValue:MSG_ERROR forKey:@"err_msg"];
                break;
            case 2:
                [jsobj setValue:MSG_SUCCESS forKey:@"err_msg"];
                break;
            case 8:
                [jsobj setValue:[jsobj valueForKey:@"msg"] forKey:@"err_msg"];
                break;
            case 9:
                [jsobj setValue:[jsobj valueForKey:@"msg"] forKey:@"err_msg"];
                break;
            case 99:
                [jsobj setValue:MSG_TIMEOUT forKey:@"err_msg"];
                break;
            default:
                [jsobj setValue:MSG_ERROR forKey:@"err_msg"];
                break;
        }
        
        
//        if([appDelegate.build intValue]< [[jsobj valueForKey:@"min_ver"]intValue])
//        {
//            [jsobj setValue:@"9" forKey:@"result"];
//            [jsobj setValue:MSG_VER_LOW forKey:@"err_msg"];
//        }
        return jsobj;
    } decrypt_handler:^NSMutableDictionary *(NSMutableDictionary *jsobj) {
        
        NSString* base64str = jsobj[@"str"];
        NSString* decryptstr=[AESCrypt AES128Decrypt:base64str key:@"usai2010"];
        jsobj=[[RAUtils string2dict:decryptstr] mutableCopy];
        return jsobj;
    }];
    
    
    /*


     
     */
    return nil;
}
+(NSDictionary*)new_document
{
    
    
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(appDelegate.user!=nil)
        [params setValue:appDelegate.user forKey:@"user"];
    
    
    if(appDelegate.password!=nil)
        [params setValue:appDelegate.password forKey:@"password"];
    params[@"_operate"]=@"doc_id";
    
    if(![self IsNetworkAvailable])
    {
        DebugLog(@"NET ERR");
        
        return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
        //        return nil;
    }
    NSData* json=[self get_json:URL_NEW_DOCUMENT parameters:params];
    //if(json==nil)
    
    
    if(json==nil)
        return nil;
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    int result = [[jsobj valueForKey:@"result"] intValue];
    

    return jsobj;
}
+(NSDictionary*)logout
{
    
    
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(appDelegate.user!=nil)
        [params setValue:appDelegate.user forKey:@"user"];
    
    
    if(appDelegate.password!=nil)
        [params setValue:appDelegate.password forKey:@"password"];
    params[@"_operate"]=@"logout_zip";
    
    if(![self IsNetworkAvailable])
    {
        DebugLog(@"NET ERR");
        
        return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
        //        return nil;
    }
    NSData* json=[self get_json:URL_LOGOUT parameters:params];
    //if(json==nil)
    
    
    if(json==nil)
        return nil;
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    int result = [[jsobj valueForKey:@"result"] intValue];
    
    if (result==2)
    {
        [appDelegate Logout];
  
    }
    return jsobj;
}
+(int)Authorize : (NSString*) user password:(NSString*) password{
    
    //    if(![ApexMobileNetwork IsHostAvailable:URL_UPDATE_AUTH])
    //        return RESULT_NET_ERROR;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    long ver =[defaults integerForKey:[NSString stringWithFormat:@"%@_Auth_InfoVer",user]];
    
    
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    if(appDelegate.duid !=nil)
//        [params setValue:appDelegate.duid forKey:@"udid"];
//    [params setValue:@"handset_login" forKey:@"action"];
    //    [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
    
    
    
    
    [params setValue:[AESCrypt AES128Encrypt:user  key:@"usai2010"] forKey:@"user"];
    [params setValue:[AESCrypt AES128Encrypt:password  key:@"usai2010"] forKey:@"password"];
    [params setValue:[NSString stringWithFormat:@"%ld",ver]  forKey:@"auth_ver"];
        [params setValue:@"login"  forKey:@"_operate"];
    

//#ifdef TEST
//    [params setValue:@"true" forKey:@"is_debug"];
//#else
//    [params setValue:@"false" forKey:@"is_debug"];
//#endif
    
    NSData* json= nil;
//    if(appDelegate.offline_mode)
//    {
//        json= [OLDataProvider offline_login:params] ;
//        
//    }
//    else
    
        if(![self IsNetworkAvailable])
            return RESULT_NET_NOTAVAILABLE;
        json =[self get_json:URL_UPDATE_AUTH parameters:params];
        
    
    
    if(json==nil)
        return RESULT_NET_ERROR;
    
    
    int ret = [self parse_authinfo:json user:user password:password];
    DebugLog(@"parse_authinfo return %d ",ret);
    
    
    return ret;
    
    
}
+(int)parse_authinfo : (NSData *) json user:(NSString*) user password:(NSString*) password
{
    DebugLog(@"parse_authinfo");
    NSError *error=nil;
    
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        int result = [[jsobj valueForKey:@"result"] intValue];
        
        if (result<0)
            return result;
        if(result!=AP_USER_AUTH&& result!=9)
        {
            
            
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            [appDelegate Logout];
            if(result==8)
            {
                return RESULT_LOGIN_DEVICE;
            }
            return RESULT_FALSE;
            
        }
//        NSDictionary* objheader = [jsobj objectForKey:@"header"];
//        
//        NSString* required_ver=[jsobj objectForKey:@"min_ver"] ;
//        user=[objheader objectForKey:@"username"] ;
//        DebugLog(@"required_ver=%@ ",required_ver);
//        //        NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
//        //        NSString* versionNum =[infoDict valueForKey:@"CFBundleVersion"];
//        //        versionNum = [NSString stringWithFormat:@"A%@",versionNum];
//        int ibadge = [[objheader valueForKey:@"badge"] intValue];
//        
//        //        if([ibadge isEqual:[NSNull null]])
//        //            strbadge=@"0";
//        //        if(ibadge==nil)
//        //            ibadge=@"0";
//        //        if([strbadge isEqualToString:@"null"])
//        //            strbadge=@"0";
//        app.applicationIconBadgeNumber = ibadge;//[strbadge intValue];
//        
//        //  BOOL bigger = [appDelegate.build compare:required_ver] ;
//        if([appDelegate.build intValue]<[required_ver intValue])
//            return RESULT_VER_LOW;
//        //        appDelegate.sessionid = [objheader valueForKey:@"sessionid"];
//        appDelegate.user = user;
//        appDelegate.password = password;
////        appDelegate.user_type = [[objheader valueForKey:@"user_type"] intValue];
////        appDelegate.user_icon =[objheader valueForKey:@"user_img"] ;
//        appDelegate.bLogin = true;
        
        
        [appDelegate Login:user pwd:password];
        
        
//        
//        if(appDelegate.user_type==USER_ROLE_CUSTOMER)
//        {
//            appDelegate.customerInfo = [[objheader objectForKeyedSubscript:@"customerInfo"] mutableCopy];
//            appDelegate.contact_id = [objheader valueForKey:@"contact_id"];
//            //            appDelegate.order_code =[objheader valueForKey:@"orderCode"];
//            //            appDelegate.order_status =[[objheader valueForKey:@"orderStatus"] intValue];
//            //            [appDelegate SetSo:[objheader valueForKey:@"soId"]];
//        }
//        NSString* mode =[jsobj valueForKey:@"mode"] ;
//        [appDelegate SetMode:mode];
//        
//        
//        appDelegate.cart_count = [[objheader valueForKey:@"cart_count"] intValue];
//        appDelegate.wish_count =[[objheader valueForKey:@"wish_count"] intValue];
//        appDelegate.port_count =[[objheader valueForKey:@"portfolio_count"] intValue];
//        
//        [appDelegate update_count_mark];
//        
//        
//        
//        appDelegate.can_show_price =[[objheader valueForKey:@"can_show_price"] boolValue];
//        appDelegate.can_see_price =[[objheader valueForKey:@"can_see_price"] boolValue];
//        appDelegate.can_create_portfolio =[[objheader valueForKey:@"can_create_portfolio"] boolValue];
//        appDelegate.can_create_order =[[objheader valueForKey:@"can_create_order"] boolValue];
//        
//        appDelegate.can_cancel_order =[[objheader valueForKey:@"can_cancel_order"] boolValue];
//        appDelegate.can_set_cart_price =[[objheader valueForKey:@"can_set_cart_price"] boolValue];
//        appDelegate.can_delete_order =[[objheader valueForKey:@"can_delete_order"] boolValue];
//        appDelegate.can_update_contact_info =[[objheader valueForKey:@"can_update_contact_info"] boolValue];
//        appDelegate.can_submit_order =[[objheader valueForKey:@"can_submit_order"] boolValue];
//        appDelegate.can_set_tearsheet_price =[[objheader valueForKey:@"can_set_tearsheet_price"] boolValue];
//        
//        appDelegate.save_order_logout =[[objheader valueForKey:@"save_order_logout"] boolValue];
//        appDelegate.submit_order_logout =[[objheader valueForKey:@"submit_order_logout"] boolValue];
//        
//        appDelegate.alert_sold_in_quantities = [[objheader valueForKey:@"alert_sold_in_quantities"] boolValue];
//        
//        
//        
//        appDelegate.ipad_perm =[objheader valueForKey:@"ipad_perm"] ;
//        
//        NSString* strfilter = [objheader valueForKey:@"statusFilter"] ;
//        
//        
//        
//        appDelegate.OrderFilter= [[RAUtils string2dict:strfilter] mutableCopy];
//        
//        
//        [appDelegate set_main_button_panel];
//        
//        if(appDelegate.user_type==USER_ROLE_CUSTOMER) {
//            
//            // shop order status filter
//            NSString *shopOrderStatusFilterStr = [objheader valueForKey:@"shopOrderFilter"] ;
//            [Singleton sharedInstance].shop_order_status_filter = [[RAUtils string2dict:shopOrderStatusFilterStr] mutableCopy];
//            
//            // specialInstruction
//            [Singleton sharedInstance].specialInstruction = [objheader valueForKey:@"specialInstruction"];
//            
//            //-价格类型
//            [Singleton sharedInstance].npd_shop_price_type = [[objheader valueForKey:@"price_type"] integerValue];
//            
//            // 权限
//            [Singleton sharedInstance].permissions_price_setting = [[objheader valueForKey:@"can_set_price_formula"] boolValue];
//            [Singleton sharedInstance].permissions_edit_order = [[objheader valueForKey:@"can_place_order"] boolValue];
//            
//            [Singleton sharedInstance].permissions_submit_order = [[objheader valueForKey:@"can_submit_order"] boolValue];
//            
//            [Singleton sharedInstance].permissions_merge_order = [[objheader valueForKey:@"can_merge_order"] boolValue];
//            
//            [Singleton sharedInstance].deliveryString = [objheader valueForKey:@"delivery_price"];
//            [[Singleton sharedInstance] resetGlobalLock];
//            [Singleton sharedInstance].customer_can_see_sales_Order = [[objheader valueForKey:@"can_see_salesorder"] boolValue];
//        }
        
        //        DebugLog(@"sessionid=%@ ",appDelegate.sessionid);
        //        if ([[objheader valueForKey:@"update"] boolValue]==false)
        //        {
        //            // no update on the server;
        //            return RESULT_TRUE;
        //        }
        //        int Auth_InfoVer = [[objheader valueForKey:@"ver"] intValue];
        //        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        //        [defaults removeObjectForKey:[NSString stringWithFormat:@"%@_Auth_InfoVer",user]];
        //       [defaults setInteger:Auth_InfoVer forKey:[NSString stringWithFormat:@"%@_Auth_InfoVer",user]];
        //        [defaults synchronize];
        //
        //        NSDictionary* objfuncs = [jsobj objectForKey:@"functions"];
        //        NSArray* keys= [objfuncs allKeys];
        
        
        /*
         
         db.setTransactionSuccessful();
         db.endTransaction();
         */
        return RESULT_TRUE;
        
    }
    //    NSDictionary *weatherInfo = [jsobj objectForKey:@"weatherinfo"];
    //    txtView.text = [NSString stringWithFormat:@"今天是 %@  %@  %@  的天气状况是：%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
    //      DebugLog(@"weatherInfo字典里面的内容为--》%@", weatherDic );
    
    
    
    return RESULT_USERAUTH_ERROR;
}
+(NSDictionary*)err_log:(NSString*) up_params result:(NSString*)result module:(NSString*) module code:(int) code//device:(NSString*) device
{
//    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
//    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    if(appDelegate.user!=nil)
//        [params setValue:appDelegate.user forKey:@"user"];
//    
//    [params setValue:up_params forKey:@"upparam"];
//    
//    [params setValue:[NSNumber numberWithInt:code ] forKey:@"code"];
//    
//    [params setValue:result forKey:@"result"];
//    [params setValue:module forKey:@"interfac"];
//    
//    [params setValue:[RAUtils base64en:[RAUtils dict2string: [RAUtils device_info]]] forKey:@"device"];
//    
//    
//    //     [params setValue:module forKey:@"module"];
//    
//    //  [[UIDevice currentDevice]  name];
//    
//    //    if(appDelegate.offline_mode)
//    //    {
//    //        return [OLDataProvider offline_notimpl];
//    //    }
//    if(![self IsNetworkAvailable])
//        return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
//    
//    NSData* json=[self get_json:URL_ERR_LOG parameters:params];
//    if(json==nil)
//        return nil;
//    NSError *error=nil;
//    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
//    return jsobj;
    NSMutableDictionary* jsobj = [@{@"result":@"2"} mutableCopy];
    return jsobj;
}

+(NSString *) prepareUploadFile:(NSString*) file json:(NSMutableDictionary*)json
{
    NSString* serial= [[NSUUID UUID] UUIDString];
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachefolder = [paths objectAtIndex:0];
    
    NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
    upfolder = [upfolder stringByAppendingPathComponent:serial];
    
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL bdir=YES;
    if(!  [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
    {
        
        NSError *error = nil;
        bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
        
        if(!bsuccess)
            DebugLog(@"Create UPLOAD folder failed");
        
    }
    
//    NSMutableDictionary* ret = [[NSMutableDictionary alloc] init];
//    ret[@"contact"]=[self prepareContact:serial];
//    ret[@"wishlist"]=[self prepareWishlist:serial];
//    ret[@"order"]=[self prepareOrder:serial soid:arr_order];
//    ret[@"portfolio"] = [self preparePortfolio:serial];
//    ret[@"view_portfolio"] = [self preparePDF:serial];
    
    NSString* str= [RAUtils dict2string:json];
    
    
    
    
    
    NSString * jsonpath= [upfolder stringByAppendingPathComponent:@"json.json"];
    
    NSString * zippath= [upfolder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip",serial]];
    
    
    NSError *error=nil;
    
    [str writeToFile:jsonpath atomically:true encoding:NSUTF8StringEncoding error:&error];
    
   // NSArray* arr_files=[RAUtils allFilesAtPath:upfolder];
    
    ZipArchive* zip = [[ZipArchive alloc] init];
    
    
    BOOL result = [zip CreateZipFile2:zippath Password:nil];
    

        result = [zip addFileToZip:file newname:[file lastPathComponent]];
    result = [zip addFileToZip:jsonpath newname:[jsonpath lastPathComponent]];

    
    if( ![zip CloseZipFile2] )
    {
        zippath = @"";
    }
    
    
    

    
    return zippath;
}

+(NSDictionary*)request_DocList:(NSMutableDictionary*) params
{
//    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    if(appDelegate.user!=nil)
//        [params setValue:appDelegate.user forKey:@"user"];
//    
//    
//    if(appDelegate.password!=nil)
//        [params setValue:appDelegate.password forKey:@"password"];
    params[@"_operate"]=@"listIpad";
    
    if(![self IsNetworkAvailable])
    {
        DebugLog(@"NET ERR");
        
        return [RAUtils error_json:RESULT_NET_NOTAVAILABLE err_msg:nil];
        //        return nil;
    }
    NSData* json=[self get_json:URL_REQUEST_DOC parameters:params];
    //if(json==nil)
    
    
    if(json==nil)
        return nil;
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];

    return jsobj;
}
@end
