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

#import "PageViewController.h"

#import "config.h"
#import "const.h"

#import "SignatureListViewController.h"
#import "SignatureViewController.h"
#import "PDFUtils.h"
#import "ImageUtils.h"
#import "TextUtils.h"

#import "CheckSelectorViewController.h"
#import "DatePickerViewController.h"



//#import "TouchImageView.h"
@interface PageViewController ()

@end

@implementation PageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //   self.pageIndex=1;
    
    // self.pdfPageView.pageIndex=self.pageIndex;
    self.pdfPageView.pageRef= self.pageRef;
    
    [self initControl];
    
    //    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
    //                                                        initWithTarget:self
    //                                                        action:@selector(handlePinch:)];
    //
    //    [self.view addGestureRecognizer:pinchGestureRecognizer];
    
    // Do any additional setup after loading the view.
}
-(void) dealloc
{
 //   CFBridgingRelease(self.pageRef);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
//{
////    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
////    recognizer.scale = 1;
//
//    CGSize contentsize =self.pdfScrollView.contentSize;
//
//    self.pdfScrollView.contentSize = CGSizeMake(contentsize.width*recognizer.scale, contentsize.height*recognizer.scale);
//}


-(void) initControl
{
    int count = [self.controlTemplate[@"count"] intValue];
    for(int i=0;i<count;i++)
    {
        NSMutableDictionary * control =self.controlTemplate [[NSString stringWithFormat:@"control_%d",i] ];
        if([control[@"type"] isEqualToString:@"TextView"])
        {
            [self addTextView:control destView:self.editControlView index:i];
        }
        else if([control[@"type"] isEqualToString:@"Button"])
        {
            [self addButton:control destView:self.editControlView index:i];
            
        }
        else if([control[@"type"] isEqualToString:@"Check"])
        {
            [self addCheck:control destView:self.editControlView index:i];
            
        }
        else if([control[@"type"] isEqualToString:@"Signature"])
        {
            [self addSignatureButton:control destView:self.editControlView index:i];
            
        }
        else if([control[@"type"] isEqualToString:@"Image"])
        {
            [self addImage:control destView:self.editControlView index:i];
            
        }
        else if([control[@"type"] isEqualToString:@"Label"])
        {
            [self addLabel:control destView:self.editControlView index:i];
            
        }
        else if([control[@"type"] isEqualToString:@"DatePicker"])
        {
            [self addDatePicker:control destView:self.editControlView index:i];
            
        }
    }
    
}
#pragma mark add controls
-(bool) checkActionCondition:(NSString*) condition
{
    if([condition isEqualToString:@"true"])
        return true;
    if([condition isEqualToString:@"control_18:[value]==0"])
    {
        NSArray* arr= self.controlTemplate[@"control_18"][@"value"];
        if(arr.count==0)
            return false;
        else
            return [arr[0] intValue]==0;

    }
    
    return false;
}
-(UIView*) findControl:(NSString*)controlName
{

    controlName=[controlName stringByReplacingOccurrencesOfString:@"control_" withString:@""];
    int d_idx = [controlName intValue];
    return [self.view viewWithTag:d_idx+CONTROL_BASE];
}
-(void) addTextView:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UITextView* tv = [[UITextView alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    float fontsize = [template[@"size"] floatValue];
    if(fontsize==0)
        fontsize=10;
    [tv setFont:[UIFont systemFontOfSize:fontsize]];
    bool isdisable = [template[@"disable"] boolValue];
    
    tv.editable = !isdisable;
    tv.text =template[@"value"];
    
    tv.tag = index+ CONTROL_BASE;
    
    
    
    //UIColorFromARGB(0x4066ccff);
    
    tv.backgroundColor = UIColorFromRGB(TV_BG);//[UIColor lightGrayColor];
    //    tv.place
    //    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
    
    
    tv.delegate = self;
    //    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    if(DEBUG_PDFSIG)
    {

        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:tv];
}
-(void) addLabel:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    float fontsize = [template[@"size"] floatValue];
    if(fontsize==0)
        fontsize=10;
    [label setFont:[UIFont systemFontOfSize:fontsize]];
    
    label.text =template[@"value"];
    
    label.tag = index+ CONTROL_BASE;
    
    
    
    //UIColorFromARGB(0x4066ccff);
    
//    tv.backgroundColor = UIColorFromRGB(TV_BG);//[UIColor lightGrayColor];
    //    tv.place
    //    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
    
    
//    tv.delegate = self;
    //    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    if(DEBUG_PDFSIG)
    {
        
        [label setBackgroundColor:[UIColor grayColor]];
         
    }
    [destView addSubview:label];
}

-(void) addButton:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
    
        btn.tag = index+ CONTROL_BASE;
    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
    btn.backgroundColor = UIColorFromRGB(BT_BG);
    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    if(DEBUG_PDFSIG)
    {
       // btn.backgroundColor = [UIColor lightGrayColor];
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:btn];
}
-(void) addDatePicker:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    

    [btn setTitle:template[@"value"] forState:UIControlStateNormal];
    float fontsize = [template[@"size"] floatValue];
    if(fontsize==0)
        fontsize=10;
    btn.titleLabel.font = [UIFont systemFontOfSize: fontsize];
    btn.tag = index+ CONTROL_BASE;
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
    btn.backgroundColor = UIColorFromRGB(BT_BG);
    [btn addTarget:self action:@selector(ControlDatePickerClicked:) forControlEvents:UIControlEventTouchUpInside];
    if(DEBUG_PDFSIG)
    {
        // btn.backgroundColor = [UIColor lightGrayColor];
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:btn];
}
-(UIView*) createMarker:(int)size x:(int)x y:(int)y
{
    UIView* v=[[UIView alloc] initWithFrame:CGRectMake(x, y, size, size)];
    return v;
    
}
-(void) addCheck:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    
    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
        btn.tag = index+ CONTROL_BASE;
    [btn addTarget:self action:@selector(CheckButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIColor* marker_bg=UIColorFromRGB(CK_BG);//[UIColor clearColor];
    if(DEBUG_PDFSIG)
    {
        btn.backgroundColor = [UIColor lightGrayColor];

        [btn setTitle:template[@"title"] forState:UIControlStateNormal];
//        marker_bg = [UIColor redColor];
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:btn];
    NSArray* cadedate = template[@"cadedate"];
    
    NSArray* checkedData = self.controlTemplate [[NSString stringWithFormat:@"control_%d",index] ][@"value"];
    float fontsize = [template[@"size"] floatValue];
    if(fontsize==0)
        fontsize=10;

//    if(checkedData.count>0)
//        marker_bg = [UIColor clearColor];
//    else
        marker_bg=UIColorFromRGB(CK_BG);
    
    for(int i=0;i<cadedate.count;i++)
    {
        NSArray* item = cadedate[i];
        NSArray* checkmarker = item[1];
        if(checkmarker.count==0)
        {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont systemFontOfSize: fontsize];
            btn.backgroundColor = UIColorFromRGB(CK_BG);
            if([checkedData containsObject:[NSNumber numberWithLong:i]])
            {
                [btn setTitle:item[0][0] forState:UIControlStateNormal];
                
            }
            continue;
        }
        else
        {
            [btn setTitle:@"" forState:UIControlStateNormal];
        }
        UIView* marker=[self createMarker:[template[@"marker_size"] intValue] x:[item[1][0] intValue] y:[item[1][1] intValue]];
        
        marker.backgroundColor = marker_bg;
        marker.tag = CHECK_BASE+index*1000+i;
        
        
        if([checkedData containsObject:[NSNumber numberWithLong:i]])
        {
            
            marker.backgroundColor= UIColorFromRGB(CK_MK);
            
        }
        else
        {
            marker.backgroundColor= marker_bg;
        }
        
        [destView addSubview:marker];
        
    }
    
}
-(void) addSignatureButton:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    TouchImageView* btn = [[TouchImageView alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    
    btn.contentMode = UIViewContentModeScaleAspectFit;
    btn.delegate = self;
    btn.layer.borderColor = [UIColor clearColor].CGColor;
    btn.layer.borderWidth = 0;
        btn.tag = index+ CONTROL_BASE;
    
    NSString* file =template[@"value"];
    
    NSData* img_data=[ImageUtils load_img:file];
    
    if(img_data!=nil)
    {
        
        UIImage* image=[UIImage imageWithData:img_data];
        btn.image = image;
        
    }
    

    btn.backgroundColor = UIColorFromRGB(SIG_BG);

    if(DEBUG_PDFSIG)
    {
        
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:btn];
}
-(void) addImage:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
{
    UIImageView* btn = [[UIImageView alloc] initWithFrame:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue])];
    
    btn.contentMode = UIViewContentModeScaleAspectFit;
    
    btn.layer.borderColor = [UIColor clearColor].CGColor;
    btn.layer.borderWidth = 0;
    btn.tag = index+ CONTROL_BASE;
    
    NSString* file =template[@"value"];
    
    NSData* img_data=[ImageUtils load_img:file];
    
    if(img_data!=nil)
    {
        
        UIImage* image=[UIImage imageWithData:img_data];
        btn.image = image;
        
    }
    
    
    btn.backgroundColor = UIColorFromRGB(SIG_BG);
    
    if(DEBUG_PDFSIG)
    {
        
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:btn];
}
#pragma mark UIScrollView delegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    
    UIView *subView = [scrollView viewWithTag:1024];
    return subView;
    
}
//- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
//
//
//
//}
#pragma mark Button Click
- (void)ControlDatePickerClicked:(UIButton *)sender {
    
    
        long index = sender.tag - CONTROL_BASE;
    
    __weak __typeof(self)weakSelf = self;
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSString* date = @"";
    
    NSDate* currentDate =nil;
    if(date.length==0)
        currentDate=[NSDate date];
    else
        currentDate=[formatter dateFromString:date];
    
    DatePickerViewController* dpvc =[ [UIStoryboard storyboardWithName:@"CommonEditor" bundle:nil] instantiateViewControllerWithIdentifier:@"DatePickerViewController"];
    
    dpvc.pickerMode = UIDatePickerModeDate;
    
    
    
    dpvc.date = currentDate;
    dpvc.formatter = formatter;
    dpvc.labelTime.text = [formatter stringFromDate:currentDate];
    
    dpvc.blk_Set = ^(NSString* strdate)
    {
//        weakSelf.labelSignDate.text = strdate;
        
        [sender setTitle:strdate forState:UIControlStateNormal];
        
           weakSelf.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = strdate;
    };
    dpvc.title=@"Please choose a date";
    [self.navigationController pushViewController:dpvc animated:true];
}
- (void)ControlButtonClicked:(UIButton *)sender {
    //    DebugLog(@"cart sort button clicked");
    
    NSLog(@"button clicked;");
    //    [self.view addSubview:self.sortItemController.view];
}
- (void)CheckButtonClicked:(UIButton *)sender {
    //    DebugLog(@"cart sort button clicked");
    
    NSLog(@"check clicked;");
    
    long index = sender.tag - CONTROL_BASE;
    

    bool single_select = [self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"single_select"] boolValue];
    bool show_detail = [self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"show_detail"] boolValue];
    NSArray* rowData = self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"cadedate"];
    NSArray* checkedData = self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"];
    CheckSelectorViewController *checkVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"CheckSelectorViewController"];
    
    checkVC.blk_OK = ^(NSArray* checkedData){
        
        

        
        for(int i=0;i<rowData.count;i++)
        {
            long tag=CHECK_BASE+index*1000+i;
            
            
            
            NSArray* item = rowData[i];
            NSArray* checkmarker = item[1];
            if(checkmarker.count==0)
            {
                sender.backgroundColor = UIColorFromRGB(CK_BG);
                if([checkedData containsObject:[NSNumber numberWithLong:i]])
                {
                    [sender setTitle:item[0][0] forState:UIControlStateNormal];
                    if(item.count>=3)
                    {
                        NSMutableDictionary* action = item[2];
                        NSArray* disable_arr = action[@"disable"] ;
                        for(int d = 0 ; d<disable_arr.count;d++)
                        {
                            self.controlTemplate [disable_arr[d] ] [@"disable"] = [NSNumber numberWithBool:true];
                            NSString* s_idx =disable_arr[d];
                            s_idx=[s_idx stringByReplacingOccurrencesOfString:@"control_" withString:@""];
                            int d_idx = [s_idx intValue];
                            ((UITextView*)[sender.superview viewWithTag:d_idx+CONTROL_BASE]).editable = false;
                        }
                        NSArray* enable_arr = action[@"enable"] ;
                        for(int e = 0 ; e<enable_arr.count;e++)
                        {
                            self.controlTemplate [enable_arr[e] ] [@"disable"] = [NSNumber numberWithBool:false];
                            
                            NSString* s_idx =enable_arr[e];
                            s_idx=[s_idx stringByReplacingOccurrencesOfString:@"control_" withString:@""];
                            int d_idx = [s_idx intValue];

                            ((UITextView*)[sender.superview viewWithTag:d_idx+CONTROL_BASE]).editable = true;
                        }
                        
                        NSMutableDictionary* json_setval=action[@"set_val"] ;
                        for(int i=0;i<[json_setval[@"count"] intValue];i++)
                        {
                            
                            NSMutableDictionary * control =  json_setval [[NSString stringWithFormat:@"item_%d",i] ];
                            UITextView* tv = (UITextView*) [self findControl:control[@"control"]];
                            NSString* value = control[@"value"];
                            
                            UITextView* tv6 = (UITextView*) [self findControl:@"control_6"];
                            NSString* text = tv6.text;
                            NSString* newvalue = nil;
                            if([value isEqualToString:@"*0.1"])
                            {
                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.1;
                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
                                self.controlTemplate [control[@"control"] ][@"value"] = newvalue;
                            }
                            else if([value isEqualToString:@"*0.9"])
                            {
                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.9;
                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
                                self.controlTemplate [control[@"control"] ][@"value"] = newvalue;
                            }

                            
                            tv.text = newvalue;
                            
                        }
                    }
                    
                }
                continue;
            }
            else
            {
                [sender setTitle:@"" forState:UIControlStateNormal];
            }
            
           // UIView* v= sender;
            if([checkedData containsObject:[NSNumber numberWithLong:i]])
            {
               // [checkedData removeObject:[NSNumber numberWithLong:indexPath.row]];
                
                [sender.superview viewWithTag:tag].backgroundColor= [UIColor blackColor];
                
            }
            else
            {
               // [self.checkedData addObject:[NSNumber numberWithLong:indexPath.row] ];
                [sender.superview viewWithTag:tag].backgroundColor= [UIColor clearColor];
            }
            
            
        }
        self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"]=checkedData;
    };
    checkVC.rowData = rowData;
    checkVC.checkedData = [checkedData mutableCopy];
    checkVC.single_select = single_select;
    checkVC.show_detail = show_detail;
    
    checkVC.title=@"abcdefg";
    checkVC.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:checkVC animated:YES completion:nil];
    
}

#pragma mark TextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    
    long index = textView.tag - CONTROL_BASE;
    
    NSString* oldtext =textView.text;
    if(oldtext==nil)
        oldtext=@"";

    bool canChange=true;
    
    int max_line = [self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"lines"] intValue];
    if(max_line==0)//默认只能有一行
        max_line=1;
    long linecount=[TextUtils countOccurencesOfString:oldtext find:@"\n"];
    if(max_line!=-1) //maxline -1表示不限制行数。
    {
        if(linecount<=max_line-1&& [text isEqualToString:@"\n"])
        {
            canChange = false;
        }
    }

    int lenth = [self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"length"] intValue];
    if(lenth==0)
        return canChange;
    else
    {
        return canChange&& (lenth>textView.text.length ||[text isEqualToString:@""]);
    }

}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    long index = textView.tag - CONTROL_BASE;
    
    
    //处理 prefix 和 浮点格式化
        NSString* prefix_str= self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
    if(prefix_str.length==0)
        prefix_str = @"";
    NSString* text = [textView.text stringByReplacingOccurrencesOfString:prefix_str withString:@""];
    
    NSString* value_type= self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value_type"];
    if([value_type isEqualToString:@"float"])
        text=[NSString stringWithFormat:@"%.2f",[text floatValue] ];
    


    text =[NSString stringWithFormat:@"%@%@",prefix_str,text] ;
    
    textView.text = text;
    
    if(text==nil)
        text=@"";
    self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = text;
    
    NSDictionary* action = self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"action"];
    NSArray* keys=[action allKeys];
    for(int k=0;k<keys.count;k++)
    {
        NSMutableDictionary* act_k = action[keys[k] ];
        
        
        if (![self checkActionCondition:act_k[@"condition"]])
            continue;
        for(int i=0;i<[act_k[@"count"] intValue];i++)
        {
            
            NSMutableDictionary * control =  act_k [[NSString stringWithFormat:@"item_%d",i] ];
            UITextView* tv = (UITextView*) [self findControl:control[@"control"]];
            NSString* value = control[@"value"];
            
            NSString* newvalue = nil;
            if([value isEqualToString:@"*0.1"])
            {
                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.1;
                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
                
                self.controlTemplate [control[@"control"] ][@"value"] = newvalue;
            }
            else if([value isEqualToString:@"*0.9"])
            {
                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.9;
                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
                self.controlTemplate [control[@"control"] ][@"value"] = newvalue;
            }
            else if([value isEqualToString:@"control_6-control_7"])
            {
                
                UITextView* tv6 = (UITextView*) [self findControl:@"control_6"];
                float f6= [[tv6.text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue];
                
                float f7= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue];
                newvalue = [NSString stringWithFormat:@"$ %.2f",f6-f7];
                self.controlTemplate [control[@"control"] ][@"value"] = newvalue;
            }
            
            tv.text = newvalue;
            
        }
    }

    
//    int count = [self.controlTemplate[@"count"] intValue];
//    for(int i=0;i<count;i++)
//    {
//        NSMutableDictionary * control =;
    //[self update_newprice];
}
/*
 #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.
 }
 */
#pragma mark signature clicked 
//touchimageview Delegate
- (void)TouchImageViewOnTouche:(TouchImageView *)touchImageView
{
    
    NSLog(@"signature button clicked;");
    
    
    {
        
        //    CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
        //
        //
        //    CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
        //
        //    DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
        SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
        signatureVC.title=@"Signatures";
        signatureVC.signatureData = self.signatureData;
        
//        signatureVC.imageView = touchImageView;
        
        signatureVC.blk_Select =^(NSString* file)
        {
            
            
            
//            NSString* file_name=[file lastPathComponent];
            
            NSData* img_data=[ImageUtils load_img:file];
            
            if(img_data!=nil)
            {
                
                UIImage* image=[UIImage imageWithData:img_data];
                touchImageView.image = image;
                
                long index = touchImageView.tag - CONTROL_BASE;
                self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
                
            }

        };
        signatureVC.blk_Fill =^(NSString* file)
        {
            
            
            
//            //            NSString* file_name=[file lastPathComponent];
//            
//            NSData* img_data=[ImageUtils load_img:file];
//            
//            if(img_data!=nil)
//            {
//                
//                UIImage* image=[UIImage imageWithData:img_data];
//                touchImageView.image = image;
//                
//                long index = touchImageView.tag - CONTROL_BASE;
//                self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
//                
//            }
            
        };
        signatureVC.blk_Add = ^()
        {
            
            __block UIImage* signimg=nil;
            SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
            
            vc.onReturnImg = ^(UIImage* img)
            {
                
                
                signimg = img;
                
                if(signimg!=nil)
                {
                    NSString* file=[PDFUtils addSignature:signimg to:self.signatureData];
                        long index = touchImageView.tag - CONTROL_BASE;
                        self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
                    touchImageView.image = signimg;
                }
                
                
            };
            //    orderinfoVC.url_type = URL_REMOTE;
            //    orderinfoVC.request_url=URL_CARTDELIVERY;
            //
            //    orderinfoVC.params = params;
            //
            //    orderinfoVC.delegate=self;
            //
            //    if(checked.count==count)
            //    {
            //    orderinfoVC.have_tail = true
            //    }
            
            [self.navigationController pushViewController:vc animated:true];
            
            
            
        };
        
        UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
        navi.modalPresentationStyle=UIModalPresentationPopover;
        
        UIPopoverPresentationController* popPc = navi.popoverPresentationController;
        popPc.permittedArrowDirections = UIPopoverArrowDirectionAny;
        popPc.sourceView = touchImageView;
        popPc.delegate = nil;
        
        
        
        [self presentViewController:navi animated:true completion:nil];
        
        ////    menu.selector = self.selector;
        ////
        ////    menu.selectordelegate = self;
        //
        //    // 1.创建一个UIPopover
        //    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
        //
        //
        //
        //    UIPopoverPresentationController
        //    // 2.设置尺寸
        //    //    popover.popoverContentSize = CGSizeMake(320, 44 * 5);
        //
        //    // 3.从哪里显示出来 --> 指向item
        //
        //    [popover presentPopoverFromRect:self.view.frame   inView:self.view permittedArrowDirections:0 animated:YES];
        //    //  [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        //
        ////    self.popover = popover;
        //    popover pop
        //
        // [self performSegueWithIdentifier:@"selector_popover" sender:self];
        
    }
    //    __block int tag = touchImageView.tag;
    //    UIViewController* vc=[RAUtils getViewController :touchImageView];
    //
    //    if(self.editable==true)
    //    {
    //
    //
    //        ImageUploadViewController * uploadvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"ImageUploadViewController"];
    //
    //        //        UIImage* img =[self.buttonImg backgroundImageForState:UIControlStateNormal];;
    //
    //        if(self.img_validate)
    //            uploadvc.img= touchImageView.image;
    //
    //        uploadvc.returnValue = ^(NSString* url_down,NSString* url_up,UIImage* img)
    //        {
    //
    //            self.imgs[tag] = url_up;
    //
    //            NSString* newurl=[RAUtils arr2string:self.imgs separator:@"," trim:false];
    //
    //            touchImageView.image=img;
    //
    //            if(self.imgChanged)
    //                self.imgChanged(url_down,newurl,tag,url_up);
    //
    //        };
    //
    //        [vc.navigationController pushViewController:uploadvc animated:false];
    //    }
    //    else
    //    {
    //        if(touchImageView.image==nil)
    //            return ;
    //        ImageViewController * imagevc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"ImageViewController"];
    //
    //
    //        UIImage* img=touchImageView.image;
    //
    //        if(self.img_validate)
    //            imagevc.image = img;//.imageView.image = [self.buttonImg backgroundImageForState:UIControlStateNormal];
    //
    //        //        uploadvc.returnValue = ^(NSString* url_down,NSString* url_up,UIImage* img)
    //        //        {
    //        //
    //        //            [self.buttonImg setBackgroundImage:img forState:UIControlStateNormal];
    //        //
    //        //            if(self.imgChanged)
    //        //                self.imgChanged(url_down,url_up);
    //        //
    //        //        };
    //        
    //        [vc.navigationController pushViewController:imagevc animated:false];
    //    }
    //    //    bundleVC.content_data = self.bundle_item;
    //    
    
}



@end
