//
//  CommonEditorEnumViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 14-7-18.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "EnumSelectViewController.h"
#import "EnumSelectorCell.h"
#import "RAUtils.h"
#import "AppDelegate.h"

#define  DEF_CELL_HEIGHT 44
//#define  DEF_TABLE_HEIGHT 44
//#define  LINE_WIDTH 0
//#define  CELL_MARGIN 0
#define  LABEL_MARGIN 15


@interface EnumSelectViewController ()

@end

@implementation EnumSelectViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.max_select = 0;
    
    self.navi_item.title = self.title;
    
//    self.navigationItem.title = self.title;
    // Do any additional setup after loading the view.

    self.auto_close = true;
    
    if(self.is_dialog)
    {
        UIBarButtonItem *closeButton =   [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                                                              style:UIBarButtonItemStylePlain
                                                                                                             target:self
                                                                                                             action:@selector( onCloseClick:)];
 //       [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
        self.navi_item.rightBarButtonItem = closeButton;
    }
    else
    {
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                       style:UIBarButtonItemStylePlain
                                                                      target:self
                                                                      action:@selector( onBackClick:)];
        //   [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Back", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onBackClick:)];
        
        self.navigationItem.leftBarButtonItem = backButton;
    }
    self.dirty = false;
    
    
    
    
    UILabel* titleLabel= [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 200
                                                                   
                                                                   , 44)];
    titleLabel.text=self.title;
    //  titleLabel.backgroundColor =[UIColor yellowColor];
    titleLabel.textAlignment=NSTextAlignmentCenter;
    
    
    //将搜索条放在一个UIView上
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1768, 44)];
    
    
    
    
    searchView.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
    
    titleLabel.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    titleLabel.center=searchView.center;
    
    
    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(searchView.frame.size.width-200.0f-8.0f,0.0f,200.0f,44.0f)];
    searchBar.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    searchBar.delegate = self;
    [searchBar setPlaceholder:@"filter"];
    //searchBar.barTintColor=[UIColor clearColor];
    searchBar.searchBarStyle=UISearchBarStyleMinimal;
    [searchView addSubview:titleLabel];
    [searchView addSubview:searchBar];
    
    self.navigationItem.titleView = searchView;
    

    [[self navigationController] setNavigationBarHidden:self.hide_navibar animated:NO];
    
}
- (void)onBackClick:(UIButton *)sender {
    
    
    [self.navigationController popViewControllerAnimated:(false)];
    //    [self.navigationController dismissViewControllerAnimated:true completion:^{
    //        ;
    //    }];
}
- (void)onCloseClick:(UIButton *)sender {

    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 
                                 
                             }];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if(self.dirty == false)
    return;
    if (self.delegate && [self.delegate respondsToSelector:@selector(EnumValueChanged:indexPath:)]) {
        [self.delegate EnumValueChanged:self.cadedate indexPath:self.updatePosition];
    }
    if(self.returnValue)
        self.returnValue(self.cadedate);
}


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

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    
    [self.tableEnum reloadData];
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    [appDelegate didRotated];
    
    
    
}
#pragma mark - Table view data source


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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    //    if(self.canbeEmpty)
    //    return [[self.cadedate valueForKey:@"count"] intValue]+1;
    //    else
    
    
    if(self.keywords==nil || self.keywords.length==0)
    {
        self.filter_count = 0;
    return [[self.cadedate valueForKey:@"count"] intValue];
    }
    else
    {
        
        int count = 0;
        
        for (int i=0; i<[[self.cadedate valueForKey:@"count"] intValue]; i++)
        {
            NSDictionary* val_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i ]];
            
            NSString* value = [val_json valueForKey:@"value"];
            
            NSUInteger location=[[value uppercaseString] rangeOfString:self.keywords].location;
            if(location!= NSNotFound)
                count++;
        }
        self.filter_count = count;
        return count;
    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    
    NSDictionary* val_json =nil;
    
    
    if(self.keywords==nil || self.keywords.length==0)
    {
        val_json=[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row ]];
    }
    else
    {
        
        int count = 0;
        
        for (int i=0; i<[[self.cadedate valueForKey:@"count"] intValue]; i++)
        {
            if(count>= self.filter_count)
                break;
            NSDictionary* search_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i ]];
            
            NSString* value = [search_json valueForKey:@"value"];
            
            NSUInteger location=[[value uppercaseString] rangeOfString:self.keywords].location;
            if(location!= NSNotFound)
                count++;
            
            if(count-1==indexPath.row)
                val_json=search_json;
        }
        
    }
    
    
    
    
    NSString* value = [val_json valueForKey:@"value"];
    
    
    float width = tableView.frame.size.width;
    width-=40;
    CGSize constraintkey = CGSizeMake(width-2*LABEL_MARGIN, 10.0f);//key label width is 40% cell width;
    //            CGSize constraintval = CGSizeMake(width*0.6-2*LABEL_MARGIN, 20000.0f);//val label width is 60% cell width;
    
    
    
    //  NSDictionary* item = [self.content get_item_seg:indexPath.section row:indexPath.row];
//    NSString* key =[self.content_data valueForKey:@"order_info"];
    
    //   [cell.keyLabel sizeToFit];
    //            NSString* val=[item_json valueForKey:@"val"] ;
    
    //            if([val isEqual:[NSNull null]])
    //                val=@"";
    //            if(val==nil)
    //                val=@"";
    //            if([val isEqualToString:@"null"])
    //                val=@"";
    
    
    
    CGRect frame;
    frame.size = constraintkey;
    frame.origin.x=0;
    frame.origin.y=0;
    
    
    
    RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
    
  //  rtlabel.lineSpacing = 10;
    //            [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
    //        rtlabel.lineSpacing = 20.0;
    [rtlabel setText: value];
    CGSize optimumSize = [rtlabel optimumSize];
    //            DebugLog(@"%@",key);
    
    //            [rtlabel sizeThatFits:constraintkey];
    
    //            rtlabel frameHeight:<#(CTFrameRef)#>
    //            rtlabel
    //            [rtlabel sizeToFit];
    //CGSize newsize=            rtlabel.frame.size;
    //            CGSize sizeval=rtlabel.optimumSize;
    
    
    //            CGSize sizekey = [key sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
    //           CGSize sizeval = [val sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintval lineBreakMode:NSLineBreakByWordWrapping];
    float height = optimumSize.height;
    height = MAX(height+2*LABEL_MARGIN, DEF_CELL_HEIGHT);
    
    
    return height;
    
}


//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleNone;
//}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //如果两次点击的时间间隔小于1秒，则断定为双击事件
//
//    if(tableView.editing==false)
//        return;
//
//
//    if([tableView numberOfRowsInSection:indexPath.section]<=1)
//        return;
//    //    int between = 1;
//    NSUInteger curr = [[NSDate date] timeIntervalSince1970];
//
//    if(indexPath.row==self.lasttap.row&&indexPath.section==self.lasttap.section)
//    {
//        if (curr-self.taptime<1) {
//            DebugLog(@"double click!");
//            self.lasttap =nil;
//
//            NSMutableArray * from;
//            NSMutableArray * to ;
//            int section;
//            if(indexPath.section==0)
//            {
//                from  = self.displayfields;
//                to = self.hidefields;
//                section = 1;
//            }
//            else
//            {
//
//                from  = self.hidefields;
//                to = self.displayfields;
//                section = 0;
//            }
//            NSIndexPath * toIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
//            //            NSIndexPath * headerIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
//            //            NSIndexPath * headerIndexPath1 = toIndexPath;
//
//            id content=from[indexPath.row];
//            [tableView beginUpdates];
//            [from removeObjectAtIndex:indexPath.row];
//            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//
//            [to insertObject:content atIndex:0];
//            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:toIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//            [tableView endUpdates];
//
//            //            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:headerIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//            //            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:headerIndexPath1] withRowAnimation:UITableViewRowAnimationFade];
//            [tableView reloadData];
//
//
//        }
//        self.taptime = curr;
//
//
//    }
//    else
//    {
//        self.taptime = curr;
//        self.lasttap = indexPath;
//    }
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    NSDictionary* val_json =nil;
    
    
    if(self.keywords==nil || self.keywords.length==0)
    {
        val_json=[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row ]];
    }
    else
    {
        
        int count = 0;
        
        for (int i=0; i<[[self.cadedate valueForKey:@"count"] intValue]; i++)
        {
            if(count>= self.filter_count)
                break;
            NSDictionary* search_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i ]];
            
            NSString* value = [search_json valueForKey:@"value"];
            
            NSUInteger location=[[value uppercaseString] rangeOfString:self.keywords].location;
            if(location!= NSNotFound)
                count++;
            
            if(count-1==indexPath.row)
                val_json=search_json;
        }
        
    }
    
    
    
    NSString* CellIdentifier = @"EnumSelectorCell";
    
    EnumSelectorCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//    NSDictionary* val_json = [self.cadedate objectForKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row ]];
    
    NSString* value = [val_json valueForKey:@"value"];
   // cell.rtLabel.lineSpacing=10;
    cell.rtLabel.text = value;
//    cell.labelValue.text = value;
    int check = [[val_json valueForKey:@"check" ] intValue];
    if(check==1)
    cell.img_checkmark.hidden=false;
    else
    cell.img_checkmark.hidden=true;
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EnumSelectorCell* cell = (EnumSelectorCell*)[tableView cellForRowAtIndexPath:indexPath];

    
    cell.selected = false;
    self.dirty = true;
    
    if(self.single_select)
    {
        
        
        
        
        
        if(self.keywords==nil || self.keywords.length==0)
        {
            for(int i=0;i<[[self.cadedate valueForKey:@"count"] intValue];i++)
            {
                
                
                
                
                NSMutableDictionary* val_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]] mutableCopy];
                if(i==indexPath.row)
                    [val_json setValue:@"1" forKey:@"check"];
                else
                    [val_json setValue:@"0" forKey:@"check"];
                [self.cadedate setObject:val_json forKey:[NSString stringWithFormat:@"val_%d",i]];
            }
        }
        else
        {
            

            
            NSMutableDictionary* val_json =nil;
            
            int count = 0;
            
            for (int cc=0; cc<[[self.cadedate valueForKey:@"count"] intValue]; cc++)
            {
                if(count>= self.filter_count)
                    break;
                NSMutableDictionary* search_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",cc ]] mutableCopy];
                
                NSString* value = [search_json valueForKey:@"value"];
                
                NSUInteger location=[[value uppercaseString] rangeOfString:self.keywords].location;
                if(location!= NSNotFound)
                    count++;
                
                if(count-1==indexPath.row)
                    val_json=search_json;
            }
            
            for (int sc=0;sc<[[self.cadedate valueForKey:@"count"] intValue];sc++)
            {
                NSMutableDictionary* sc_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",sc ]] mutableCopy];
                
                if ([[sc_json valueForKey:@"value" ] isEqual:[val_json valueForKey:@"value"]] )
                    [sc_json setValue:@"1" forKey:@"check"];
                else
                    [sc_json setValue:@"0" forKey:@"check"];
                [self.cadedate setObject:sc_json forKey:[NSString stringWithFormat:@"val_%d",sc]];
            }
            
        }
        
        if(self.auto_close)
        {
            if(self.navigationController!=nil)
                [self.navigationController popViewControllerAnimated:YES];
                
//            [self.navigationController dismissViewControllerAnimated:YES
//                                                          completion:^{
//                                                              
//                                                              
//                                                          }];
            else
            [self dismissViewControllerAnimated:YES
                                     completion:^{
                                         
                                         
                                     }];
        }
    }
    else
    {
        

        
        
        NSMutableDictionary* val_json =nil;
        
        
        if(self.keywords==nil || self.keywords.length==0)
        {
            val_json=[[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row ]] mutableCopy];
        }
        else
        {
            
            int count = 0;
            
            for (int i=0; i<[[self.cadedate valueForKey:@"count"] intValue]; i++)
            {
                if(count>= self.filter_count)
                    break;
                NSMutableDictionary* search_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i ]] mutableCopy];
                
                NSString* value = [search_json valueForKey:@"value"];
                
                NSUInteger location=[[value uppercaseString] rangeOfString:self.keywords].location;
                if(location!= NSNotFound)
                    count++;
                
                if(count-1==indexPath.row)
                    val_json=search_json;
            }
            
        }
        
//        NSMutableDictionary* val_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row]] mutableCopy];
        int check = [[val_json valueForKey:@"check"] intValue];
        if(check==1)
        [val_json setValue:@"0" forKey:@"check"];
        else
        {
            if([self check_count]>=self.max_select && self.max_select>0)
            {
                
//                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:  message:[NSString stringWithFormat: delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                //        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error!" message:@"User&Password can not be empty!" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) , nil];
//                [alert show];
                
                
                [RAUtils alert_view:[NSString stringWithFormat:@"%d items at most for this field.",self.max_select ] title:@"Max count reached"];
                
                return;
            }
            [val_json setValue:@"1" forKey:@"check"];
        }
        [self.cadedate setObject:val_json forKey:[NSString stringWithFormat:@"val_%ld",(long)indexPath.row]];
        
        
    }
    [self.tableEnum reloadData];
    
}
-(int) check_count
{
    int check_count=0;
   // int count = 0;
    
    for (int i=0; i<[[self.cadedate valueForKey:@"count"] intValue]; i++)
    {

        NSMutableDictionary* val_json = [[self.cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i ]] mutableCopy];
        
        int check = [[val_json valueForKey:@"check"] intValue];
        if(check==1)
            check_count++;

    }
    return check_count;
}

#pragma mark - searchBar delegate;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.keywords=[searchBar.text uppercaseString];
    
    [self.tableEnum reloadData];
//    self.offset = 0;
//    [self.content_data removeAllObjects];
//    [self loadpage];
//    DebugLog(@"search");
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    
    if([searchText isEqualToString:@""] && !self.reset)
    {
        self.keywords=nil;
        [self.tableEnum reloadData];
        self.reset=true;
    
    }
    else
        self.reset = false;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
