//
//  ApexMobileNetwork.m
//  Apex Mobile
//
//  Created by Ray on 14-2-28.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//




#import "ApexMobileNetwork.h"









@implementation ApexMobileNetwork
+(int) ChangePassword : (NSString*) newpass user:(NSString*) user oldpass:(NSString*) oldpass
{
    
    if(![ApexMobileNetwork IsNetworkAvailable])
        return RESULT_NET_NOTAVAILABLE;
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params setValue:user forKey:@"user"];
    [params setValue:oldpass forKey:@"oldpass"];
    [params setValue:newpass forKey:@"newpass"];
    [params setValue:@"Change Password" forKey:@"module_name"];
    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    NSData* json=[ApexMobileNetwork get_json:URL_RETRIEVE_PASS parameters:params];
    
    
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return RESULT_NET_ERROR;
    }
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result== AP_SESSION_EXPIRED)
        {
            [self Authorize:appDelegate.user password:appDelegate.password];
            json=[ApexMobileNetwork get_json:URL_RETRIEVE_PASS parameters:params];
            if (json==nil)
            {
                DebugLog(@"json is wrong");
                return RESULT_NET_ERROR;
            }
            jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
            result = [[jsobj valueForKey:@"result"] intValue];
            
        }
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            return RESULT_FALSE;
            
        }
        return RESULT_TRUE;
        
    }
    return RESULT_NET_ERROR;
    
    
}
+(int) RetrievePassword : (NSString*) user  email:(NSString*) email
{
    
    if(![ApexMobileNetwork IsNetworkAvailable])
        return RESULT_NET_NOTAVAILABLE;
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params setValue:user forKey:@"user"];
    [params setValue:email forKey:@"email"];
    [params setValue:@"Retrieve Password" forKey:@"module_name"];
    [params setValue:@"handset_search" forKey:@"action"];
    NSData* json=[ApexMobileNetwork get_json:URL_RETRIEVE_PASS parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return RESULT_NET_ERROR;
    }
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            return RESULT_FALSE;
            
        }
        return RESULT_TRUE;
        
    }
    return RESULT_NET_ERROR;
    
    
}
+(int)parse_authinfo : (NSData *) json user:(NSString*) user password:(NSString*) password
{
    DebugLog(@"parse_authinfo");
    NSError *error=nil;
    
    sqlite3 *db =[ApexMobileDB get_db];
    
    
    
    
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        
        UIApplication * app = [UIApplication sharedApplication];
        ApexMobileAppDelegate *appDelegate = [app delegate];
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            [appDelegate Logout];
            return RESULT_FALSE;
            
        }
        NSDictionary* objheader = [jsobj objectForKey:@"header"];
        
        NSString* required_ver=[objheader objectForKey:@"client_ver"] ;
        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 = [versionNum compare:required_ver] ;
        if(!bigger)
            return RESULT_VER_LOW;
        appDelegate.sessionid = [objheader valueForKey:@"sessionid"];
        appDelegate.user = user;
        appDelegate.password = password;
        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];
        
        
        
        [ApexMobileDB execSql: [NSString stringWithFormat: @"update fields_info set abandon = 1 where user ='%@'",user] db:db];
        [ApexMobileDB execSql: [NSString stringWithFormat: @"update actions_info set abandon = 1 where user ='%@'",user] db:db];
        char* sql = "insert into fields_info(name,aname,field_type,function_name,behavior,priority,show,user) values(?,?,?,?,?,?,?,?)";
        char* sql1 = "insert into actions_info(name,function_name,user,priority) values(?,?,?,?)";
        
        sqlite3_stmt *stmt;
        sqlite3_stmt *stmt1;
        sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
        sqlite3_prepare_v2(db, sql1, -1, &stmt1, nil);
        
        // db.beginTransaction();
        for(int i=0;i<keys.count;i++)
        {
            NSString* func_name = keys[i];
            NSDictionary *objfun = [objfuncs objectForKey:func_name];
            int behavior, priority = 999;
            int show =1;
            NSDictionary *objbehavior = [objfun objectForKey:@"search"];
            NSArray* keysbehavior= [objbehavior allKeys];
            behavior = BEHAVIOR_SEARCH;
            for(int j=0;j<keysbehavior.count;j++)
            {
                NSString* field = keysbehavior[j];
                NSDictionary* field_info = [objbehavior objectForKey:field];
                NSString* field_name =[field_info valueForKey:@"name"] ;
                NSString* field_type = [field_info valueForKey:@"type"] ;
                NSString* alias_name = [field_info valueForKey:@"alias"] ;
                priority = [[field_info valueForKey:@"priority"] intValue];
                if(priority==999)
                    show=0;
                else
                    show=1;
                int id = [ApexMobileDB get_recordid:db table:@"fields_info" where:[NSString stringWithFormat:@"name='%@' and behavior=%d and function_name='%@' and user='%@'",field_name,behavior,func_name,user]];
                if(id>=0)
                    [ApexMobileDB execSql:[NSString stringWithFormat:@"update fields_info set abandon = 0 where _id=%d",id] db:db];
                else
                {
                    
                    sqlite3_bind_text(stmt, 1, [field_name UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt, 2, [alias_name UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt, 3, [field_type UTF8String], -1, NULL);
                    
                    sqlite3_bind_text(stmt, 4, [func_name UTF8String], -1, NULL);
                    
                    sqlite3_bind_int(stmt, 5, behavior);
                    sqlite3_bind_int(stmt, 6, priority);
                    sqlite3_bind_int(stmt, 7, show);
                    sqlite3_bind_text(stmt, 8, [user UTF8String], -1, NULL);
                    
                    
                    if (sqlite3_step(stmt) != SQLITE_DONE)
                    {
                        fprintf(stderr, "Error: insert search failed, error infomation: %s\n", sqlite3_errmsg(db));
                    }
                    sqlite3_reset(stmt);
                    
                }
                
                
            }
            
            objbehavior = [objfun objectForKey:@"result"];
            NSArray* keysresult= [objbehavior allKeys];
            behavior = BEHAVIOR_RESULT;
            for(int j=0;j<keysresult.count;j++)
            {
                NSString* field = keysresult[j];
                NSDictionary* field_info = [objbehavior objectForKey:field];
                NSString* field_name =[field_info valueForKey:@"name"] ;
                NSString* field_type = [field_info valueForKey:@"type"] ;
                NSString* alias_name = [field_info valueForKey:@"alias"] ;
                priority = [[field_info valueForKey:@"priority"] intValue];
                if(priority==999)
                    show=0;
                else
                    show=1;
                int id = [ApexMobileDB get_recordid:db table:@"fields_info" where:[NSString stringWithFormat:@"name='%@' and behavior=%d and function_name='%@' and user='%@'",field_name,behavior,func_name,user]];
                if(id>=0)
                    [ApexMobileDB execSql:[NSString stringWithFormat:@"update fields_info set abandon = 0 where _id=%d",id] db:db];
                else
                {
                    sqlite3_bind_text(stmt, 1, [field_name UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt, 2, [alias_name UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt, 3, [field_type UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt, 4, [func_name UTF8String], -1, NULL);
                    sqlite3_bind_int(stmt, 5, behavior);
                    sqlite3_bind_int(stmt, 6, priority);
                    sqlite3_bind_int(stmt, 7, show);
                    sqlite3_bind_text(stmt, 8, [user UTF8String], -1, NULL);
                    
                    if (sqlite3_step(stmt) != SQLITE_DONE)
                    {
                        fprintf(stderr, "Error: insert result failed, error infomation: %s\n", sqlite3_errmsg(db));
                    }
                    sqlite3_reset(stmt);
                    
                }
            }
            objbehavior = [objfun objectForKey:@"actions"];
            NSArray* keysactions= [objbehavior allKeys];
            behavior = BEHAVIOR_SEARCH;
            for(int j=0;j<keysactions.count;j++)
            {
                NSString* actionname = keysactions[j];
                int action_priority = [[objbehavior valueForKey:actionname] intValue];
                int id = [ApexMobileDB get_recordid:db table:@"actions_info" where:[NSString stringWithFormat:@"name='%@' and function_name='%@' and user='%@'",actionname,func_name,user]];
                if(id>=0)
                    [ApexMobileDB execSql:[NSString stringWithFormat:@"update actions_info set abandon = 0 , priority=%d where _id=%d",action_priority,id] db:db];
                else
                {
                    
                    sqlite3_bind_text(stmt1, 1, [actionname UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt1, 2, [func_name UTF8String], -1, NULL);
                    sqlite3_bind_text(stmt1, 3, [user UTF8String], -1, NULL);
                    sqlite3_bind_int(stmt1, 4, action_priority);
                    
                    if (sqlite3_step(stmt1) != SQLITE_DONE)
                    {
                        fprintf(stderr, "Error: insert action_info failed, error infomation: %s\n", sqlite3_errmsg(db));
                    }
                    sqlite3_reset(stmt1);
                }
            }
        }
        [ApexMobileDB execSql:@"delete from fields_info where abandon = 1" db:db];
        [ApexMobileDB execSql:@"delete from actions_info where abandon = 1" db:db];
        
        sqlite3_finalize(stmt);
        sqlite3_finalize(stmt1);
        sqlite3_close(db);
        /*
         
         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;
}
+(DetailContent*) get_detailcontent: (NSMutableDictionary *) params
{
    DebugLog(@"get_detailcontent");
    DetailContent * detailContent = [[DetailContent alloc] init];
    NSMutableArray* segments = [[NSMutableArray alloc] init];
    detailContent.segments = segments;
    if(![ApexMobileNetwork IsNetworkAvailable])
    {
        detailContent.result_code = RESULT_NET_NOTAVAILABLE;
        return detailContent;
    }
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    //    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    NSData* json=[ApexMobileNetwork get_json:URL_REQUEST_RECORDS parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        detailContent.result_code = RESULT_NET_ERROR;
        return detailContent;
    }
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result== AP_SESSION_EXPIRED)
        {
            [self Authorize:appDelegate.user password:appDelegate.password];
            json=[ApexMobileNetwork get_json:URL_REQUEST_RECORDS parameters:params];
            if (json==nil)
            {
                DebugLog(@"json is wrong");
                detailContent.result_code = RESULT_NET_ERROR;
                return detailContent;
            }
            jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
            result = [[jsobj valueForKey:@"result"] intValue];
            
        }
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            detailContent.result_code = result;
            return detailContent;
            
        }
        
        int count =[[jsobj valueForKey:@"count"] intValue];
        detailContent.result_code = RESULT_TRUE;
        if(count==0)
        {
            
            return detailContent;
        }
        
        for(int i=0;i<count;i++)
        {
            
            NSDictionary* segment = [jsobj objectForKey:[NSString stringWithFormat:@"group%d",i]];
            [segments addObject:segment];
            
            /*
             JSONObject groupobj = jsonObj.getJSONObject("group" + i);
             View v = inflater.inflate(R.layout.group_tag, null);
             v.setOnClickListener(this);
             
             TextView tvgroup = (TextView) v.findViewById(R.id.tv_group);
             String group_name = groupobj.getString("_name");
             tvgroup.setText(group_name);
             v.setId(commonUtil.generateViewId());
             ll_root.addView(v);
             String grouptype = groupobj.getString("_type");
             
             */
        }
        
        //   NSDictionary* objrecords = [jsobj objectForKey:@"records"];
        
        
        
        return detailContent;
        
    }
    return nil;
    
}
+(PageData*) get_pagedata: (NSMutableDictionary *) params
{
    
    DebugLog(@"get_pagedata");
    if(![ApexMobileNetwork IsNetworkAvailable])
        return nil;
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    NSData* json=[ApexMobileNetwork get_json:URL_REQUEST_RECORDS parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return nil;
    }
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result== AP_SESSION_EXPIRED)
        {
            [self Authorize:appDelegate.user password:appDelegate.password];
            json=[ApexMobileNetwork get_json:URL_REQUEST_RECORDS parameters:params];
            if (json==nil)
            {
                DebugLog(@"json is wrong");
                return nil;
            }
            jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
            result = [[jsobj valueForKey:@"result"] intValue];
            
        }
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            return nil;
            
        }
        
        NSDictionary* objrecords = [jsobj objectForKey:@"records"];
        
        PageData * pageData = [[PageData alloc] initWithRecords:objrecords];
        return pageData;
        
    }
    return nil;
    
}
+(int) get_recordcount: (NSMutableDictionary *) params// delegate:(id < NSURLConnectionDelegate >)delegate
{
    DebugLog(@"get_recordcount");
    if(![ApexMobileNetwork IsNetworkAvailable])
        return RESULT_NET_NOTAVAILABLE;
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [params setValue:@"handset_search_count" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_REQUEST_COUNT parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return RESULT_NET_ERROR;
    }
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    if(jsobj)
    {
        int result = [[jsobj valueForKey:@"result"] intValue];
        if(result== AP_SESSION_EXPIRED)
        {
            [self Authorize:appDelegate.user password:appDelegate.password];
            json=[ApexMobileNetwork get_json:URL_REQUEST_COUNT parameters:params];
            if (json==nil)
            {
                DebugLog(@"json is wrong");
                return RESULT_NET_ERROR;
            }
            jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
            result = [[jsobj valueForKey:@"result"] intValue];
            
        }
        if(result!=AP_USER_AUTH)
        {
            DebugLog(@"USER NOT AUTHORIZED CODE=%d ",result);
            return RESULT_USERAUTH_ERROR;
            
        }
        else
            return [[jsobj valueForKey:@"count" ] intValue];
    }
    
    return RESULT_ERROR;
}
//+(bool) IsHostAvailable : (NSString*) url
//{
//    Reachability *r = [Reachability reachabilityWithHostName:url];
//    int i = [r currentReachabilityStatus];
//    if ([r currentReachabilityStatus]==NotReachable)
//        return false;
//    return true;
//}
+(bool) IsNetworkAvailable
{
    
    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) &&
        ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable))
        return false;
    return true;
}

+(void)post_without_return : (NSString*) url parameters:(NSMutableDictionary *) params //delegate:(id < NSURLConnectionDelegate >)delegate
{
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:30];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    //    NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    
    //    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    //     [params setValue:@"handset_login" forKey:@"action"];
    //    [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
    
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    //   [params setValue:password forKey:@"password"];
    //    [params setValue:[NSString stringWithFormat:@"%d",ver]  forKey:@"auth_ver"];
    
    
    
    //    [headers setValue:headQuerlString forKey:@"param"];
    
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    DebugLog(@"================parms==================");
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"pic"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
            DebugLog(@"parameter: key=%@   value=%@",key,[params objectForKey:key]);
        }
    }
    DebugLog(@"================parms==================");
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    //    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    
    NSHTTPURLResponse* urlResponse = nil;
    
    NSError *error = [[NSError alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){}];
    //    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:nil];
    
    
    
}
+(NSData*)get_marketnews : (NSString*) id limit: (int) limit
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return nil;//RESULT_NET_NOTAVAILABLE;
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Market News" forKey:@"module_name"];
    [params setValue:@"search" forKey:@"action_type"];
    [params setValue:id forKey:@"id"];
    [params setValue:[NSString stringWithFormat:@"%d",limit ] forKey:@"limit"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_ANNOUNCEMENTS parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return nil;
    }
    return json;
    
    
    
}
+(NSData*)get_MessageDetail: (int) offset limit:(int) limit from:(NSString*) sid to:(NSString*) eid
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return nil;//RESULT_NET_NOTAVAILABLE;
    
    
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    //    NSString* sess
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Pull Message" forKey:@"module_name"];
    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:sid forKey:@"s_id"];
    [params setValue:eid forKey:@"e_id"];
    [params setValue:@"detail" forKey:@"action_type"];
    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    [params setValue:appDelegate.duid forKey:@"uuid"];
    

    
    [params setValue:[NSString stringWithFormat:@"%d",offset] forKey:@"offset"];
    [params setValue:[NSString stringWithFormat:@"%d",limit] forKey:@"limit"];
    //    [params setValue:@"20" forKey:@"limit"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return nil;
    }
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    int result = [[jsobj valueForKey:@"result" ] intValue] ;
    if(result== AP_SESSION_EXPIRED)
    {
        [self Authorize:appDelegate.user password:appDelegate.password];
        json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
        if (json==nil)
        {
            DebugLog(@"json is wrong");
            return nil;
        }
        jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
        result = [[jsobj valueForKey:@"result"] intValue];
        
    }
    if(result!= AP_MESSAGE_NEW)
        return nil;
    
    
    return json;
    
}
+(int) delAllMessage:(NSString*) before
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return RESULT_NET_NOTAVAILABLE;//RESULT_NET_NOTAVAILABLE;
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    //    NSString* sess
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Pull Message" forKey:@"module_name"];
    [params setValue:@"read_all" forKey:@"action_type"];
    [params setValue:@"handset_search" forKey:@"action"];
    //    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    [params setValue:appDelegate.duid forKey:@"uuid"];
    [params setValue:before forKey:@"id"];
    
    
    NSData* json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return RESULT_NET_ERROR;
    }
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    int result = [[jsobj valueForKey:@"result" ] intValue] ;
    if(result== AP_SESSION_EXPIRED)
    {
        [self Authorize:appDelegate.user password:appDelegate.password];
        json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
        if (json==nil)
        {
            DebugLog(@"json is wrong");
            return RESULT_NET_ERROR;
        }
        jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
        result = [[jsobj valueForKey:@"result"] intValue];
        
    }
    return result;
    
    
}
+(NSData*)pull_message: (int) offset
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return nil;//RESULT_NET_NOTAVAILABLE;
    
    
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    //    NSString* sess
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Pull Message" forKey:@"module_name"];
    [params setValue:@"ios_list" forKey:@"action_type"];
    [params setValue:@"handset_search" forKey:@"action"];
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    [params setValue:appDelegate.duid forKey:@"uuid"];
    [params setValue:[NSString stringWithFormat:@"%d",offset] forKey:@"offset"];
    [params setValue:@"20" forKey:@"limit"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return nil;
    }
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    int result = [[jsobj valueForKey:@"result" ] intValue] ;
    if(result== AP_SESSION_EXPIRED)
    {
        [self Authorize:appDelegate.user password:appDelegate.password];
        json=[ApexMobileNetwork get_json:URL_PUSH parameters:params];
        if (json==nil)
        {
            DebugLog(@"json is wrong");
            return nil;
        }
        jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
        result = [[jsobj valueForKey:@"result"] intValue];
        
    }
    if(result!= AP_MESSAGE_NEW)
        return nil;
    
    
    return json;
    
}
+(bool) UpdateServiceLocation
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return false;//RESULT_NET_NOTAVAILABLE;
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Location" forKey:@"module_name"];
    [params setValue:@"search" forKey:@"action_type"];
    [params setValue:@"999" forKey:@"limit"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_LOCATIONS parameters:params];
    if (json==nil)
        return false;
    
    NSError *error=nil;
    NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
    NSString* remote_ver = [jsobj valueForKey:@"version"] ;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    NSString *local_ver =[defaults stringForKey:@"location_ver"];
    int total = [[jsobj valueForKey:@"total"] intValue];
    
    BOOL bigger = [remote_ver compare:local_ver];
    if(!bigger)
        return false;
    
    
    sqlite3 *db =[ApexMobileDB get_db];
    [ApexMobileDB execSql:@"delete from locations" db:db];
    
    char* sql = "insert into locations(area,company,city,longitude,latitude,address,telephone,fax,contact,email) values(?,?,?,?,?,?,?,?,?,?)";
    sqlite3_stmt *stmt;
    
    sqlite3_prepare_v2(db, sql, -1, &stmt, nil);
    
    NSDictionary* objrecords = [jsobj objectForKey:@"records"];
    
    for(int i=0;i<total;i++)
    {
        
        NSDictionary* objlocation = [objrecords objectForKey:[NSString stringWithFormat:@"record%d",i]];
        NSString* area = [objlocation valueForKey:@"area"];
        NSString* company = [objlocation valueForKey:@"company"];
        NSString* city = [objlocation valueForKey:@"city"];
        NSString*  longitude = [objlocation valueForKey:@"longitude"] ;
        NSString*  latitude = [objlocation valueForKey:@"latitude"] ;
        NSString* address = [objlocation valueForKey:@"address"];
        NSString* telephone = [objlocation valueForKey:@"telephone"];
        NSString* fax = [objlocation valueForKey:@"fax"];
        NSString* contact = [objlocation valueForKey:@"contact"];
        NSString* email = [objlocation valueForKey:@"email"];
        
        
        if([area isEqual:[NSNull null]])
            area=@"";
        if(area==nil)
            area=@"";
        if([area isEqualToString:@"null"])
            area=@"";
        
        
        if([company isEqual:[NSNull null]])
            company=@"";
        if(company==nil)
            company=@"";
        if([company isEqualToString:@"null"])
            company=@"";
        
        if([city isEqual:[NSNull null]])
            city=@"";
        if(city==nil)
            city=@"";
        if([city isEqualToString:@"null"])
            city=@"";
        
        if([longitude isEqual:[NSNull null]])
            longitude=@"";
        if(longitude==nil)
            longitude=@"";
        if([longitude isEqualToString:@"null"])
            longitude=@"";
        
        if([latitude isEqual:[NSNull null]])
            latitude=@"";
        if(latitude==nil)
            latitude=@"";
        if([latitude isEqualToString:@"null"])
            latitude=@"";
        
        if([address isEqual:[NSNull null]])
            address=@"";
        if(address==nil)
            address=@"";
        if([address isEqualToString:@"null"])
            address=@"";
        
        if([telephone isEqual:[NSNull null]])
            telephone=@"";
        if(telephone==nil)
            telephone=@"";
        if([telephone isEqualToString:@"null"])
            telephone=@"";
        
        if([fax isEqual:[NSNull null]])
            fax=@"";
        if(fax==nil)
            fax=@"";
        if([fax isEqualToString:@"null"])
            fax=@"";
        
        if([contact isEqual:[NSNull null]])
            contact=@"";
        if(contact==nil)
            contact=@"";
        if([contact isEqualToString:@"null"])
            contact=@"";
        
        if([email isEqual:[NSNull null]])
            email=@"";
        if(email==nil)
            email=@"";
        if([email isEqualToString:@"null"])
            email=@"";
        
        sqlite3_bind_text(stmt, 1, [area UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [company UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [city UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [longitude UTF8String], -1, NULL);
        
        sqlite3_bind_text(stmt, 5, [latitude UTF8String], -1, NULL);
        
        
        
        sqlite3_bind_text(stmt, 6, [address UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 7, [telephone UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 8, [fax UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 9, [contact UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 10, [email UTF8String], -1, NULL);
        if (sqlite3_step(stmt) != SQLITE_DONE)
        {
            
            fprintf(stderr, "Error: insert search failed, error infomation: %s\nsql:%s\n", sqlite3_errmsg(db),sqlite3_sql(stmt));
        }
        sqlite3_reset(stmt);
        
    }
    
    sqlite3_finalize(stmt);
    
    sqlite3_close(db);
    
    [defaults removeObjectForKey:@"location_ver"];
    [defaults setValue:remote_ver forKey:@"location_ver"];
    return true;
    
}
//+(void) testmail1:(UIViewController*) caller
//{
//    MFMailComposeViewController *mail=[[MFMailComposeViewController alloc] init];
//    mail.mailComposeDelegate=caller;
//
//    //设置主题
//    [mail setSubject:@"测试发送电子邮件"];
//
//    //添加收件人
//    NSArray *toRecipients=[NSArray arrayWithObject:@"admin@163.com"];
//    [mail setToRecipients:toRecipients];
//    //添加抄送;
//    NSArray *ccRecipients=[NSArray arrayWithObjects:@"test1@163.com",@"test@qq.com", nil];
//    [mail setCcRecipients:ccRecipients];
//    //添加密送
//    NSArray *bccRecipients=[NSArray arrayWithObject:@"admin@gmail.com"];
//    [mail setBccRecipients:bccRecipients];
//
//
//    //添加一张图片
//    UIImage *addPic=[UIImage imageNamed:@"bg_3"];
//    NSData *imageData=UIImagePNGRepresentation(addPic);
//    [mail addAttachmentData:imageData mimeType:@"image/png" fileName:@"icon"];
//
//    //添加一个xml附件
////    NSString *file=[self fullBundlePathFromRelativePath:@"model.xml"];
////    NSData *xmldata=[NSData dataWithContentsOfFile:file];
////    [mail addAttachmentData:xmldata mimeType:@"" fileName:@"model"];
//
//    NSString *emailBody=@"<font color='red'>send test email</font>";
//    [mail setMessageBody:emailBody isHTML:YES];
//    [caller presentViewController:mail animated:YES completion:nil];
//
//
//}
//+(void) testmail
//{
//    NSMutableString *buffer=
//    [NSMutableString stringWithString:
//     @"<HTML><HEAD><TITLE>PAGE</TITLE></HEAD><BODY>example<img src=\"data:image/png;base64,\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0IHF1YWxpdHkK\/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy\/9sAQwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMj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WYIMKCelFFUgMmYB74SsMsIyM\/jVyNR5WaKKuh8ciavwoiRt0e1sFfQ0+5jSFFlhXynX5cpxkHtRRUYn+KiqP8NlcH5g55ZSGBPPNNnmeS6kkOAXbJAHHNFFEt0Zr4TR0yxhN\/b3Q3B+SQDwSK61X\/ANlee+KKK4qmrOuGx6r8N\/8AkXrn\/r7b\/wBASiiit4fCjN7n\/9k=\"  /></BODY></HTML>"];
//      NSString* subjectLine =@"Example HTML formatted EMAIL with Image";
//
//      NSString *str1 = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorSystemDefault, (CFStringRef) subjectLine, NULL, CFSTR(";/?:@&=+$,"), kCFStringEncodingUTF8));
//      NSString *str2 = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorSystemDefault, (CFStringRef)buffer, NULL, CFSTR(";/?:@&=+$,"), kCFStringEncodingUTF8));
//
//      NSString *urlString = [NSString stringWithFormat:@"mailto:?subject=%@&body=%@",str1 ,str2 ];
//
//      [[UIApplication sharedApplication] openURL:[NSURL  URLWithString:urlString]];
//
////    [NSURL URLWithString:urlString];
//}
+(NSData*)get_announcements : (NSString*) id limit: (int) limit
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return nil;//RESULT_NET_NOTAVAILABLE;
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    [params setValue:@"Announcements" forKey:@"module_name"];
    [params setValue:@"search" forKey:@"action_type"];
    [params setValue:id forKey:@"id"];
    [params setValue:[NSString stringWithFormat:@"%d",limit ] forKey:@"limit"];
    
    NSData* json=[ApexMobileNetwork get_json:URL_ANNOUNCEMENTS parameters:params];
    if (json==nil)
    {
        DebugLog(@"json is wrong");
        return nil;
    }
    return json;
    
    
    
}
+(NSData*)get_json : (NSString*) url parameters:(NSMutableDictionary *) params //delegate:(id < NSURLConnectionDelegate >)delegate
{
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:30];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    //    NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    
    //    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    //     [params setValue:@"handset_login" forKey:@"action"];
    //    [headers setValue:[NSString stringWithFormat:@"%d",dataLength] forKey:@"Content-Length"];
    
    [params setValue:appDelegate.sessionid forKey:@"sessionid"];
    //   [params setValue:password forKey:@"password"];
    //    [params setValue:[NSString stringWithFormat:@"%d",ver]  forKey:@"auth_ver"];
    
    
    
    //    [headers setValue:headQuerlString forKey:@"param"];
    
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    DebugLog(@"================parms==================");
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"pic"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
            DebugLog(@"parameter: key=%@   value=%@",key,[params objectForKey:key]);
        }
    }
    DebugLog(@"================parms==================");
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    //    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    
    NSHTTPURLResponse* urlResponse = nil;
    
    NSError *error = [[NSError alloc] init];
    
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    
    DebugLog(@"response: %@",[NSHTTPURLResponse localizedStringForStatusCode:urlResponse.statusCode]);
    
    if (responseData==nil) {
        
        DebugLog(@"move failed:%@", [error localizedDescription]);
    }
    else
    {
        NSMutableString *result = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        
        DebugLog(@"result: %@",result);
        
        
    }
    return responseData;
    
}
+(void)Logout
{
    if(![ApexMobileNetwork IsNetworkAvailable])
        return ;//RESULT_NET_NOTAVAILABLE;
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    if(appDelegate.duid !=nil)
        [params setValue:appDelegate.duid forKey:@"udid"];
    [params setValue:@"handset_logout" forKey:@"action"];
    
    [ApexMobileNetwork post_without_return :URL_UPDATE_AUTH parameters:params];
}
+(int)Authorize : (NSString*) user password:(NSString*) password{
    
    if(![ApexMobileNetwork IsNetworkAvailable])
        return RESULT_NET_NOTAVAILABLE;
    //    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];
    ApexMobileAppDelegate *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:user forKey:@"user"];
    [params setValue:password forKey:@"password"];
    [params setValue:[NSString stringWithFormat:@"%ld",ver]  forKey:@"auth_ver"];
#ifdef TEST
    [params setValue:@"true" forKey:@"is_debug"];
#else
    [params setValue:@"false" forKey:@"is_debug"];
#endif
    NSData* json=[ApexMobileNetwork get_json:URL_UPDATE_AUTH parameters:params];
    if(json==nil)
        return RESULT_NET_ERROR;
    
    int ret = [ApexMobileNetwork parse_authinfo:json user:user password:password];
    DebugLog(@"parse_authinfo return %d ",ret);
    
    
    return ret;
    
}

@end
