//
//  SearchViewController.m
//  Apex Mobile
//
//  Created by Ray on 14-3-3.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//
 
#import "SearchViewController.h"
#import "ResultViewController.h"
#import "SearchTableAdapter.h"
//#import "DB_Field.h"
#import "TableCellEdit.h"
#import "TableCellDate.h"
#import "TableCellBool.h"
#import "MyAutocompleteView.h"
@interface SearchViewController ()
@property (strong,nonatomic) SearchTableAdapter* adapter ;
@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.ioffset = 0;
    NSString* title=@"";
    if([self.function_name isEqualToString:@"Ocean Booking"])
        title = @"Booking Search";
    else if([self.function_name isEqualToString:@"Ocean B/L info."])
        title = @"B/L info. Search";
    else if([self.function_name isEqualToString:@"Container detail"])
        title = @"Container Search";
    else if([self.function_name isEqualToString:@"Download Document"])
        title = @"Document Search";
    self.navigationItem.title = title;
    
    
//    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
//    backButton.title = @"Back";
//    self.navigationItem.backBarButtonItem = backButton;
    
    self.dirty = true;
    
      DebugLog(@"viewDidLoad");
    
    
}
- (IBAction)onBoolitemClick:(UIButton *)sender {
      DebugLog(@"onBoolitemClick");
    UITableViewCell *cell  = (UITableViewCell *)[[sender superview] superview];
    //      DebugLog(@"reuseid:%@",cell.reuseIdentifier);
    //    //    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
    
    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
    if(indexPath==nil)
    {//for ios7
        cell  = (UITableViewCell *) sender.superview.superview.superview;
        indexPath = [self.table indexPathForCell:cell];
    }
    //    NSMutableDictionary * field =[_adapter get_item:[indexPath row]];
    //      DebugLog(@"textFieldShouldBeginEditing  row=%ld  type=%@",(long)[indexPath row], [field valueForKey:@"type"]);
    //    if(![[field valueForKey:@"type"] isEqualToString:@"bool"])
    //        return YES;
    
    NSString *title = NSLocalizedString(@"select_val", nil);//UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"Select value" : @"Select value";
    UIActionSheet *selBool = [[UIActionSheet alloc] initWithTitle:title
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"no", nil)
                                           destructiveButtonTitle:NSLocalizedString(@"clear", nil)
                                                otherButtonTitles:NSLocalizedString(@"yes", nil),
                              nil];
    selBool.tag = 1;
    //dateDialog.actionSheetStyle = self.navigationController.navigationBar.barStyle;
    [selBool showInView:self.view];
    self.boolBtntmp = sender;
    
    //    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    //    datePicker.tag = 101;
    //    datePicker.datePickerMode=UIDatePickerModeDate;
    //    [dateDialog addSubview:datePicker];
    
    
    //    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
	// 此处编写弹出日期选择器的代码。
    //	self.textFieldtmp=textField;
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
      DebugLog(@"viewWillAppear");
    if(self.dirty ==true)
    {
        _adapter=[[SearchTableAdapter alloc] init];
        [_adapter initfields:_function_name];
        
        [self.table reloadData];
        self.dirty=false;
    }
    [self.table reloadData];
}
//-(void) viewWillDisappear:(BOOL)animated
//{
//    [[self view] endEditing:animated];
//}
- (IBAction)onCustomize:(UIBarButtonItem *)sender {
    CustomizeFieldViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CustomizeFieldViewController"];
    ViewController.function_name = self.function_name;
    ViewController.behavior =BEHAVIOR_SEARCH;
    self.dirty = true;
    //ViewController.dirty = self.dirty;
    //    ViewController.
    
    [self.navigationController pushViewController:ViewController animated:YES];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
      DebugLog(@"numberOfSectionsInTableView");
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return [_adapter get_itemcount];
}

//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//    
//}
//- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
//{
//   [[self view] endEditing:YES];
//    return false;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSMutableDictionary * field =[_adapter get_item:[indexPath row]];
    

    
    if([[field valueForKey:@"type"] isEqualToString:@"boolean"])
    {
        NSString *CellIdentifier = @"item_bool";
        TableCellBool *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.anameLabel.text = [field valueForKey:@"aname"];
        NSString * val = [field valueForKey:@"value"];
        if(val.length==0)
            [cell.valButton setTitle:@"Not set" forState:UIControlStateNormal];
        else
            if([val isEqualToString:@"true"])
                [cell.valButton setTitle:@"Yes" forState:UIControlStateNormal];
            else
                [cell.valButton setTitle:@"No" forState:UIControlStateNormal];
        [cell.anameLabel sizeToFit];
          DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
        
        // Configure the cell...
        
        return cell;
        
        
        
    }
    else if([[field valueForKey:@"type"] isEqualToString:@"time"])
    {
        NSString *CellIdentifier = @"item_date";
        TableCellDate *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.anameLabel.text = [field valueForKey:@"aname"];
        [cell.anameLabel sizeToFit];
          DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
        
        // Configure the cell...
        NSString* str_from= [field valueForKey:@"from"];
        NSString* str_to= [field valueForKey:@"to"];
//        if(str_from.length>0)
        cell.fromEdit.text = str_from;
        cell.toEdit.text = str_to;
        return cell;
        
        //        static NSString *CellIdentifier = @"item_date";
        ////
        ////        //注册要使用的cell
        ////        [tableView registerClass:[TableCellDate class]
        ////          forCellReuseIdentifier:CellIdentifier];
        //
        //        //创建cell
        //        TableCellDate *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        //
        //        if(cell == nil)
        //        {
        //            cell = [[TableCellDate alloc] initWithStyle:UITableViewCellStyleValue1
        //                                        reuseIdentifier:CellIdentifier];
        //        }
        //
        //        cell.anameLabel.text = [field valueForKey:@"aname"];
        //        [cell.anameLabel sizeToFit];
        //          DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
        //        return cell;
    }
    else
    {
        NSString *CellIdentifier = @"item_edit";
        NSString * type = [field valueForKey:@"type"];
        
            
        TableCellEdit *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.anameLabel.text = [field valueForKey:@"aname"];
        [cell.anameLabel sizeToFit];
        NSString * val = [field valueForKey:@"value"];
        if([type isEqualToString:@"int"])
            cell.valueEdit.keyboardType = UIKeyboardTypeNumberPad;
        else
            cell.valueEdit.keyboardType = UIKeyboardTypeDefault;
        cell.valueEdit.text = val;
        
        NSArray* array = [ApexMobileDB get_searchhistory:[field valueForKey:@"name"]];
//        [self.autocompleteView.itemsSource put_predictions:array ];
        
        MyAutocompleteView* autocompleteView = [MyAutocompleteView autocompleteViewBindedTo:cell.valueEdit
                                                                 usingSource:[[MyAutocompleteItemsSource alloc]
                                                                              initWithMinimumCharactersToTrigger:1
                                                                              source:array
                                                                              ]
                                                                 cellFactory:[[MyAutocompletionCellFactory alloc]
                                                                              initWithCellTextColor:[UIColor blackColor]
                                                                              fontSize:14]
//                                                                presentingIn:self
                                                                                 parentView:self.table];
        autocompleteView.topMargin = 0;
        //    self.autocompleteView.backgroundColor = [UIColor ui];
        
        autocompleteView.didAutocompleteWith = ^(MySuggestion* item)
        {
            NSLog(@"Autocompleted with: %@",  item.completionText);
        };
        cell.autocompleteView = autocompleteView;
//        if(val.length==0)

          DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
        // Configure the cell...
        
        return cell;
        
        //        static NSString *CellIdentifier = @"item_edit";
        //
        ////        //注册要使用的cell
        ////        [tableView registerClass:[TableCellEdit class]
        ////          forCellReuseIdentifier:CellIdentifier];
        //
        //        //创建cell
        //        TableCellEdit *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        //
        //        if(cell == nil)
        //        {
        //            cell = [[TableCellEdit alloc] initWithStyle:UITableViewCellStyleValue1
        //                                        reuseIdentifier:CellIdentifier];
        //        }
        //
        //        cell.anameLabel.text = [field valueForKey:@"aname"];
        //        [cell.anameLabel sizeToFit];
        //          DebugLog(@"cellForRowAtIndexPath%@",[field valueForKey:@"aname"]);
        //        return cell;
        
    }
    return nil;
    
    
}
- (IBAction)ClearBtnOnClick:(UIButton *)sender {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"attention", nil) message:NSLocalizedString(@"alert_title_confirm_clear", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"no", nil) otherButtonTitles:NSLocalizedString(@"yes", nil), nil];
    [alert show];
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(buttonIndex!=alertView.cancelButtonIndex)
    {
        
        _adapter=[[SearchTableAdapter alloc] init];
        [_adapter initfields:_function_name];
        
        [self.table reloadData];
    }
    
    
}



- (IBAction)SearchBtnOnClick:(UIButton *)sender {
    
    ResultViewController *resultViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ResultViewController"];
    resultViewController.function_name = self.function_name;
//    if([self.function_name isEqualToString:@"Document Download"])
//        resultViewController.fullrow_select =false;
//    else
//        resultViewController.fullrow_select=true;
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    for(int i=0;i<[_adapter get_itemcount];i++)
    {
        NSMutableDictionary * field =[_adapter get_item:i];
        if([[field valueForKey:@"type"] isEqualToString:@"time"])
        {
            NSString* str_from= [field valueForKey:@"from"];
            NSString* str_to= [field valueForKey:@"to"];
            
            if(str_from.length>0)
                [params setValue:str_from forKey:[NSString stringWithFormat:@"%@_from",[field valueForKey:@"name"]]];
            if(str_to.length>0)
                [params setValue:str_to forKey:[NSString stringWithFormat:@"%@_to",[field valueForKey:@"name"]]];
        }
        else
        {
            NSString* value =[field valueForKey:@"value"];
            if(value.length>0)
            {
                [params setValue:[field valueForKey:@"value"] forKey:[field valueForKey:@"name"]];
                if([[field valueForKey:@"type"] isEqualToString:@"string"] )
                {
                     [ApexMobileDB savehistory:[field valueForKey:@"name"] value:[field valueForKey:@"value"]];
                }
            }
        }
    }
    [params setValue:self.function_name forKey:@"module_name"];
    resultViewController.params =params;
    [self.navigationController pushViewController:resultViewController animated:YES];
}


//- (IBAction)onTouchDown:(UITextField *)sender {
//      DebugLog(@"onTouchDown");
//}
//
//- (IBAction)dateEditOnClick:(UITextField *)sender forEvent:(UIEvent *)event {
//      DebugLog(@"dateEditOnClick");
//    UITableViewCell *cell  = (UITableViewCell *)[[sender superview] superview];
//    //      DebugLog(@"reuseid:%@",cell.reuseIdentifier);
//    //    //    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
//    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
//    NSMutableDictionary * field =[_adapter get_item:[indexPath row]];
//    if(![[field valueForKey:@"type"] isEqualToString:@"time"])
//        return ;
//
//    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n";
//    UIActionSheet *dateDialog = [[UIActionSheet alloc] initWithTitle:title
//                                                            delegate:self
//                                                   cancelButtonTitle:@"Cancel"
//                                              destructiveButtonTitle:@"Set"
//                                                   otherButtonTitles:nil,
//                                 nil];
//    //dateDialog.actionSheetStyle = self.navigationController.navigationBar.barStyle;
//    [dateDialog showInView:self.view];
//    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
//    datePicker.tag = 101;
//    datePicker.datePickerMode=UIDatePickerModeDate;
//    [dateDialog addSubview:datePicker];
//
//
//    //    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
//	// 此处编写弹出日期选择器的代码。
//	self.textFieldtmp=sender;
//
//}
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

#pragma mark - Text field delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    int fieldpos = [textField convertPoint:textField.bounds.origin toView:self.view].y+textField.frame.size.height;
    fieldpos+=150 ;//autocomplete height;
    int screenheight =self.view.frame.size.height;
    int ioffset = fieldpos - (screenheight - 216);//216 -(self.view.frame.size.height-fieldpos);
    if(ioffset>0)
    {
        self.ioffset = ioffset;
    CGPoint offset = self.table.contentOffset;
    offset.y+=ioffset;
        DebugLog(@"table content offset%d",ioffset);
    [self.table setContentOffset:offset animated:YES];
    }
}
//- (BOOL)textFieldShouldReturn:(UITextField *)sender {
//    [self.table setContentOffset:CGPointMake(0, 0) animated:YES];
//    return YES;
//}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
//    if(self.ioffset>0)
//    {
//        
//        CGPoint offset = self.table.contentOffset;
//        offset.y-=self.ioffset;
//        [self.table setContentOffset:offset animated:YES];
//        self.ioffset = 0;
//    }
//    
//    [self.table setContentOffset:CGPointMake(0, 0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
      DebugLog(@"textFieldDidEndEditing%@",textField.text);
    
    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
    
    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
    if(indexPath==nil)
    {//for ios7
        cell  = (UITableViewCell *) textField.superview.superview.superview;
        indexPath = [self.table indexPathForCell:cell];
    }
//    [self.table setContentOffset:CGPointMake(0, 0) animated:YES];
    [[_adapter get_item:[indexPath row]] setValue:textField.text forKey:@"value"];
}
//
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//    [self.table setContentOffset:CGPointMake(0, 70) animated:YES];
      DebugLog(@"textFieldShouldBeginEditing  text=%@",textField.text);
    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
    //      DebugLog(@"reuseid:%@",cell.reuseIdentifier);
    //    //    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
    
    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
    if(indexPath==nil)
    {//for ios7
        cell  = (UITableViewCell *) textField.superview.superview.superview;
        indexPath = [self.table indexPathForCell:cell];
    }
    NSMutableDictionary * field =[_adapter get_item:[indexPath row]];
      DebugLog(@"textFieldShouldBeginEditing  row=%ld  type=%@",(long)[indexPath row], [field valueForKey:@"type"]);
    if(![[field valueForKey:@"type"] isEqualToString:@"time"])
        return YES;
    
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n";
    UIActionSheet *dateDialog = [[UIActionSheet alloc] initWithTitle:title
                                                            delegate:self
                                                   cancelButtonTitle:NSLocalizedString(@"cancel",nil)
                                              destructiveButtonTitle:NSLocalizedString(@"clear",nil)
                                                   otherButtonTitles:NSLocalizedString(@"set",nil),
                                 nil];
    dateDialog.tag = 0;
    //dateDialog.actionSheetStyle = self.navigationController.navigationBar.barStyle;
    [dateDialog showInView:self.view];
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.tag = 101;
    datePicker.datePickerMode=UIDatePickerModeDate;
    [dateDialog addSubview:datePicker];
    
    
    //    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
	// 此处编写弹出日期选择器的代码。
	self.textFieldtmp=textField;
    //
    //
    //	[UIView setAnimationDuration:5.0];
    //	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    //	[UIView commitAnimations];
    //
	
    return NO;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if(actionSheet.tag==0)
    {
        
        if(buttonIndex==actionSheet.cancelButtonIndex)
            return;
        if(buttonIndex==actionSheet.destructiveButtonIndex)
        {
            self.textFieldtmp.text=nil;
            UITableViewCell *cell  = (UITableViewCell *)[[self.textFieldtmp superview] superview];
            
            NSIndexPath *indexPath = [self.table indexPathForCell:cell];
            if(indexPath==nil)
            {//for ios7
                cell  = (UITableViewCell *) self.textFieldtmp.superview.superview.superview;
                indexPath = [self.table indexPathForCell:cell];
            }
            
            if([self.textFieldtmp.restorationIdentifier isEqualToString:@"edit_from"])
                [[_adapter get_item:[indexPath row]] setValue:@"" forKey:@"from"];
            else
                [[_adapter get_item:[indexPath row]] setValue:@"" forKey:@"to"];
            
        }
        else
        {
            UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:101];
            NSDate *date = [datePicker date];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //设定时间格式,这里可以设置成自己需要的格式
            [dateFormatter setDateFormat:@"MM/dd/yyyy"];
            //用[NSDate date]可以获取系统当前时间
            self.textFieldtmp.text = [dateFormatter stringFromDate:date];
            
            
            
            
            //          DebugLog(@"textFieldShouldBeginEditing  text=%@",textField.text);
            UITableViewCell *cell  = (UITableViewCell *)[[self.textFieldtmp superview] superview];
            //      DebugLog(@"reuseid:%@",cell.reuseIdentifier);
            //    //    UITableViewCell *cell  = (UITableViewCell *)[[textField superview] superview];
            
            NSIndexPath *indexPath = [self.table indexPathForCell:cell];
            if(indexPath==nil)
            {//for ios7
                cell  = (UITableViewCell *) self.textFieldtmp.superview.superview.superview;
                indexPath = [self.table indexPathForCell:cell];
            }
            //        NSMutableDictionary * field =[_adapter get_item:[indexPath row]];
            
            if([self.textFieldtmp.restorationIdentifier isEqualToString:@"edit_from"])
                [[_adapter get_item:[indexPath row]] setValue:[dateFormatter stringFromDate:date] forKey:@"from"];
            else
                [[_adapter get_item:[indexPath row]] setValue:[dateFormatter stringFromDate:date] forKey:@"to"];
            //          DebugLog(@"textFieldShouldBeginEditing  row=%ld  type=%@",(long)[indexPath row], [field valueForKey:@"type"]);
            //        if(![[field valueForKey:@"type"] isEqualToString:@"time"])
            
            
            
        }
    }
    else
    {
       // self.boolBtntmp = sender;
        TableCellBool *cell  = (TableCellBool *)[[self.boolBtntmp superview] superview];
        
        NSIndexPath *indexPath = [self.table indexPathForCell:cell];
        if(indexPath==nil)
        {//for ios7
            cell  = (TableCellBool *) self.boolBtntmp.superview.superview.superview;
            indexPath = [self.table indexPathForCell:cell];
        }
        
        if(buttonIndex==actionSheet.cancelButtonIndex)
        {
            [self.boolBtntmp setTitle:@"No" forState:UIControlStateNormal];
            [[_adapter get_item:[indexPath row]] setValue:@"false" forKey:@"value"];
        }
        else if(buttonIndex==actionSheet.destructiveButtonIndex)
        {
            [self.boolBtntmp setTitle:@"Not set" forState:UIControlStateNormal];
            [[_adapter get_item:[indexPath row]] setValue:@"" forKey:@"value"];
        }
        else
        {
            [self.boolBtntmp setTitle:@"Yes" forState:UIControlStateNormal];
            
//            cell.anameLabel.text =@"aaa";
      //      [self.boolBtntmp.titleLabel setText:@"yes"];
       //     self.boolBtntmp.titleLabel.text = @"Yes";
            [[_adapter get_item:[indexPath row]] setValue:@"true" forKey:@"value"];
        }
        
    }
    // TODO:
}
//-(void)changedDate:(id)sender{
//	
//	//实例化一个NSDateFormatter对象
//	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//	//设定时间格式,这里可以设置成自己需要的格式
//	[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
//	//用[NSDate date]可以获取系统当前时间
//	self.textFieldtmp.text = [dateFormatter stringFromDate:self.datePicker.date];
//    
////	[dateFormatter release];
//    
//}
@end
