//
//  TearSeetParamViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 11/11/15.
//  Copyright © 2015 United Software Applications, Inc. All rights reserved.
//

#import "TearSheetParamViewController.h"
#import "iSalesNetwork.h"
#import "PDFViewController.h"
#import "MainViewController.h"
#import "Singleton.h"

@interface TearSheetParamViewController ()

@end

@implementation TearSheetParamViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector(onCloseClick:)];
    //[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
    //    closeButton.title = @"Close";
  //  closeButton.tintColor = UIColorFromRGB(0x996633);
    self.navigationItem.leftBarButtonItem = closeButton;
    
    
    
    UIBarButtonItem *previewbtn = nil;//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSaveClick:)];
    
    previewbtn = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"preview"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                  style:UIBarButtonItemStylePlain
                                                 target:self
                                                 action:@selector(onPreviewClick:)];
    
  //  previewbtn.tintColor = UIColorFromRGB(0x996633);
    
    UIBarButtonItem *savebtn = nil;//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSaveClick:)];
    
    savebtn = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"save"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(onSaveClick:)];
    
  //  savebtn.tintColor = UIColorFromRGB(0x996633);
    _savebtn = savebtn;
    
    
    UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedItem.width = 0.0f;
    
    NSMutableArray * items = [[NSMutableArray alloc]init];
    
    [items addObject:previewbtn];
    [items addObject:fixedItem];
    [items addObject:savebtn];
    
    //        [items addObject:item2];
    self.navigationItem.rightBarButtonItems=items;
    
    
    
    //    self.navigationItem.rightBarButtonItem = previewbtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)onCloseClick:(UIButton *)sender {
    [self.navigationController dismissViewControllerAnimated:true completion:^{
        ;
    }];
}
- (void)onPreviewClick:(UIButton *)sender {
    
    // add params check here.
    [self.lastedit endEditing:true];
    [self.lasttextview endEditing:true];
    

//    self.cancommit=true;
//    NSMutableDictionary* upparams=[[NSMutableDictionary alloc] init];
//    //  [upparams setValue:[self.params valueForKey:@"cart2Checkbox"] forKey:@"cart2Checkbox"];
//    int section_count=[[self.content_data_download valueForKey:@"section_count"] intValue];
//    for(int i=0;i<section_count;i++)
//    {
//        NSMutableDictionary * sectionjson = [[self.content_data_download objectForKey:[NSString stringWithFormat:@"section_%d",i ]] mutableCopy];
//        int item_count = [[sectionjson valueForKey:@"count"] intValue];
//        for(int j=0;j<item_count;j++)
//        {
//            NSMutableDictionary * itemjson=[[sectionjson objectForKey:[NSString stringWithFormat:@"item_%d",j ]] mutableCopy];
//            NSString* key = [itemjson valueForKey:@"name"];
//            if(key==nil || key.length==0)
//                continue;
//            if([[itemjson valueForKey:@"control"] isEqualToString:@"enum"])
//            {
//                NSString* single_select = [itemjson valueForKey:@"single_select"];
//                if([single_select isEqualToString:@"true"])
//                {
//                    NSDictionary* cadejson=[itemjson objectForKey:@"cadedate"];
//                    int count = [[cadejson valueForKey:@"count"] intValue];
//                    bool setvalue = false;
//                    for(int cc=0;cc<count;cc++)
//                    {
//                        NSDictionary* valjson=[cadejson objectForKey:[NSString stringWithFormat:@"val_%d",cc]];
//                        if([[valjson valueForKey:@"check"]intValue]==1)
//                        {
//                            [upparams setValue:[valjson valueForKey:@"value_id"] forKey:[itemjson valueForKey:@"name"]];
//                            setvalue=true;
//                            break;
//                        }
//                    }
//                    if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] && setvalue==false)
//                    {
//                        self.cancommit = false;
//                    }
//                }
//                else
//                {
//                    //not support multi select for now;
//                }
//                /*
//                 upparams setValue:itemjson forKey:<#(NSString *)#>
//                 
//                 */
//            }else
//                if([[itemjson valueForKey:@"control"] isEqualToString:@"action"])
//                {
//                    if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] && [itemjson objectForKeyedSubscript:@"data"]==nil)
//                        self.cancommit = false;
//                }
//                else if([[itemjson valueForKey:@"control"] isEqualToString:@"switch"])
//                {
//                    NSString* valuestr = [itemjson valueForKey:@"value"];
//                    [upparams setValue:valuestr forKey:[itemjson valueForKey:@"name"]];
//                    
//                    NSString* value = [itemjson valueForKey:@"value"];
//                    NSMutableDictionary* boolitem=nil;
//                    NSMutableDictionary* subjson=nil;
//                    if([value isEqualToString:@"true"])
//                    {
//                        boolitem =[[itemjson objectForKey:@"true"] mutableCopy];
//                        
//                    }
//                    else
//                    {
//                        boolitem =[[itemjson objectForKey:@"false"] mutableCopy];
//                        
//                    }
//                    subjson=[[boolitem objectForKey:@"sub_item"] mutableCopy];
//                    if( subjson!=nil /*&& !active*/)
//                    {
//                        int sub_count = [[subjson valueForKey:@"count"] intValue];
//                        for(int l=0;l<sub_count;l++)
//                        {
//                            NSMutableDictionary * modify_item=[[subjson objectForKey:[NSString stringWithFormat:@"item_%d",l ]] mutableCopy];
//                            
//                            
//                            
//                            
//                            if([modify_item valueForKey:@"value"]!=nil && ![[modify_item valueForKey:@"value"]isEqualToString:@""])
//                                [upparams setValue:[modify_item valueForKey:@"value"] forKey:[modify_item valueForKey:@"name"]];
//                            else
//                            {
//                                if([[modify_item valueForKey:@"required"] isEqualToString: @"true"] )
//                                    self.cancommit = false;
//                            }
//                        }
//                        
//                        
//                        
//                    }
//                }
//                else
//                {
//                    if([itemjson valueForKey:@"value"]!=nil && ![[itemjson valueForKey:@"value"]isEqualToString:@""])
//                        [upparams setValue:[itemjson valueForKey:@"value"] forKey:[itemjson valueForKey:@"name"]];
//                    else
//                    {
//                        if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] )
//                            self.cancommit = false;
//                    }
//                }
//            upparams= [self subitem_param:itemjson addto:upparams ];
//        }
//    }
//    if(self.cancommit==false)
//    {
////        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Some requried field is missing" message:@"Fields with * mark cannot be empty." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
////        //UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
////        [alert show];
//        
//        
//        [RAUtils alert_view:@"Fields with * mark cannot be empty." title:@"Some Requried Fields Are Missing."];
//        self.content_data_control = [self translate_json:self.content_data_download changed:self.changed_data];
//        //DebugLog(@"CONTENT translate:%@",[iSalesNetwork DataTOjsonString:self.content_data]);
//        //[self.editorTable reloadData ];
//        [self.editorTable reloadData];
//        return;
//    }
    NSMutableDictionary* upparams = [self check_cancommit:true];
    if(self.cancommit==false)
        return;
    
    NSMutableString* pdf_url = [[self.content_data_download valueForKey:@"pdf_url"] mutableCopy];
    
  //  DebugLog([RAUtils dict2string:self.content_data_download]);
    
    bool bremove=false;
    
    NSString* catelog_name= nil;
        NSString* internal_note= nil;
    NSArray *keys= [upparams allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        if([key isEqualToString:@"remove_item"])
        {
            bremove=[[upparams valueForKey:key]boolValue];
            continue;
        }
        
        
        
        if([key isEqualToString:@"catalog_name"])
        {
            catelog_name=[upparams valueForKey:key];
            
        }
        if([key isEqualToString:@"internal_note"])
        {
            internal_note=[upparams valueForKey:key];
            
        }
        
        
        [pdf_url appendString:@"&"];
        
        [pdf_url appendString:key];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        NSString* valuefrom = [upparams valueForKey:key];
        
        valuefrom = [NSString stringWithFormat:@"%@",valuefrom];
        
        [pdf_url appendString:@"="];
        
        
        
        
        [pdf_url appendString:[valuefrom stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        //    NSString* value=[self getValue:valuefrom];
        
        //    [ret setValue:value forKey:valuefrom];
    }
    
    upparams[@"pdfUrl"]=pdf_url;
    
    upparams[@"product_ids"]=self.product_ids;
    upparams[@"item_ids"]=self.item_ids;
    
    //   pdf_url=[pdf_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    
    
    UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Processing"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary* editor_json = [iSalesNetwork request_TearSheet:upparams];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
            
            
            if([[editor_json valueForKey:@"result"] intValue]==2)
            {
                //                    NSMutableDictionary * customerInfo=[self create_cusromer_info_from_table];
                
                AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                
                NSString* url = [editor_json valueForKey:@"pdf_path"];
                NSString* path = [editor_json valueForKey:@"pdf_real_path"];
                bool isLocalFile = [[editor_json valueForKey:@"isLocalFile"] boolValue];
                PDFViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PDFViewController"];
                ViewController.url = url;
                ViewController.canSave = true;
                ViewController.isLocalfile=isLocalFile;
                //                    ViewController.mail_content = [self.content_data valueForKey:@"email_content"];
                
                ViewController.save_name =catelog_name;
                ViewController.save_note =internal_note;
                //ViewController.filename = catelog_name;
                NSString* company=    [appDelegate.customerInfo valueForKey:@"customer_name"];
                
                if(company==nil)
                    company=@"";
                //                    NSString* customer_email=    [appDelegate.customerInfo valueForKey:@"customer_email"];
                
                
                //                    NSMutableArray* send_to = [[NSMutableArray alloc]init];
                //                    if(customer_email.length>0)
                //                        [send_to addObject:customer_email];
                //                    ViewController.mail_to = send_to;
                
                
                
                //  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;
                
                NSString* subject;
                //                    if (company.length==0) {
                
       //         NSString* cur_time =[RAUtils current_date];
                subject =catelog_name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
                
                
                
                //                    }
                //                    else
                //                    {
                //                        subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
                //                    }
                ViewController.attachment_name = [NSString stringWithFormat:@"%@.pdf",catelog_name];//[NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
                ViewController.mail_subject = subject;
                
                //                    ViewController.onLoadSuccess =^(NSString* url)
                //                    {
                //
                //                    };
                
                
                ViewController.onSavePDF=^(NSString* name,NSString* file)
                {
                    
                    
                    NSString* del_ids = nil;
                    if(bremove)
                        del_ids=[self.params valueForKey:@"item_ids"];
                    
                    UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Saving..."];
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
                        
                        
                        if (appDelegate.offline_mode) {
                            [upparams setValue:url forKey:@"pdfPath"];
                        } else {
                            [upparams setValue:path forKey:@"pdfPath"];
                        }
                        [upparams setValue:name forKey:@"pdfName"];
                        [upparams setValue:internal_note forKey:@"pdfNote"];
                        [upparams setValue:del_ids forKey:@"itemIds"];
                        [upparams setValue:pdf_url forKey:@"configureParams"];
                        

                        
                        NSDictionary* json = [iSalesNetwork save_TearSheet:upparams];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                            
                            
                            if([[json valueForKey:@"result"] intValue]==2)
                            {
                                [RAUtils alert_view:nil title:@"Portfolio saved. You can find it from View Portfolios" ] ;
                                
                                [self.navigationController dismissViewControllerAnimated:true completion:^{
                                    [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
                                    [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:true];
                                    //                                            if(self.onDismiss)
                                    //                                                self.onDismiss(catelog_name);
                                }];
                            }
                            else
                            {
                                [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save Portfolio" controller:self] ;
                            }
                            
                        });
                    });
                    
                  
                    
                };
                
                //    ViewController. = self.function_name;
                //    ViewController.behavior =BEHAVIOR_SEARCH;
                ViewController.hidenavi = false;
                [self.navigationController pushViewController:ViewController animated:YES];
              //  [[self navigationController] setNavigationBarHidden:NO animated:NO];
                
                
                /*
                 if(self.return_url)
                 self.return_url(url,path,bremove);
                 [self.navigationController dismissViewControllerAnimated:true completion:^{
                 if(self.onDismiss)
                 self.onDismiss(catelog_name);
                 }];
                 */
                
            }
            else
            {
                [RAUtils message_alert:[editor_json valueForKey:@"err_msg"] title:@"Create Portfolio" controller:self] ;
            }
            
            
            
            
        });
    });
    
    
    
    
}
- (void)onSaveClick:(UIButton *)sender {
    
    // add params check here.
    [self.lastedit endEditing:true];
    [self.lasttextview endEditing:true];
//    self.cancommit=true;
//    NSMutableDictionary* upparams=[[NSMutableDictionary alloc] init];
//    //  [upparams setValue:[self.params valueForKey:@"cart2Checkbox"] forKey:@"cart2Checkbox"];
//    int section_count=[[self.content_data_download valueForKey:@"section_count"] intValue];
//    for(int i=0;i<section_count;i++)
//    {
//        NSMutableDictionary * sectionjson = [[self.content_data_download objectForKey:[NSString stringWithFormat:@"section_%d",i ]] mutableCopy];
//        int item_count = [[sectionjson valueForKey:@"count"] intValue];
//        for(int j=0;j<item_count;j++)
//        {
//            NSMutableDictionary * itemjson=[[sectionjson objectForKey:[NSString stringWithFormat:@"item_%d",j ]] mutableCopy];
//            NSString* key = [itemjson valueForKey:@"name"];
//            if(key==nil || key.length==0)
//                continue;
//            if([[itemjson valueForKey:@"control"] isEqualToString:@"enum"])
//            {
//                NSString* single_select = [itemjson valueForKey:@"single_select"];
//                if([single_select isEqualToString:@"true"])
//                {
//                    NSDictionary* cadejson=[itemjson objectForKey:@"cadedate"];
//                    int count = [[cadejson valueForKey:@"count"] intValue];
//                    bool setvalue = false;
//                    for(int cc=0;cc<count;cc++)
//                    {
//                        NSDictionary* valjson=[cadejson objectForKey:[NSString stringWithFormat:@"val_%d",cc]];
//                        if([[valjson valueForKey:@"check"]intValue]==1)
//                        {
//                            [upparams setValue:[valjson valueForKey:@"value_id"] forKey:[itemjson valueForKey:@"name"]];
//                            setvalue=true;
//                            break;
//                        }
//                    }
//                    if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] && setvalue==false)
//                    {
//                        self.cancommit = false;
//                    }
//                }
//                else
//                {
//                    //not support multi select for now;
//                }
//                /*
//                 upparams setValue:itemjson forKey:<#(NSString *)#>
//                 
//                 */
//            }else
//                if([[itemjson valueForKey:@"control"] isEqualToString:@"action"])
//                {
//                    if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] && [itemjson objectForKeyedSubscript:@"data"]==nil)
//                        self.cancommit = false;
//                }
//                else if([[itemjson valueForKey:@"control"] isEqualToString:@"switch"])
//                {
//                    NSString* valuestr = [itemjson valueForKey:@"value"];
//                    [upparams setValue:valuestr forKey:[itemjson valueForKey:@"name"]];
//                    
//                    NSString* value = [itemjson valueForKey:@"value"];
//                    NSMutableDictionary* boolitem=nil;
//                    NSMutableDictionary* subjson=nil;
//                    if([value isEqualToString:@"true"])
//                    {
//                        boolitem =[[itemjson objectForKey:@"true"] mutableCopy];
//                        
//                    }
//                    else
//                    {
//                        boolitem =[[itemjson objectForKey:@"false"] mutableCopy];
//                        
//                    }
//                    subjson=[[boolitem objectForKey:@"sub_item"] mutableCopy];
//                    if( subjson!=nil /*&& !active*/)
//                    {
//                        int sub_count = [[subjson valueForKey:@"count"] intValue];
//                        for(int l=0;l<sub_count;l++)
//                        {
//                            NSMutableDictionary * modify_item=[[subjson objectForKey:[NSString stringWithFormat:@"item_%d",l ]] mutableCopy];
//                            
//                            
//                            
//                            
//                            if([modify_item valueForKey:@"value"]!=nil && ![[modify_item valueForKey:@"value"]isEqualToString:@""])
//                                [upparams setValue:[modify_item valueForKey:@"value"] forKey:[modify_item valueForKey:@"name"]];
//                            else
//                            {
//                                if([[modify_item valueForKey:@"required"] isEqualToString: @"true"] )
//                                    self.cancommit = false;
//                            }
//                        }
//                        
//                        
//                        
//                    }
//                }
//                else
//                {
//                    if([itemjson valueForKey:@"value"]!=nil && ![[itemjson valueForKey:@"value"]isEqualToString:@""])
//                        [upparams setValue:[itemjson valueForKey:@"value"] forKey:[itemjson valueForKey:@"name"]];
//                    else
//                    {
//                        if([[itemjson valueForKey:@"required"] isEqualToString: @"true"] )
//                            self.cancommit = false;
//                    }
//                }
//            upparams= [self subitem_param:itemjson addto:upparams ];
//        }
//    }
//    if(self.cancommit==false)
//    {
////        UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @"Some requried field is missing" message:@"Fields with * mark can not be empty." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
////        //UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
////        [alert show];
//        
//        [RAUtils alert_view:@"Fields with * mark cannot be empty." title:@"Some Requried Fields Are Missing."];
//        self.content_data_control = [self translate_json:self.content_data_download changed:self.changed_data];
//        //DebugLog(@"CONTENT translate:%@",[iSalesNetwork DataTOjsonString:self.content_data]);
//        //[self.editorTable reloadData ];
//        [self.editorTable reloadData];
//        return;
//    }
    
    
    
    NSMutableDictionary* upparams = [self check_cancommit:true];
    if(self.cancommit==false)
        return;
    
    NSMutableString* pdf_url = [[self.content_data_download valueForKey:@"pdf_url"] mutableCopy];
    
//    DebugLog([RAUtils dict2string:self.content_data_download]);
    
    bool bremove=false;
    
    NSString* catelog_name= nil;
    NSString* internal_note = nil;
    NSArray *keys= [upparams allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        if([key isEqualToString:@"remove_item"])
        {
            bremove=[[upparams valueForKey:key]boolValue];
            continue;
        }
        
        
        
        if([key isEqualToString:@"catalog_name"])
        {
            catelog_name=[upparams valueForKey:key];
            
        }
        
        if([key isEqualToString:@"internal_note"])
        {
            internal_note=[upparams valueForKey:key];
            
        }
        
        [pdf_url appendString:@"&"];
        
        [pdf_url appendString:key];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        NSString* valuefrom = [upparams valueForKey:key];
        
        valuefrom = [NSString stringWithFormat:@"%@",valuefrom];
        
        [pdf_url appendString:@"="];
        
        
        
        
        [pdf_url appendString:[valuefrom stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        //    NSString* value=[self getValue:valuefrom];
        
        //    [ret setValue:value forKey:valuefrom];
    }
    
    upparams[@"product_ids"]=self.product_ids;
    upparams[@"item_ids"]=self.item_ids;
    
    __block NSString* saveName = catelog_name;
    
     __block NSString* saveNote = internal_note;
    NSString* del_ids = nil;
    if(bremove)
        del_ids=[self.params valueForKey:@"item_ids"];
    
    //   pdf_url=[pdf_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Save pdf" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //block代码块取代了delegate
    
    
    [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = saveName;
        
        
    }];
    
    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        
        UITextField *name = alertControl.textFields.firstObject;
        if(name.text.length==0)
        {
            [RAUtils message_alert:@"Cannot save without name. Save canceled." title:@"Name is missing" controller:self];
        }
        else
        {
            saveName = name.text;
            _savebtn.enabled =false;
            
            
            UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Processing"];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                
                [upparams setValue:pdf_url forKey:@"pdfUrl"];
                [upparams setValue:saveName forKey:@"pdfName"];
                [upparams setValue:del_ids forKey:@"itemIds"];
                [upparams setValue:saveNote forKey:@"pdfNote"];
                
                NSDictionary* editor_json = [iSalesNetwork direct_save_TearSheet:upparams];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
                    
                    
                    if([[editor_json valueForKey:@"result"] intValue]==2)
                    {
                        
                        
                        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                        
                     //   [RAUtils alert_view:nil title:@"Portfolio saved. You can find it from View Portfolios" ] ;
                        NSString* url = [editor_json valueForKey:@"pdf_path"];
                        bool isLocalFile = [editor_json valueForKey:@"isLocalFile"];
                        [self.navigationController dismissViewControllerAnimated:true completion:^{
                            [((MainViewController*)appDelegate.main_vc) reloadDocuments:true immediately:false];
                            [((MainViewController*)appDelegate.main_vc) reloadPortfolio:true immediately:true];
                            if(self.onSaved)
                                self.onSaved(url,saveName,isLocalFile);
                        }];
                        
                    }
                    else
                    {
                        [RAUtils message_alert:[editor_json valueForKey:@"err_msg"] title:@"Create Portfolio" controller:self] ;
                    }
                    
                    
                    
                    
                });
            });

        }
    }];
    
    UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        DebugLog(@"Cancel");
    }];
    [alertControl addAction:actionOne];
    
    [alertControl addAction:alertthree];
    
    //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
    
    
    [self presentViewController:alertControl animated:YES completion:nil];
    
    
    
    
    

    
    
    
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
