//
//  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 "CheckSelectorViewController.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)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];
            
        }
    }
    
}
#pragma mark add controls
-(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]];
    
    tv.text =template[@"value"];
    
    tv.tag = index+ CONTROL_BASE;
    
    
    //    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)
    {
        tv.backgroundColor = [UIColor lightGrayColor];
        
        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [destView addSubview:tv];
}
-(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 addTarget:self action:@selector(ControlButtonClicked:) 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=[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"];


    
    
    for(int i=0;i<cadedate.count;i++)
    {
        NSArray* item = cadedate[i];
        
        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= [UIColor blackColor];
            
        }
        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;
        
    }
    



    if(DEBUG_PDFSIG)
    {
        btn.backgroundColor = [UIColor lightGrayColor];
        
        // [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)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];
    
    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;
           // 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.title=@"abcdefg";
    checkVC.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:checkVC animated:YES completion:nil];
    
}

#pragma mark TextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    long index = textView.tag - CONTROL_BASE;
    
    NSString* text =textView.text;
    if(text==nil)
        text=@"";
    self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = text;
    
//    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_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
