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

#import "ResultViewController.h"
#import "TabBarController.h"
@interface ResultViewController ()
-(void) getHeader: (NSMutableArray*)header_name header_aname:(NSMutableArray*)header_aname;
-(void) loadpage;
-(NSArray*) getActions;
@end

@implementation ResultViewController
-(void) loadpage
{
    
    [self.params setValue:[NSString stringWithFormat:@"%ld",self.offset] forKey:@"offset"];
    self.mum.center = self.view.center;
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.prepageButton.enabled=false;
    self.nextpageButton.enabled=false;
    self.mum.hidden = false;
    self.grid.hidden = true;
    
    [UIView commitAnimations];
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //        PageData* pageData=nil;
        if(self.recordCount<0)
            self.recordCount=[ApexMobileNetwork get_recordcount: self.params ];
        if(self.recordCount>0)
        {
            self.pageData=[ApexMobileNetwork get_pagedata:self.params];
            //            self.pageData=[ApexMobileNetwork]
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSTimeInterval animationDuration = 0.30f;
            [UIView beginAnimations:@"ResizeView" context:nil];
            [UIView setAnimationDuration:animationDuration];
            
            if(self.recordCount>=0)
            {
                if(self.recordCount<2000)
                    self.countView.title = [NSString stringWithFormat:@"%ld records",self.recordCount];
                else
                    self.countView.title = @"2000+ records";
            }
            else
            {
                self.countView.title = @"Net error!";
            }
            if(self.offset<self.pageData.get_count||self.offset==0)
                self.prepageButton.enabled=false;
            else
                self.prepageButton.enabled=true;
            if(self.offset+self.pageData.get_count>=self.recordCount)
                self.nextpageButton.enabled=false;
            else
                self.nextpageButton.enabled=true;
            [self.grid initgrid :self.pageData];
            
            CGPoint p = self.grid.frame.origin;
            
            
            self.mum.hidden = true;
            self.grid.hidden = false;
            [UIView commitAnimations];
            
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            bool autologin =[defaults boolForKey:@"autologin"];
            if(!autologin)
            {
                TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
                [self presentViewController:viewController animated:YES completion:^{
                    
                }];
            }
            
        });
    });
}
- (void) showDetail:(UIMenuItem*) sender
{
    DebugLog(@"show detail id = %@",self.detail_id);
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:self.params copyItems:true];
    
    
    [params setValue:self.detail_id forKey:@"id"];
    
    
    DetailTabBarController *detailViewController=[[DetailTabBarController alloc] init:self.function_name actions:self.actions params:params];
    
    
    //        DetailTabBarController *detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailTabBarController"];
    //        detailViewController.function_name = self.function_name;
    //        detailViewController.actions = self.actions;
    //        detailViewController.params =params;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    //(int)Authorize : (NSString*) user password:(NSString*) password
    
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"1111" message:@"1111" delegate:self cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles: nil];
    //    [alert show];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(showDetail:))
        return YES;//显示
    else
        return NO;//不显示
}

-(void)menuItemSelected:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.item);
    [pulldownMenu animateDropDown];
    if(indexPath.item==0)
    {
        CustomizeFieldViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomizeFieldViewController"];
        ViewController.function_name = self.function_name;
        ViewController.behavior =BEHAVIOR_RESULT;
        self.dirty=true;
        //    ViewController.dirty = self.dirty;
        
        [self.navigationController pushViewController:ViewController animated:YES];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"alert_title_create_tag", nil) message:NSLocalizedString(@"alert_msg_savehint", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"save", nil),nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        UITextField * txt = [[UITextField alloc] init];
        
        txt.backgroundColor = [UIColor yellowColor];
        
        txt.frame = CGRectMake(alert.center.x+65,alert.center.y+48, 150,23);
        //        [alert addSubview:txt];
        [alert show];
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(buttonIndex!=alertView.cancelButtonIndex)
    {
        UITextField * txt=[alertView textFieldAtIndex:0];
        NSString* name = txt.text;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.params
                                                           options:0
                                                             error:nil];
        NSString* param = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
        NSString* user = appDelegate.user;
        
        sqlite3 *db =[ApexMobileDB get_db];
        
        [ApexMobileDB execSql: [NSString stringWithFormat: @"insert into history(params,name,module_name,user) values('%@','%@','%@','%@')",param,name,self.function_name,user] db:db];
        
        sqlite3_close(db);
        
        //NSString *jsonString =
        /*
         String name = ((EditText) edit)
         .getText().toString();
         String param = getIntent().toUri(0);
         
         JSONObject obj = new JSONObject();
         Set<String> keys = searchParms.keySet();
         for (String key : keys)
         {
         
         
         try
         {
         obj.put(key, searchParms.get(key).toString());
         
         }
         catch (JSONException e)
         {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
         
         }
         obj.toString();
         
         SQLiteDatabase db = dbUtil.OpenDB(
         ApexTrackingApplication.get_instance(), null, true);
         db.execSQL("insert into history(params,name,criterion,module_name,user,create_time) values('"
         
         + param
         + "','"
         + name
         + "','"
         + obj.toString()
         + "','"
         + function_name
         + "','"
         + ApexTrackingApplication.get_user()
         + "',"
         + System.currentTimeMillis() + ")");
         dbUtil.CloseDB(db);
         
         */
        
    }
    
    
}
-(void)pullDownAnimated:(BOOL)open
{
    if (open)
    {
        NSLog(@"Pull down menu open!");
    }
    else
    {
        NSLog(@"Pull down menu closed!");
    }
}

- (IBAction)onCustomize:(UIBarButtonItem *)sender {
    
    
    
    CGRect ff = self.navigationController.navigationBar.frame;
    //    : CGPointMake(0.0f,self.navigationController.navigationBar.frame.size.height)
    
    [pulldownMenu animateDropDown:CGPointMake(0.0f,self.navigationController.navigationBar.frame.size.height)];
    //    CustomizeFieldViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomizeFieldViewController"];
    //    ViewController.function_name = self.function_name;
    //    ViewController.behavior =BEHAVIOR_RESULT;
    //    self.dirty=true;
    //    //    ViewController.dirty = self.dirty;
    //
    //    [self.navigationController pushViewController:ViewController animated:YES];
}
- (BOOL)canBecomeFirstResponder{
    return YES;
}
- (void) Tap:(UIView*)view url:(NSString*) url
{
    WebViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
    ViewController.url = url;
    //    ViewController. = self.function_name;
    //    ViewController.behavior =BEHAVIOR_SEARCH;
    
    [self.navigationController pushViewController:ViewController animated:YES];
}
- (void) LongPress:(UIView*)view _id:(NSString*) _id
{
    DebugLog(@"!!!!!!!!!!!!!!!!!");
    self.actions = [self getActions];
    
    if(self.actions.count<1)
        return;
    self.detail_id = _id;
    UIMenuItem *detail = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"menuitem_showdetail", nil) action:@selector(showDetail:)];
    //    [detail setValue:_id forKey:@"_id"];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    
    [menu setMenuItems:[NSArray arrayWithObjects:detail, nil]];
    
    [menu setTargetRect:view.frame inView:view.superview];
    [menu setMenuVisible:YES animated:YES];
    
    
    
}

- (IBAction)onPrePageClick:(UIButton *)sender {
    self.offset -=self.prepageCount;
    [self loadpage];
}
- (IBAction)onNextPageClick:(UIButton *)sender {
    self.offset +=self.pageData.get_count;
    self.prepageCount=self.pageData.get_count;
    [self loadpage];
}

-(NSArray*) getActions
{
    DebugLog(@"getActions");
    
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    
    NSMutableArray* actions = [[NSMutableArray alloc]init];
    sqlite3 *db =[ApexMobileDB get_db];
    NSString *quary = [NSString stringWithFormat:@"select name from actions_info where function_name='%@' and user='%@'order by priority",self.function_name, appDelegate.user];
    
    
    
    sqlite3_stmt *stmt;
    
    if (sqlite3_prepare_v2(db, [quary UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        DebugLog(@"sql:%@",quary);
        DebugLog(@"=======================show tabs===================");
        while (sqlite3_step(stmt)==SQLITE_ROW)
        {
            
            NSString *name = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
            [actions addObject:name];
            DebugLog(@"action name: %@",name);
        }
        DebugLog(@"=======================show tabs===================");
        sqlite3_finalize(stmt);
    }
    //用完了一定记得关闭，释放内存
    sqlite3_close(db);
    return actions;
}
-(void) getHeader: (NSMutableArray*)header_name header_aname:(NSMutableArray*)header_aname
{
    //    NSMutableDictionary* header = [[NSMutableDictionary alloc] init];
    //    [header setValue:@"aaa" forKey:@"bbb"];
    DebugLog(@"initHeader");
    ApexMobileAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    sqlite3 *db =[ApexMobileDB get_db];
    NSString *quary = [NSString stringWithFormat:@"select aname,name from fields_info where function_name='%@' and user='%@' and behavior=%d and show=1 order by priority,aname",self.function_name, appDelegate.user,BEHAVIOR_RESULT];
    
    
    
    sqlite3_stmt *stmt;
    
    if (sqlite3_prepare_v2(db, [quary UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        DebugLog(@"sql:%@",quary);
        DebugLog(@"=======================show fields===================");
        while (sqlite3_step(stmt)==SQLITE_ROW)
        {
            NSString *aname = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
            NSString *name = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
            //            [header setValue:aname forKey:name];
            [header_name addObject:name];
            [header_aname addObject:aname];
            DebugLog(@"%@",aname);
            
        }
        DebugLog(@"=======================show fields===================");
        sqlite3_finalize(stmt);
    }
    //用完了一定记得关闭，释放内存
    sqlite3_close(db);
    //    return header;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //       self.pageData=[[PageData alloc] init];
        
        
    }
    return self;
}
//- (BOOL)shouldAutorotate
//{
//    return YES;
//}
//
//- (NSUInteger)supportedInterfaceOrientations
//{
//    return UIInterfaceOrientationMaskLandscapeRight;
//}
//
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
//{
//    return UIInterfaceOrientationLandscapeRight;
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    
    
    
    NSString* title=@"";
    if([self.function_name isEqualToString:@"Ocean Booking"])
        title = @"Booking Result";
    else if([self.function_name isEqualToString:@"Ocean B/L info."])
        title = @"B/L info. Result";
    else if([self.function_name isEqualToString:@"Container detail"])
        title = @"Container Result";
    else if([self.function_name isEqualToString:@"Download Document"])
        title = @"Document Result";
    self.navigationItem.title = title;
//    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
//    backButton.title = @"Back";
//    
//    self.navigationItem.backBarButtonItem = backButton;
    
    // self.navigationController.view.frame.size.height;
    
    //    NSMutableArray * items = [[NSMutableArray alloc]init];
    //    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] init];
    //    item1.title = @"item1";
    //    item1.image = [UIImage imageNamed:@"rect_setting"];
    //    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] init];
    //    item2.image = [UIImage imageNamed:@"rect_about"];
    //    item2.title = @"item2";
    //    [items addObject:item1];
    //    [items addObject:item2];
    //    self.navigationItem.rightBarButtonItems=items;
    //    self.navigationItem.backBarButtonItem = backButton;
    
    
    self.dirty = @"true";
    
    if([self.function_name isEqualToString:@"Download Document"])
        self.fullrow_select =false;
    else
        self.fullrow_select=true;
    
    
    
    pulldownMenu = [[PulldownMenu alloc] initWithView:self.view];
    [self.view addSubview:pulldownMenu];
    
    [pulldownMenu insertButton:NSLocalizedString(@"menuitem_setting", nil)];
    [pulldownMenu insertButton:NSLocalizedString(@"menuitem_savesearch", nil)];
    
    
    pulldownMenu.delegate = self;
    //    self.navigationItem.rightBarButtonItems
    
    [pulldownMenu loadMenu];
    
    
    
    
    
    UIRefreshControl *ref = [[UIRefreshControl alloc]init];
    ref.tag = 200 ;
    ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"drag to refresh"];
    ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
    //    ref.hidden = true;
    [ref addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
    [self.grid addSubview:ref];
    
}
-(void)changeCell
{
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
    [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
    DebugLog(@"refresh!!!!!!!!");
    
}

-(void)ReloadData
{
    
    //    Count ++ ;
    //    [mytabelview reloadData];
    [self loadpage];
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
    
    [reF endRefreshing];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    DebugLog(@"viewWillAppear");
    
    
    
    
    if(self.dirty ==true)
    {
        self.prepageCount=0;
        self.recordCount = -1;
        self.offset = 0;
        NSMutableArray* header_name =[[NSMutableArray alloc]init];
        NSMutableArray* header_aname =[[NSMutableArray alloc]init];
        [self getHeader:header_name header_aname:header_aname];
        //    self.header = [self getHeader:header_name];
        //    self.grid.header = self.header;
        self.grid.fullrowselect = self.fullrow_select;
        self.grid.griddelegate = self;
        self.grid.header_name=header_name;
        self.grid.header_aname=header_aname;
        [self.params setValue:self.function_name forKey:@"module_name"];
        NSString* fields =@"";
        for(int i=0;i<header_name.count;i++)
        {
            fields=[fields stringByAppendingFormat:@"%@,",header_name[i]];
            
        }
        fields=[fields substringToIndex: fields.length-1];
        
        [self.params setValue:fields forKey:@"columns"];
        
        [self loadpage];
        self.dirty = false;
        //            [pulldownMenu loadMenu:self.grid.frame.origin];
    }
    
    
}
//-(NSUInteger)supportedInterfaceOrientations
//{
//      DebugLog(@"myViewController::supportedInterfaceOrientations");
//    return UIInterfaceOrientationMaskLandscape;
//    //    return [[self topViewController] supportedInterfaceOrientations];
//}
//- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
//{
//      DebugLog(@"myViewController::preferredInterfaceOrientationForPresentation");
//    return UIInterfaceOrientationLandscapeRight;
//}
//-(BOOL)shouldAutorotate
//{
//      DebugLog(@"myViewController::shouldAutorotate");
//    return YES;
//}
//
//- (void)viewWillAppear:(BOOL)animated
//{
////    [self presentViewController:[[UIViewController alloc]init] animated:NO completion:^
////    {
////          DebugLog(@"dismiss viewcontroller");
////        [self dismissViewControllerAnimated:NO completion:nil];
////    }];
//
//
////    [self presentViewController:nil animated:NO completion:nil];
//
//    //    [self presentViewController];
//
//}




//    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//    {
//        return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//    }

//    - (NSUInteger)supportedInterfaceOrientations
//    {
//        //    return UIInterfaceOrientationMaskLandscapeLeft;
//        return UIInterfaceOrientationMaskLandscapeRight;
//    }

//    - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
//        return UIInterfaceOrientationLandscapeRight;
//        //    return UIInterfaceOrientationPortrait;
//    }
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
