//
//  AppDelegate.m
//  RedAnt ERP Suite
//
//  Created by Ray on 14-5-19.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "AppDelegate.h"
#import "UILabel+FontAppearance.h"
#import "MainViewController.h"
#import "PDFViewController.h"
#import "ZipArchive.h"
#import "DefaultAppearance.h"
#import "OLDataProvider.h"
#import "AFHTTPSessionManager.h"
#import "SelectUploadOrderViewController.h"
#import "iSalesDB.h"
#import "iSalesNetwork.h"
#import "NotificationNameCenter.h"
#import "CustomerEditViewController.h"
#import "CreateOrderViewController.h"
#import "OrderDetailViewController.h"
#import "AddressEditorViewController.h"
#import "config.h"
#import "Singleton.h"
#define UNZIP_OPEN_FAILED 0
#define UNZIP_SUCCESS 1
#define UNZIP_NO_SPACE 2
#define UNZIP_FILE_DAMAGE 3

@implementation AppDelegate
{
#ifdef USE_SOFTSCAN
    DeviceInfo* _softScanDeviceInfo;
#endif
    DeviceInfo* _deviceInfoToTrigger;
}
@synthesize price_hidden = _price_hidden;
@synthesize ScanApi;
@synthesize ScanApiConsumer;
@synthesize scanApiVersion;
//@synthesize devices;
-(void) set_priceHidden:(bool)price_hidden
{
    _price_hidden = price_hidden;
    
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    
    //    NSObject* obj;
    //    [obj isEqual:@""];
    
    [avc showHidePrice];
}

-(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
{

    _customerInfo=customerInfo;
    
//    DebugLog(@"%@",_customerInfo.class);
//    DebugLog(@"%@",customerInfo.class);
    int count=customerInfo[@"count"];
    //assert(count==0);
    
}
-(void) set_main_button_panel
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        if(self.user_type==USER_ROLE_CUSTOMER)
        {
            main_vc.customer_bp.hidden=false;
            main_vc.employee_bp.hidden = true;
        }
        else
        {
            main_vc.customer_bp.hidden=true;
            main_vc.employee_bp.hidden = false;
        }
    });
}
-(void) update_count_mark
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        //contact button
        
        
        
        if(self.user==nil)
        {
            
            
            [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
            
            [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            main_vc.btnContact.hidden = YES;
            
        }
        else
        {
            
            
            
            NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
            NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
            if(self.customerInfo==nil)
            {
                //                contact=@"No Name";    if(customerinfo==nil)
                //                {
                contact=@"Select Contact";
                [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }
            else
            {
                
                if(contact==nil||contact.length==0)
                {
                    contact=@"No Name";
                    [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                }
                else
                {
                    [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
                }
            }
            
            NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
            if(contact.length>0)
                [arr_contact addObject:contact];
            if(customer.length>0)
                [arr_contact addObject:customer];
            
            NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
            
            
            [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
            
            
        }
        //cart
        if(self.user==nil||self.cart_count==0)
        {
            main_vc.label_ccount.hidden = true;
            main_vc.label_cccount.hidden=true;
        }
        else
        {
            
            NSString* strcount;
            if(self.cart_count>999)
                strcount=@"999+";
            else
                strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
            
            main_vc.label_ccount.text = strcount;
            if(strcount.length==1)
                main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
            if(strcount.length==2)
                main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
            if(strcount.length==3)
                main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
            if(strcount.length==4)
                main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
            
            main_vc.label_ccount.hidden = false;
            
            
            main_vc.label_cccount.text = strcount;
            if(strcount.length==1)
                main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
            if(strcount.length==2)
                main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
            if(strcount.length==3)
                main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
            if(strcount.length==4)
                main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
            
            main_vc.label_cccount.hidden = false;
            
            
        }
        
        //wishlist
        if(self.user==nil||self.wish_count==0)
        {
            main_vc.label_wcount.hidden = true;
            main_vc.label_cwcount.hidden = true;
            
        }
        else
        {
            
            NSString* strcount;
            if(self.wish_count>999)
                strcount=@"999+";
            else
                strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
            
            main_vc.label_wcount.text = strcount;
            if(strcount.length==1)
                main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
            if(strcount.length==2)
                main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
            if(strcount.length==3)
                main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
            if(strcount.length==4)
                main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
            
            
            main_vc.label_wcount.hidden = false;
            
            
            
            main_vc.label_cwcount.text = strcount;
            if(strcount.length==1)
                main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
            if(strcount.length==2)
                main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
            if(strcount.length==3)
                main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
            if(strcount.length==4)
                main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
            
            
            main_vc.label_cwcount.hidden = false;
            
            
        }
    });
    
    
}
-(void) closeOrder
{
    self.order_code = nil;
    self.order_customer_id = nil;
    
    
    if(self.user_type!=USER_ROLE_CUSTOMER)
    {
        self.customerInfo = nil;
        self.contact_id = nil;
    }

    //   [self SetMode:nil];
    //   [self SetSo:nil];
    
    
    
    [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
    [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
}
-(void) switchToPreviousVC
{
    MainViewController * main_vc= (MainViewController*)self.main_vc;
    
    [main_vc switchToPreviousVC];
}

-(void) SetMode:(NSString*)mode1
{
    
    __block NSString* blockmode= mode1;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        if(self.offline_mode)
            blockmode =@"Regular Mode";
        
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        if(self.user==nil)
        {
            
            NSString* title = [NSString stringWithFormat:@"Sign in"];
            [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
            
            [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
            
            [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            main_vc.btnContact.hidden = YES;
            
            main_vc.labelMode.text=nil;
            [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
            //        [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
            //        main_vc.buttonUser.hidden=true;
            //        main_vc.buttonUser.hidden=false;
            //         [main_vc.headerView setNeedsDisplay];
            //        [main_vc.headerView setNeedsLayout];
            return;
        }
        else
        {
            if(self.user_type==USER_ROLE_CUSTOMER)
            {
                NSString* title = [NSString stringWithFormat:@"%@",self.user];
                [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                main_vc.labelMode.text=nil;
                [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
                
                //            [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
                //            main_vc.buttonUser.hidden=true;
                //            main_vc.buttonUser.hidden=false;
                //             [main_vc.headerView setNeedsDisplay];
                //            [main_vc.headerView setNeedsLayout];
            }
            else
            {
                if([blockmode isEqualToString:@"Regular Mode"])
                {
                    self.mode=@"RM";
                    NSString* title = self.user;
                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                    
                    main_vc.labelMode.text=self.mode;
                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
                    //                main_vc.buttonUser.hidden=true;
                    //                main_vc.buttonUser.hidden=false;
                    //                 [main_vc.headerView setNeedsDisplay];
                    //                [main_vc.headerView setNeedsLayout];
                }
                else
                {
                    
                    self.mode=@"TM";
                    NSString* title = self.user;
                    [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
                    
                    main_vc.labelMode.text=self.mode;
                    [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
                    //                [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x009966) forState:UIControlStateNormal];
                    //                main_vc.buttonUser.hidden=true;
                    //                main_vc.buttonUser.hidden=false;
                    //                 [main_vc.headerView setNeedsDisplay];
                    //                [main_vc.headerView setNeedsLayout];
                }
                

                
            }
            
            NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
            NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
            if(self.customerInfo==nil)
            {
                //                contact=@"No Name";    if(customerinfo==nil)
                //                {
                contact=@"Select Contact";
                [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            }
            else
            {
                
                if(contact==nil||contact.length==0)
                {
                    contact=@"No Name";
                    [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                }
                else
                {
                    [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
                }
            }
            
            NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
            if(contact.length>0)
                [arr_contact addObject:contact];
            if(customer.length>0)
                [arr_contact addObject:customer];
            
            NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
            
            
            [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
        }
    });
}


-(void) SetSo:(NSString *)So
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.main_vc==nil)
            return;
        
        MainViewController * main_vc= (MainViewController*)self.main_vc;
        
        if(self.user==nil)
        {
            
            //            NSString* title = [NSString stringWithFormat:@"Sign in"];
            main_vc.labelSo.text=nil;
            
            return;
        }
        else
        {
//            if(self.user_type==USER_ROLE_CUSTOMER)
//            {
//                
//                
//                main_vc.labelSo.text=nil;
//                //            main_vc.buttonUser.hidden=true;
//                //            main_vc.buttonUser.hidden=false;
//                //             [main_vc.headerView setNeedsDisplay];
//                //            [main_vc.headerView setNeedsLayout];
//            }
//            else
            {
                if(So.length==0)
                    main_vc.labelSo.text=nil;
                else
                {
                    NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
                    main_vc.labelSo.text=text;
                }
            }
        }
    });
}
//- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
//    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
//        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
//        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
//    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
//        UINavigationController* navigationController = (UINavigationController*)rootViewController;
//        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
//    } else if (rootViewController.presentedViewController) {
//        UIViewController* presentedViewController = rootViewController.presentedViewController;
//        return [self topViewControllerWithRootViewController:presentedViewController];
//    } else {
//        return rootViewController;
//    }
//}
//- (UIViewController*)topViewController {
//    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
//}
//-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
////      // Get topmost/visible view controller
//    UIViewController *currentViewController = [self topViewController];
//
//    if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
//
//        return UIInterfaceOrientationMaskPortrait;
//    }
////
////      // Only allow portrait (standard behaviour)
//    return UIInterfaceOrientationMaskAll;
//}

void UncaughtExceptionHandler(NSException *exception) {
    
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
    NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
    NSString *versionNum = @"";
#ifdef BUILD_NPD
    versionNum = [NSString stringWithFormat:@"Version: npd %@ Build %@",version,build];
#endif
    
#ifdef BUILD_HMLG
    versionNum = [NSString stringWithFormat:@"Version: HOMELEGANCE %@ Build %@",version,build];
#endif
    
    versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
    /**
     *  获取异常崩溃信息
     */
    NSArray *callStack = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name:  %@\n exception_reason:  \n%@ \n exception_callStackSymbols:  \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
    
    content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
    
    
    NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
    if ([Singleton sharedInstance].currentDB) {
        [iSalesDB close_db:[Singleton sharedInstance].currentDB];
    }
    [iSalesDB execSql:sql];
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate writeUrgencyCache];
}

- (void)handleErrorLog {
    
    __block NSMutableArray *err_array = [NSMutableArray array];
    [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
        
        const char *version_char = (char *)sqlite3_column_text(stmt, 0);
        const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
        const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
        
        if (version_char == NULL)
            version_char = "";
        if (errlog_char == NULL)
            errlog_char = "";
        if (dateTime_char == NULL)
            dateTime_char = "";
        
        NSString *version_str = [NSString stringWithUTF8String:version_char];
        NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
        NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
        
        NSDictionary *err_dic = @{
                                  @"version" : version_str,
                                  @"errlog" : errlog_str,
                                  @"time" : dateTime_str
                                  };
        
        [err_array addObject:err_dic];
        
        
    }];
    
    if (err_array.count) {
        // 首先上传
        for (NSDictionary *err_dic in err_array) {
            
            NSString *version = [err_dic objectForKey:@"version"];
            NSString *errlog = [err_dic objectForKey:@"errlog"];
            NSString *time = [err_dic objectForKey:@"time"];
            
            NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
            
            NSDictionary *ret = [iSalesNetwork err_log:errlog result:result module:@"crash" code:0];
            
            // 上传成功之后清除纪录
            if ([[ret objectForKey:@"result"] integerValue] == 2) {
                
                [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
            }
        }
        
        
    }
    
    
}

- (void)dealWithUrgencyFile {
    
    NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
    
    if (tmp_urgencyDic.allKeys.count > 2) {
        
        [self.urgencyDic removeAllObjects];
        [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
        
        MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        NSString *user = [tmp_urgencyDic objectForKey:@"user"];
        if (![user isEqualToString:self.user]) {
            return;
        }
        
        BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
        if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
            return;
        }
        
        id count = [tmp_urgencyDic objectForKey:@"count"];
        int level_count = count ? [count integerValue] : 0;
        
        if (!level_count) {
            return;
        }
        
        for (int i = 0; i < level_count; i++) {
            
            NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
            
            NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
            
            NSString *className = [urgencyDic objectForKey:@"class_name"];
            
            NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
            
            NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
            
            dispatch_async(dispatch_get_main_queue(), ^{
               
                if ([className isEqualToString:@"CustomerEditViewController"]) {
                    // CustomerEditViewController
                    
                    NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
                    
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    
                    [params setValue:contact_id forKey:@"contact_id"];
                    CustomerEditViewController * cuseditVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CustomerEditViewController"];
                    
                    cuseditVC.bnewcustomer=false;
                    cuseditVC.url_type = URL_RESTORE;
                    cuseditVC.request_url=URL_EDIT_CUSTOMER;
                    
                    cuseditVC.params = params;
                    cuseditVC.content_data_download = restored_data;
                    
                    //            cuseditVC.delegate=self;
                    
                    
                    [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
                    [mainVC.navigationController pushViewController:cuseditVC animated:false];
                    
                    
                    
                } else if ([className isEqualToString:@"CreateOrderViewController"]) {
                    // CreateOrderViewController
                    
                    NSString *order_code = [urgencyDic objectForKey:@"order_code"];
                    int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
                    NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
                    NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
                    NSString *so = [urgencyDic objectForKey:@"order_so"];
                    self.order_customer_id = order_customer_id;
                    
                    // 首先通过order code 打开订单
                    NSDictionary* order_json = [iSalesNetwork open_Order:order_code];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //                [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                        if([[order_json valueForKey:@"result"] intValue]==2)
                        {
                            
                            self.order_code = order_code;
                            self.order_status = order_status;
                            [self SetSo:so];
                            
                            if (userType != USER_ROLE_CUSTOMER) {
                                self.customerInfo = [[[iSalesNetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
                                
                                self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
                            }
                           
                            
                            [mainVC reloadOrder:true immediately:false];
                            [mainVC reloadCart:true immediately:false];
                            
                            
                        }
                        else
                        {
                            [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:mainVC] ;
                        }
                    });
                    
                    
                    
                    // 再place order
                    
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    
                    CreateOrderViewController * orderinfoVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CreateOrderViewController"];
                    
                    orderinfoVC.disable_dropdown_refresh=true;
                    orderinfoVC.url_type = URL_RESTORE;
                    orderinfoVC.request_url=URL_CARTDELIVERY;
                    orderinfoVC.params = params;
                    orderinfoVC.content_data_download = restored_data;
                    orderinfoVC.resumeOrder = YES;
                    
                    [mainVC.navigationController pushViewController:orderinfoVC animated:true];
                    
                    
                } else  if ([className isEqualToString:@"AddressEditorViewController"]) {
                    // AddressEditorViewController
                    
                    AddressEditorViewController * addressVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"AddressEditorViewController"];
                    
                    addressVC.url_type = URL_RESTORE;
                    addressVC.request_url=URL_ADDRESS_EDOTOR;
                    
                    NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
                    
                    params[@"is_subaction"]=@"true";
                    addressVC.params = params;
                    addressVC.content_data_download = restored_data;
                    
                    
                    [mainVC.navigationController pushViewController:addressVC animated:true];
                    
                }// class_name
                
            });
            
        }
        
        
    }
}

- (void)handleUrgencyFile {
    
    __weak typeof(self) weakself = self;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        if (weakself) {
            
            __strong typeof(weakself) strongself = weakself;
            
            [strongself dealWithUrgencyFile];
        }
        
        

        
    });
    
}

- (void)writeUrgencyCache {
    if (!self.user) {
        return;
    }
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];

//    [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
    [self.urgencyDic writeToFile:urgencyFile atomically:NO];
    
    // Place Order恢复是否能提交订单
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
    if ([Singleton sharedInstance].currentOrderIsMerged && [Singleton sharedInstance].permissions_submit_order) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
    }
}

- (NSMutableDictionary *)readUrgencyCache {
    // 检查本地urgency文件，存在则加载进_urgencyDic
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
    NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
    if ([manager fileExistsAtPath:urgencyFile]) {
        
        resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
        [manager removeItemAtPath:urgencyFile error:nil];
        
    }
    
    _urgencyDic = [NSMutableDictionary dictionary];

    return resultDic;
}

- (void)initialExceptionHandler {
    if (exception_switch == 1) {
        NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
    }
    
}

- (void)becomeObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{


    
//    [RAUtils expression_varable:nil regex:nil];
    self.disable_trigger = false;
    [self initialExceptionHandler];
    [self becomeObserver];
    
    [DefaultAppearance init_appearance];
    
    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");
        
    }
    
    NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
    
    if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
    {
        NSError *error = nil;
        bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
        
        if(!bsuccess)
            DebugLog(@"Create PDF Cache folder failed");
        
    }

    
    //    if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
    //
    //        DebugLog(@"文件已经存在了");
    //
    //    }
    
    
    
    
    
    //    NSString* order_filter_source_path =[[NSBundle mainBundle]  pathForResource:@"status_filter_cadedate" ofType:@"json" ];
    //    /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
    //
    //
    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //    NSString *documents = [paths objectAtIndex:0];
    //    NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
    //
    //
    //    if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
    //
    //        DebugLog(@"文件已经存在了");
    //
    //    }
    //    else
    //    {
    //
    //
    //
    //        //        DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
    //
    //        NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
    //
    //        //        DebugLog(@"mainBundleFile==%@",mainBundleFile);
    //
    //        [[NSFileManager defaultManager] createFileAtPath:dist_path
    //
    //                                                contents:mainBundleFile
    //
    //                                              attributes:nil];
    //
    //    }
    
    
    self.recent_model = [[NSMutableDictionary alloc]init];
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    bool  offline = [defaults boolForKey:@"EnableOfflineMode"] ;
    self.offline_mode = offline;
    // Override point for customization after application launch.
    
    if ( [iSalesDB initializeDb]!=0)
        DebugLog(@"init db failed");
    // disable apn
    //    [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
    self.contact_id=nil;
    
    //   NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
    if([enable_cache isEqualToString:@"false"])
        self.bEnable_Cache = false;
    else
        self.bEnable_Cache = true;
    
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    self.build =[infoDict objectForKey:@"CFBundleVersion"];
    
    
    
    //scanner
    
    self.devices=[[NSMutableArray alloc]init];
    
    // change this to YES if you want SingleEntry to
    // confirm the decoded data
    _doAppDataConfirmation=NO;
    
    if(ScanApi==nil){
#ifdef USE_SOFTSCAN
        // this is useful for SoftScan to keep a handle
        // that is used in the trigger button
        _softScanDeviceInfo=nil;
#endif
        
        ScanApi=[[ScanApiHelper alloc]init];
        [ScanApi setDelegate:self];
        self.enable_ScannerLog = true;
        self.api_Status= API_STOP;
        
        
        
        //        UIApplication * app = [UIApplication sharedApplication];
        //        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        //
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        bool  autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
        if(autolaunch==true)
            [self enableScanner:autolaunch];
        
    }
    
    
    //    [self test_descrypt];
    //    [self test_descrypt1];
    //UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:uialertcontroller.class, nil];
    //  [appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example
    
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self handleErrorLog];
    });
    
    return YES;
}
//-(void)test_descrypt
//{
//    sqlite3 *db = [iSalesDB get_db];
//
//   int result= [iSalesDB AddExFunction:db];
//
//    NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
//    sqlite3_stmt * statement;
//
//
//    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
//    {
//
//
//        while (sqlite3_step(statement) == SQLITE_ROW)
//        {
//
//
//            char *url = (char*)sqlite3_column_text(statement, 0);
//            if(url==nil)
//                url="";
//            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
//            DebugLog(nsurl);
//
//
//
//
//        }
//      //  [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
//
//
//        sqlite3_finalize(statement);
//    }
//
//    [iSalesDB close_db:db];
//}
//
//-(void)test_descrypt1
//{
//    sqlite3 *db = [iSalesDB get_db];
//
//    int result= [iSalesDB AddExFunction:db];
//
//    NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
//
//    [iSalesDB execSql:sqlindex];
////
////    NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
////    sqlite3_stmt * statement;
////
////
////
////    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
////    {
////
////
////        while (sqlite3_step(statement) == SQLITE_ROW)
////        {
////
////
////            char *url = (char*)sqlite3_column_text(statement, 0);
////            if(url==nil)
////                url="";
////            NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
////            DebugLog(nsurl);
////
////
////
////
////        }
////        //  [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
////
////
////        sqlite3_finalize(statement);
////    }
//
//    [iSalesDB close_db:db];
//}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self download_offline:false checkdiskspace:false];
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if(self.download_task!=nil)
        [self download_offline:true checkdiskspace:false];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    DebugLog(@"======================================");
    DebugLog(@"=====    MEMORY WORRING !   ==========");
    DebugLog(@"======================================");
}
- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) Logout
{
    MainViewController * main_vc= (MainViewController*)self.main_vc;
    [main_vc logoutOrder];
    
    
    [main_vc hideMenu];
    [main_vc switchToHome];
    self.user = nil;
    self.password=nil;
    self.user_icon=nil;
    self.user_type = USER_ROLE_UNKNOWN;
    self.bLogin = false;
    self.contact_id=nil;
    self.customerInfo = nil;
    self.order_code = nil;
    
    [self.recent_model removeAllObjects];
    
    [self SetMode:nil];
    
}
//disable apn
//-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
//{
//    self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
//    DebugLog(@"regisger success:%@",deviceToken);
//
//    //注册成功，将deviceToken保存到应用服务器数据库中
//}
#pragma mark - background download
-(bool)isdownloading:(NSString*) file
{
    return true;
}
-(long long)getcurrentLength:(int) taskidx
{
    
    int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
    return position;
}

-(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
{
    //操作有两种，start stop；
    //结果有四种， wait ， downloading， pause， finish
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSString* file_name=[url lastPathComponent];
        //暂停<->开始转换
        
        //   bool isdownloading = [self isdownloading:file_name];
        if (start)
        {//开始下载
            
            
            
            
            
            
            DebugLog(@"%d start",taskidx);
            
            self.current_task=taskidx;
            
            
            
            NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
            
            //        _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
            //
            //
            //        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
            //
            //        //设置请求头（GET）
            //        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
            //        [request setValue:range forHTTPHeaderField:@"Range"];
            //
            //        self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
            
            
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
            
            //设置请求头（GET）
            NSString *range = [NSString stringWithFormat:@"bytes=%lld-",  [self getcurrentLength:taskidx]];
            [request setValue:range forHTTPHeaderField:@"Range"];
            
            
            self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
            
        }else{ //暂停
            DebugLog(@"%d pause",taskidx);
            [self.connection cancel];
            self.connection = nil;
        }
    });
}
-(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order
{
    [self add_downloadlog:@"Begin sync, please wait."];
    [self add_downloadlog:@"Prepare upload data."];
    //   NSArray* arr_order=[OLDataProvider enumOfflineOrder];
    NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order];
    
    NSString* upfile=upjson[@"file"];
    
    {
        NSData* data = [NSData dataWithContentsOfFile: upfile];
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        
        
        AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
        
        serializer.timeoutInterval=300;
        
        NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
        
        if(appDelegate.user!=nil)
            [params setValue:appDelegate.user forKey:@"user"];
        //    if(appDelegate.contact_id!=nil)
        //        [params setValue:appDelegate.contact_id forKey:@"contactId"];
        if(appDelegate.password!=nil)
            [params setValue:appDelegate.password forKey:@"password"];
        
        
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_OFFLINE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:data name:@"upfile" fileName:[upfile lastPathComponent] mimeType:@"application/zip"];
        } error:nil];
        
        
        
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        NSProgress *progress = nil;
        
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            
            
            
            if (error) {
                
                NSString* err_msg = [error localizedDescription];
                DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
                
                
                NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                
                DebugLog(@"data string: %@",str);
                [self add_downloadlog:err_msg];
                [self add_downloadlog:@"Can not connect to server please try again."];
                [self.settingUI onSyncFinish];
                
            } else {
                DebugLog(@"response ");
                
                
                
                NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
                
                // 再将NSData转为字符串
                NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                
                //            NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                
                DebugLog(@"data string: %@",jsonStr);
                
                NSDictionary* json = responseObject;
                
                
                if([[json valueForKey:@"result"] intValue]==2)
                {
                    [self add_downloadlog:@"Upload successful."];
                    appDelegate.disable_trigger=true;
                    NSString* so_id=[RAUtils arr2string:arr_order separator:@"," trim:true brackets:@"'"];
                    
                    [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
                    [iSalesDB execSql:@"delete from wishlist"];
                    [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
                    [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
                    [iSalesDB execSql:@"delete from offline_portfolio"];
                    [iSalesDB execSql:@"delete from offline_pdf"];
                    [OLDataProvider offline_clear_PDFCache];
                    
                    NSString* contactMap = json[@"contactMap"];
                    if(contactMap.length>0)
                    {
                        NSDictionary* contactjson = [RAUtils string2dict:contactMap];
                        NSArray *keys= [contactjson allKeys];
                        //遍历keys
                        for(int i=0;i<[keys count];i++)
                        {
                            //得到当前key
                            NSString *key=[keys objectAtIndex:i];
                            //如果key不是pic，说明value是字符类型，比如name：Boris
                            NSString* value = [contactjson valueForKey:key];
                            
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
                            [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];

                        }
                    }
                    //                    NSDictionary* contactjson= upjson[@"contact"];
                    //                    NSDictionary* wishlistjson= upjson[@"wishlist"];
                    //                    NSDictionary* orderjson= upjson[@"order"];
                    
                    appDelegate.disable_trigger=false;
                    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                    [defaults removeObjectForKey:@"Forcedownload"];
                    [defaults setBool:true forKey:@"Forcedownload"];
                    [defaults synchronize];
                    
                    [self download_offline:ver useInternalAddress:buseinternaladdress];
                    
                }
                else
                {
                    [self add_downloadlog:[json valueForKey:@"err_msg"]];
                    [self.settingUI onSyncFinish];
                }
                
                
            }
            //  [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
        }];
        
        
        
        
        
        
        
        [uploadTask resume];
        
    }
    
    
    
    return;
}
-(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
{
    NSString *plistPath = [RAUtils get_config_path];
    NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    if([config_list[@"NEED_FULLY_SYNC"] boolValue])
    {
        ver= nil;
        [self add_downloadlog:@"App required a fully sync."];
    }
    
    
    if(self.downloading)
        return;
    
    self.downloading=true;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        
        NSString*  pvid = [defaults stringForKey:@"vid"] ;
        
        
        
        [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
        
        NSMutableDictionary* json=[[iSalesNetwork  check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
        
        
        if([json[@"result"] intValue]!=2)
        {
            [self add_downloadlog:@"Can not get offline data version, please try again later."];
            [self.settingUI onSyncFinish];
            dispatch_async(dispatch_get_main_queue(), ^{
                //    self.downloadlog=nil;
                self.downloading=false;
            });
            return;
        }
        
        [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
        NSMutableDictionary* download_json=nil;
        
        //        NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
        NSString* downSerial=[json valueForKey:@"downSerial"];
        
        [defaults removeObjectForKey:@"downSerial"];
        [defaults setValue:downSerial forKey:@"downSerial"];
        
        [defaults synchronize];
        
        //                        sleep(3);
        //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
        
        
        //     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int count=0;
        //  __block bool preparing = true;
        while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
        {
            sleep(RETRY_DELAY);
            
            
            count++;
            download_json=[[iSalesNetwork  download_Offline:downSerial] mutableCopy];
            
            
            
            
        }
        
        //服务器准备数据完毕，进入处理数据逻辑。
        if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
        {
            [self add_downloadlog:@"Can not get offline data version, please try again later."];
            dispatch_async(dispatch_get_main_queue(), ^{
                //                self.downloadlog=nil;
                self.downloading=false;
            });
            [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
            [self.settingUI onSyncFinish];
            return;
            //一直没取到json，出错处理
        }
        else
        {
            if([download_json[@"count"] intValue]==0)
            {
                //没有找到更新包，当前是最新版本
                [self add_downloadlog:@"You are up-to-date!"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //                    self.downloadlog=nil;
                    self.downloading=false;
                });
                [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
                [self.settingUI onSyncFinish];
                return;
            }
            else
            {
                [self add_downloadlog:@"Find a new version, downloading..."];
                self.download_task = [download_json mutableCopy];
                //  self.download_task[@"abcdef"]=@"abcdef";
                long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
                [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
                [self download_offline:true checkdiskspace:true];
                return;
            }
            
        }
        
    });
}
-(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
{
    
    
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    bool forcedownload = [defaults boolForKey:@"Forcedownload"];
    
    if(forcedownload|| ver==nil)
    {
        [self download_offline:ver useInternalAddress:buseinternaladdress];
        SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
        syncVC.action_string=@"Download";
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
        
        
        
        
        
        //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
        
        navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
        [parent presentViewController:navi animated:YES completion:^{
            
            //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
            
            DebugLog(@"about present.........");
            
            //   self.btop = false;
            //  <#code#>
        }];

    }
    else
    {
        NSArray* arr_order=nil;
        arr_order=[OLDataProvider enumOfflineOrder];
        
//        if(arr_order.count>0)
//        {
//            
//            {
//                SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
//                vc.returnValue = ^(NSArray* SelectedOrder){
//                    
//                    [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
//                    SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
//                    syncVC.action_string=@"Download";
//                    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
//                    
//                    
//                    
//                    
//                    
//                    //    [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
//                    
//                    navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
//                    [parent presentViewController:navi animated:YES completion:^{
//                        
//                        //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
//                        
//                        DebugLog(@"about present.........");
//                        
//                        //   self.btop = false;
//                        //  <#code#>
//                    }];
//                };
//                
//                UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
//                
//                
//                
//                
//                
//                
//                navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
//                [parent presentViewController:navi animated:YES completion:^{
//                    
//                    
//                }];
//            }
//            
//            
//        }
//        else
        {
            [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order];
            SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
            syncVC.action_string=@"Download";
            UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
            navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态，自己看看是哪种
            [parent presentViewController:navi animated:YES completion:^{
                
                //        navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
                
                DebugLog(@"about present.........");
                
                //   self.btop = false;
                //  <#code#>
            }];
        }
        
    }
    
    
    
    
    
    
    
}
-(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
{
    if(start)
    {
        [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
        
        long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
        //        [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
        long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
        long long needsize = size+500;
        if(needsize>freespace &&checkdiskspace)
        {
            //size not enough.
            NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
            
            [self add_downloadlog:space];
            [self.settingUI onSyncFinish];
            
            
            return ;
        }
        
        NSString* temp = NSTemporaryDirectory();
        
        
        NSString * ver = self.download_task[@"ver"];
        
        NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
        
        //创建版本临时目录
        NSFileManager* fileManager = [NSFileManager defaultManager];
        BOOL bdir=YES;
        if(!  [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
        {
            
            NSError *error = nil;
            bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
            
            if(!bsuccess)
                DebugLog(@"Create temp folder failed");
            
            //        if(bsuccess)
            //        {
            //            sqlite3 *db = [self get_db];
            //
            //            [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
            //            [iSalesDB close_db:db];
            //        }
        }
        
        NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
        
        NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
        if(!  [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
        {
            
            NSError *error = nil;
            bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
            
            if(!bsuccess)
                DebugLog(@"Create cache folder failed");
            
        }
        
        
        NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
        
        NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
        //    if(!  [fileManager fileExistsAtPath:resource isDirectory:&bdir])
        //    {
        //
        //        NSError *error = nil;
        //        bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
        //
        //        if(!bsuccess)
        //            DebugLog(@"Create resource folder failed");
        //
        //    }
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
        NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
        
        NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
        //    tempdb=[documents stringByAppendingPathComponent:DBNAME];
        NSError *error = nil;
        bdir=NO;
        if(!  [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
        {
            //    [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
            
            if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
            {
                DebugLog(@"copy database failed");
            }
        }
        bdir=YES;
        error=nil;
        int count = [[self.download_task valueForKey:@"count"] intValue];
        bool alldone=true;
        bool trouble=false;
        bool response = false;
        for (int i = 0;i<count;i++)
        {
            NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
            NSString* url = [itemjson valueForKey:@"url"];
            NSString* type = [itemjson valueForKey:@"type"];
            
            NSString* status = itemjson[@"status"];
            //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
            if(! [status isEqualToString:@"finish"])
            {
                
                if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
                {
                    [self handle_download:url start:start  type:type taskid:i];
                    alldone=false;
                    break;
                }
                else
                {
                    alldone=false;
                    trouble=true;
                    response = [itemjson[@"response"] boolValue];
                    break;
                }
            }
            
        }
        if(trouble)
        {
            NSString* msg =@"offline sync got some trouble, sync canceled.";
            if(response==false)
            {
                msg=@"Cannot connect to server, please check your network.";
            }
            [self add_downloadlog:msg];
            dispatch_async(dispatch_get_main_queue(), ^{
                //        self.downloadlog=nil;
                self.downloading=false;
            });
            [self.settingUI onSyncFinish];
        }
        else if(alldone)
        {
            
            [self add_downloadlog:@"Finalizing download..."];
            //全部下载完成；
            //写入当前版本
            
            
            NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
            NSString* lastsync = [formatter stringFromDate:[NSDate date]];
            
            
            
            NSString* ver= self.download_task[@"ver"];
            
            
            
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *cachefolder = [paths objectAtIndex:0];
            NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
            //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
            
            if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
            {
                DebugLog(@"move image folder failed");
                [self add_downloadlog:@"move image folder failed"];
                trouble=true;
            }
            else
            {
                DebugLog(@"move image folder successful");
            }
            error=nil;
            
            
            // copy temp db to cache.
            if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
            {
                
                if(![fileManager removeItemAtPath:database_path error:nil])
                {
                    DebugLog(@"delete database failed");
                }
                else
                {
                    if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
                    {
                        DebugLog(@"copy database failed");
                        [self add_downloadlog:@"copy database failed"];
                        trouble=true;
                        
                    }
                    else{
                        BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
                        //     [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
                    }
                }
            }
            else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
            {
                DebugLog(@"copy database failed");
                BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
                [self add_downloadlog:@"copy database failed"];
                trouble=true;
            }
            
            //        if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
            //        {
            //            DebugLog(@"move db file failed");
            //        }
            //        else
            //        {
            //            DebugLog(@"move db file successful");
            //        }
            error=nil;
            if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
            {
                DebugLog(@"move data folder failed");
                [self add_downloadlog:@"move data folder failed"];
                trouble=true;
            }
            else
            {
                DebugLog(@"move data folder successful");
            }
            
            
            [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
            
            
            if(trouble)
            {
                [self add_downloadlog:@"offline sync failed."];
                // 尚缺更新失败还原逻辑。
            }
            else
            {
                [self add_downloadlog:@"offline sync complete."];
                
                
                NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
                [defaults removeObjectForKey:@"OfflineVer"];
                [defaults setValue:ver forKey:@"OfflineVer"];
                [defaults removeObjectForKey:@"LastSync"];
                [defaults setValue:lastsync forKey:@"LastSync"];
                [defaults removeObjectForKey:@"vid"];
                [defaults setValue:self.vid forKey:@"vid"];
                [defaults removeObjectForKey:@"Forcedownload"];
                NSString * downSerial = [defaults valueForKey:@"downSerial"];
                [defaults removeObjectForKey:@"downSerial"];
                [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
                [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
                [defaults synchronize];
                
                NSString *plistPath = [RAUtils get_config_path];
                NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
                if([config_list[@"NEED_FULLY_SYNC"] boolValue])
                {
                    config_list[@"NEED_FULLY_SYNC"] = @"false";
                    [config_list writeToFile:plistPath atomically:YES];
                }
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    
                    
                    NSDictionary* editor_json = [iSalesNetwork finish_download_Offline:downSerial];
                    

                });
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //        self.downloadlog=nil;
                self.downloading=false;
                self.download_task=nil;
                self.vid=nil;
                
                
                [self.settingUI onSyncFinish];
            });
        }
    }
    else
    {
        int count = [[self.download_task valueForKey:@"count"] intValue];
        for (int i = 0;i<count;i++)
        {
            NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
            NSString* url = [itemjson valueForKey:@"url"];
            NSString* type = [itemjson valueForKey:@"type"];
            
            NSString* status = itemjson[@"status"];
            //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
            if(! [status isEqualToString:@"finish"])
            {
                
                if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
                {
                    [self handle_download:url start:start  type:type taskid:i];
                    
                    break;
                }
                
            }
            
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.downloading=false;
        });
    }
}
-(void) add_downloadlog:(NSString*) newtext
{
    //    if(!self.downloading)
    //        return;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* date;
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
        date = [formatter stringFromDate:[NSDate date]];
        
        
        if(newtext.length<=0)
            return;
        NSString* text = self.downloadlog;
        if(text.length==0)
            text=@"";
        text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
        self.downloadlog = text;
        
        
        [self.settingUI onLogUpdate];
    });
}
-(int)unpack
{
    
    //return;
    
    //DebugLog(_fileName);
    ///Users/Ray/Library/Developer/CoreSimulator/Devices/0852B217-599B-41C2-95BA-4755B02B7FA0/data/Containers/Data/Application/FC6AC5D0-2ADF-4A3B-935D-059078622031/Library/Caches/apache-tomcat-8.0.22.zip
    //文件路径
    //    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString* temp = NSTemporaryDirectory();
    
    NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
    
    [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
    
    NSString * ver = self.download_task[@"ver"];
    NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
    
    
    NSString *zipFile = [temp stringByAppendingPathComponent:location];
    ZipArchive* zip = [[ZipArchive alloc] init];
    
    // filename stringByDeletingPathExtension
    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //    NSString *cachefolder = [paths objectAtIndex:0];
    
    NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
    
    NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
    //
    //    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //    NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
    // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
    
    DebugLog(@"path: %@",unZipTo);
    if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
        BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
        if( NO==result )
        {
            //            int aaa=0;
            //解压失败
            long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
            if(freespace<=10)
            {
                return UNZIP_NO_SPACE;
            }
            [zip UnzipCloseFile];
            //文件损坏，删除文件重试
            
            
            NSFileManager* fileManager=[NSFileManager defaultManager];
            BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
            
            [fileManager removeItemAtPath:unZipTo error:nil];
            
            
            
            return UNZIP_FILE_DAMAGE;
            
            
            
        }
        else
        {
            [zip UnzipCloseFile];
            
            [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:zipFile error:nil];
            return UNZIP_SUCCESS;
            //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
            
            
        }
        //[zip UnzipCloseFile];
    }
    else
    {
        //打开文件失败，通常是文件路径有问题或密码错误。
        
        return UNZIP_OPEN_FAILED;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:zipFile error:nil];
    }
    // [zip release];
}
#pragma mark - NSURLConnectionDataDelegate

/**
 *请求失败
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    
    DebugLog(@"%d error message:%@",self.current_task,error);
    
    
    NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
    
    
    
    
    
    
    
    
    //    self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
    currenttask[@"status"] = @"pause";
    int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
    currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
    self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
    
    //    self.currentLength = 0;
    //    self.fileLength = 0;
    [self.fileHandle closeFile];
    self.fileHandle = nil;
    [self.connection cancel];
    self.connection = nil;
    
    [self download_offline:true checkdiskspace:false];
}
/**
 *接收到服务器的响应
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
    
    if (httpresponse.statusCode == 206) {//！！！断点续传的状态码为206
        
        
        DebugLog(@"%d begin",self.current_task);
        
        long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
        if (position>0) {
            //不需要创建文件；
            return;
        }
        
        //获取下载文件大小
        //        self.fileLength = response.expectedContentLength;
        NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
        currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
        
        
        //获取文件名
        //self.fileName = response.suggestedFilename;
        
        currenttask[@"fileName"] = response.suggestedFilename;
        currenttask[@"response"] = @"true";
        [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
        
        self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
        
        //文件路径
        NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
        
        NSString * ver = self.download_task[@"ver"];
        NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
        NSString *filePath = [temp stringByAppendingPathComponent:location];
        DebugLog(@"save to: %@",filePath);
        //创建一个空的文件到沙盒
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        
        //创建一个用来写数据的文件句柄
        self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    }else{
        
        //debug 这里缺少文件的情况还没处理
        
        [self.connection cancel];
        self.connection = nil;
        DebugLog(@"该文件不存在");
        [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
    }
    
}

/**
 *接收到服务器返回的数据（可能被调用多次）
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    
    //移动到文件末尾
    [self.fileHandle seekToEndOfFile];
    
    //写入数据到文件
    [self.fileHandle writeData:data];
    
    NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
    
    long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
    position += data.length;
    currenttask[@"position"] = [NSNumber numberWithLongLong:position];
    
    
    self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
    
    //更新画面中的进度
    int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
    
    
    
    
    
    double progress = (double)position/fileLength;
    
    self.file_progress = progress;
    [self.settingUI onProgressUpdate];
}

/**
 *服务器返回数据完了
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
    
    
    
    
    [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
    
    DebugLog(@"%d finish",self.current_task);
    currenttask[@"position"] = [NSNumber numberWithLongLong:0];
    
    self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
    //    self.currentLength = 0;
    //    self.fileLength = 0;
    [self.fileHandle closeFile];
    self.fileHandle = nil;
    int result=[self unpack];
    NSString* temp = NSTemporaryDirectory();
    
    NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
    
    
    
    NSString * ver = self.download_task[@"ver"];
    
    NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
    
    NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
    
    switch (result) {
        case UNZIP_FILE_DAMAGE:
        {
            NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
            currenttask[@"status"] = @"pause";
            int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
            currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
            self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
            
            //    self.currentLength = 0;
            //    self.fileLength = 0;
            [self.fileHandle closeFile];
            self.fileHandle = nil;
            [self.connection cancel];
            self.connection = nil;
            break;
        }
        case UNZIP_SUCCESS:
        {
            NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
            
            if([type isEqualToString:@"img"])
            {
                
                NSString* parent_path = self.download_task[@"path"];
                if(parent_path.length==0)
                    parent_path=@"";
                parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
                parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
                NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
                
                
                
                NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
                
                BOOL bdir=YES;
                NSError *error = nil;
                if(!  [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
                {
                    
                    bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
                    
                    if(!bsuccess)
                        DebugLog(@"Create temp folder failed");
                }
                
                error=nil;
                //                NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
                //                NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
                
                //                NSError *error = nil;
                //                NSURL* uf=[NSURL fileURLWithPath:imagecache];
                //               if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
                //                               withItemAtURL:[NSURL fileURLWithPath:unZipTo]
                //                              backupItemName:backup
                //                                     options:NSFileManagerItemReplacementWithoutDeletingBackupItem
                //                            resultingItemURL:nil error:&error])
                if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
                    //   if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、     cenPath 为目标路径
                {
                    DebugLog(@"move image folder failed");
                }
                else
                {
                    currenttask[@"status"] = @"finish";
                    DebugLog(@"move image folder successful");
                }
                
            }
            else if([type isEqualToString:@"sql"])
            {
                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                NSString * ver = self.download_task[@"ver"];
                NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
                tempdb=[temp stringByAppendingPathComponent:tempdb];
                sqlite3* tdb=[iSalesDB get_db_at:tempdb];
                
                
                [self add_downloadlog:@"updating local database..."];
                
                
                @try {
                    char *errmsg=NULL;
                    appDelegate.disable_trigger=true;
                    if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
                    {
                        
                        sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;offline_pdf;", NULL, NULL, &errmsg);
                        
                        sqlite3_free(errmsg);
                        DebugLog(@"开启事务");
                        NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
                        
                        NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
                        int count = [orderjson[@"count"] intValue];
                        for(int i=0;i<count;i++)
                        {
                            NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
                            NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
                            NSError *error = nil;
                            NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
                            //DebugLog(@"NSString类方法读取的内容是：\n%@",content);
                            
                            
                            
                            
                            if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
                            {
                                //throw exception;
                                if(errmsg==nil)
                                    errmsg="Unknown error.";
                                NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
                                [NSException raise:@"offline update sql error" format:@"FILE:%@  MSG:%@",sqlfile,nsmsg];
                            }
                            
                            sqlite3_free(errmsg);
                        }
                        
                        
                        sqlite3_exec(tdb, "CREATE TRIGGER  if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty();  UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER  if not exists wishlist_update after update on wishlist BEGIN select offline_dirty();  UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER  if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty();  UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER  if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty();  UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER  if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty();  UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER  if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty();  UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
                    }
                    //提交事务
                    if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
                        
                        DebugLog(@"提交事务");
                        
                        sqlite3_free(errmsg);
                    }
                    
                    [self add_downloadlog:@"updating local database successful"];
                    currenttask[@"status"] = @"finish";
                    
                }
                
                
                @catch (NSException *exception) {
                    char *errmsg=NULL;
                    [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
                    [self add_downloadlog:@"updating local database failed rollback..."];
                    if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
                        DebugLog(@"回滚事务");
                        
                        
                        
                        
                        
                        
                    }
                    else
                    {
                        [self add_downloadlog:@"rollback failed."];
                    }
                    
                    
                    NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
                    currenttask[@"status"] = @"pause";
                    //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
                    currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
                    self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
                    
                    //    self.currentLength = 0;
                    //    self.fileLength = 0;
                    [self.fileHandle closeFile];
                    self.fileHandle = nil;
                    [self.connection cancel];
                    self.connection = nil;
                    //break;
                }
                @finally {
                    
                    appDelegate.disable_trigger=false;
                    sqlite3_close(tdb);
                    // [iSalesDB close_db:tdb];
                    //  [self SelectData];
                }
                
            }
            else if([type isEqualToString:@"script"])
            {
                currenttask[@"status"] = @"finish";
            }
            else if([type isEqualToString:@"resource"])
            {
                currenttask[@"status"] = @"finish";
            }
            int c=self.current_task+1;
            double t=[ self.download_task[@"count"] doubleValue];
            double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
            self.overall_progress = oprogress;
            [self.settingUI onProgressUpdate];
            break;
        }
        case UNZIP_NO_SPACE:
        {
            [self add_downloadlog:@"Disk space not enough."];
            
            break;
        }
        case UNZIP_OPEN_FAILED:
        {
            [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
            break;
        }
        default:
            break;
    }
    [self download_offline:true checkdiskspace:false];
}
#pragma mark - Scaner
-(void)onTimer: (NSTimer*)theTimer{
    if(theTimer==ScanApiConsumer){
        
        //  [self addlog:@"ScanApi::doScanApiReceive:"];
        [ScanApi doScanApiReceive];
    }
}
-(void) addlog:(NSString*) newtext
{
    if(!self.enable_ScannerLog)
        return;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* date;
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
        date = [formatter stringFromDate:[NSDate date]];
        
        
        if(newtext.length<=0)
            return;
        NSString* text = self.log;
        if(text.length==0)
            text=@"";
        text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
        self.log = text;
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onLogUpdate];
    });
}
- (void)enableScanner:(bool)enable {
    
    [self addlog:@"Enable scanner:"];
    
    if(enable)
    {
        [self addlog:@"Enable"];
        
        self.api_Status =  API_INIT;
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        self.Status_Text = @"Initialize...";
        [avc onStatusChanged:@"Initialize..."];
        [ScanApi open];
        [self addlog:@"ScanApi open"];
        
        ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
        [self addlog:@"ScanApiConsumer init"];
        
        //        [ScanApi close];
        //        [self addlog:@"ScanApi opent"];
    }
    else
    {
        [self addlog:@"Disable"];
        
        
        //        [ScanApiConsumer invalidate];
        //        ScanApiConsumer= nil;
        //        [self addlog:@"ScanApiConsumer invalidate"];
        
        
        self.api_Status =  API_CLOSING;
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        self.Status_Text = @"Stoping...";
        [avc onStatusChanged:@"Stoping..."];
        [ScanApi close];
        
        
        [self addlog:@"ScanApi close"];
        
        
    }
}

#pragma mark - Device Info List management
-(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
    
    [self addlog:@"updateDevicesList:"];
    
    if(add==YES){
        [self.devices addObject:deviceInfo];
    }
    else{
        [self.devices removeObject:deviceInfo];
    }
    
    NSMutableString* temp=[[NSMutableString alloc]init];
    for (DeviceInfo* info in self.devices) {
        [temp appendString:[info getName]];
        [temp appendString:@"\n"];
    }
    if(self.devices.count>0)
        [temp appendString:@"ready to scan"];
    else
        [temp appendString:@"Waiting for Scanner..."];
    
    
    // _Status.text=temp ;
    [self addlog:temp];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    self.Status_Text = temp;
    [avc onStatusChanged:temp];
    [avc OnUpdateDevicesList];
    
    // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
    // [self.dev_table reloadData];
    
}
#pragma mark - ScanApiHelper complete delegates
// THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
// TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
// IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
// CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
// THE SCANNER, THESE CALLBACKS CAN BE REMOVED

// callback received when the Get Symbology Status is completed
-(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
    [self addlog:@"onGetSymbologyDpm:"];
    
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
        if(deviceInfo!=nil){
            ISktScanSymbology* symbology=[[scanObj Property]Symbology];
            if([symbology getStatus]==kSktScanSymbologyStatusDisable){
                [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
            }
        }
    }
    else{
        // an error message should be displayed here
        // indicating that the DPM symbology status cannot be retrieved
    }
}

// callback received when the Set Symbology Status is completed
-(void)onSetSymbology:(ISktScanObject*)scanObj{
    [self addlog:@"onSetSymbology:"];
    
    SKTRESULT result=[[scanObj Msg]Result];
    if(!SKTSUCCESS(result)){
        // display an error message saying a symbology cannot be set
    }
}

/**
 *
 */
-(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
    
    [self addlog:@"onSetDataConfirmationMode:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        
        [self addlog:@"DataConfirmation Mode OK"];
        
    }
    else{
        [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
    }
}


/**
 *
 */
-(void) onDataConfirmation:(ISktScanObject*)scanObj{
    [self addlog:@"onDataConfirmation:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Data Confirmed OK"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
    [self addlog:@"onSetLocalDecodeAction:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Local Decode Action OK"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
    }
}

/**
 *
 */
-(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        ISktScanProperty* property=[scanObj Property];
        
        [self addlog:@"SoftScan status:"];
        if([property getByte]==kSktScanEnableSoftScan){
            [self addlog:@"SoftScan is ENABLED"];
            _softScannerEnabled=TRUE;
        }
        else{
            _softScannerEnabled=FALSE;
            [self addlog:@"SoftScan is DISABLED"];
        }
        
        
    }
    else{
        [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
    [self addlog:@"onSetSoftScanStatus:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"SoftScan set status success"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onSetTrigger:(ISktScanObject*)scanObj{
    [self addlog:@"onSetTrigger:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Trigger set success"];
    }
    else{
        
        
        [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
    }
}

/**
 *
 */
-(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
    [self addlog:@"onGetScanApiVersion:"];
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result))
    {
        ISktScanProperty*property=[scanObj Property];
        if([property getType]==kSktScanPropTypeVersion)
        {
            scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
                            [[property Version]getMajor],
                            [[property Version]getMiddle],
                            [[property Version]getMinor],
                            [[property Version]getBuild]];
        }
    }
    else{
        scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
    }
    
    
    [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
}

/**
 *
 */
#ifdef USE_SOFTSCAN
-(void) onSetOverlayView:(ISktScanObject*)scanObj{
    SKTRESULT result=[[scanObj Msg]Result];
    if(SKTSUCCESS(result)){
        [self addlog:@"Overlay view set success"];
    }
    else{
        [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
        
        
    }
}
#endif
/**
 * called each time a device connects to the host
 * @param result contains the result of the connection
 * @param newDevice contains the device information
 */
-(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
    [self addlog:@"onDeviceArrival:"];
    
    [self updateDevicesList:deviceInfo Add:YES];
    
    
#ifdef USE_SOFTSCAN
    // if the scanner is a SoftScan scanner
    if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
        //  _softScannerTriggerBtn.hidden=NO;
        _softScanDeviceInfo=deviceInfo;
        if(_deviceInfoToTrigger==nil)
            _deviceInfoToTrigger=deviceInfo;
        NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
        [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
        [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
    }
    else
#endif
    {
        if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
            //            _softScannerTriggerBtn.hidden=NO;
            _deviceInfoToTrigger=deviceInfo;
        }
        if(_doAppDataConfirmation==YES){
            // switch the comment between the 2 following lines for handling the
            // data confirmation beep from the scanner (local)
            // if none is set, the scanner will beep only once when SingleEntry actually
            // confirm the decoded data, otherwise the scanner will beep twice, one locally,
            // and one when SingleEntry will confirm the decoded data
            [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
            
            //        [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
        }
        
        // for demonstration only, let's make sure the DPM is enabled
        // first interrogate the scanner to see if it's already enabled
        // and in the onGetSymbologyDpm callback, if the DPM is not already set
        // then we send a Symbology property to enable it.
        [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
    }
    
    
}


/**
 * called each time a device disconnect from the host
 * @param deviceRemoved contains the device information
 */
-(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
    
    [self addlog:@"onDeviceRemoval:"];
    [self updateDevicesList:deviceRemoved Add:NO];
    if(_deviceInfoToTrigger==deviceRemoved){
        _deviceInfoToTrigger=nil;
    }
#ifdef USE_SOFTSCAN
    if(_softScanDeviceInfo==deviceRemoved){
        _softScanDeviceInfo=nil;
    }
    if(_deviceInfoToTrigger==nil)
        _deviceInfoToTrigger=_softScanDeviceInfo;
#endif
    if(_deviceInfoToTrigger==nil){
        //        _softScannerTriggerBtn.hidden=YES;
    }
}

/**
 * called each time ScanAPI is reporting an error
 * @param result contains the error code
 */
-(void) onError:(SKTRESULT) result{
    [self addlog:@"onError:"];
    
    [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
    
    //   _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
    
}

/**
 * called each time ScanAPI receives decoded data from scanner
 * @param deviceInfo contains the device information from which
 * the data has been decoded
 * @param decodedData contains the decoded data information
 */
-(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    
    [self addlog:@"onDecodedDataResult:"];
    //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    if(SKTSUCCESS(result)){
        
        
        NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onDecodedData:cleanString];
        //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
        [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
        if(_doAppDataConfirmation==YES){
            [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
        }
    }
}

-(void) test_onDecodedDataResult:(NSString*) value
{
    
    [self addlog:@"onDecodedDataResult:"];
    //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
    if(true){
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onDecodedData:value];
        //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
        [self addlog:value];
        //        if(_doAppDataConfirmation==YES){
        //            [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
        //        }
    }
}
-(void) didRotated
{
    
}


/**
 * called when ScanAPI initialization has been completed
 * @param result contains the initialization result
 */
-(void) onScanApiInitializeComplete:(SKTRESULT) result{
    
    [self addlog:@"onScanApiInitializeComplete:"];
    
    if(SKTSUCCESS(result))
    {
        self.api_Status =  API_START;
        
        NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
        [self addlog:strlog];
        
#ifdef USE_SOFTSCAN
        // make sure we support SoftScan
        [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
        
        // check if SoftScan is enabled
        [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
#else
        // disable support SoftScan (Default, not really needed if it was never activated)
        [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
#endif
        
        // ask for ScanAPI version (not a requirement but always nice to know)
        [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
        
        // configure ScanAPI for doing App Data confirmation,
        // if TRUE then SingleEntry will confirm the decoded data
        if(_doAppDataConfirmation==YES){
            [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
        }
        
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onStatusChanged:@"Waiting for scanner..."];
        self.Status_Text = @"Waiting for scanner...";
        //   _Status.text=@"Waiting for scanner...";
    }
    else{
        ActiveViewController* avc=(ActiveViewController*)self.active_controller;
        [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
        self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
        [self addlog:strlog];
    }
}

/**
 * called when ScanAPI has been terminated. This will be
 * the last message received from ScanAPI
 */
-(void) onScanApiTerminated{
    
    [self addlog:@"onScanApiTerminated:"];
    
    
    [ScanApiConsumer invalidate];
    ScanApiConsumer= nil;
    [self addlog:@"ScanApiConsumer invalidate"];
    
    self.api_Status =  API_STOP;
    
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onStatusChanged:@"Off"];
    self.Status_Text =@"Off";
    //   _Status.text = @"Off";
    
}

/**
 * called when an error occurs during the retrieval
 * of a ScanObject from ScanAPI.
 * @param result contains the retrieval error code
 */
-(void) onErrorRetrievingScanObject:(SKTRESULT) result{
    
    [self addlog:@"onErrorRetrievingScanObject:"];
    [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
    //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
    ActiveViewController* avc=(ActiveViewController*)self.active_controller;
    [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
}



-(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
{
    PDFViewController *ViewController = [self.main_vc.storyboard instantiateViewControllerWithIdentifier:@"PDFViewController"];
    ViewController.url = url;
    ViewController.canSave = false;
    
    
    
    ViewController.mail_content = content;
    
    
    if(soid==nil)
        soid =@"";
    
    if(company==nil)
        company =@"";
    
    
    ViewController.save_name =soid;
    
    
    
    
    NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
    if(send_to.length>0)
    {
        arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
        //                            customer_email compo
        //                            [send_to addObject:customer_email];
    }
    ViewController.mail_to = arrsend_to;
    
    NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from NEW PACIFIC DIRECT,INC.",company,soid];//[arr_subject componentsJoinedByString:@" : "];
    
    ViewController.mail_subject = subject;
    
    
    
    //    NSString* subject;
    //                    if (company.length==0) {
    
    //    NSString* cur_time =[RAUtils current_date];
    //   subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
    
    //    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    //    NSString* customer_email=    [appDelegate.customerInfo valueForKey:@"customer_email"];
    //
    //
    //    NSMutableArray* send_to = [[NSMutableArray alloc]init];
    //    if(customer_email.length>0)
    //    {
    //        send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
    //        //                            customer_email compo
    //        //                            [send_to addObject:customer_email];
    //    }
    //    ViewController.mail_to = send_to;
    
    //                    }
    //                    else
    //                    {
    //                        subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
    //                    }
    //    ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
    //    ViewController.mail_subject = subject;
    ViewController.autoPrint=true;
    ViewController.hidenavi = false;
    [self.main_vc.navigationController pushViewController:ViewController animated:YES];
    //  [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
    
    
}

@end
