//
//  ContactListViewController.m
//  RedAnt ERP Mobile
//
//  Created by Ray on 8/29/15.
//  Copyright (c) 2015 United Software Applications, Inc. All rights reserved.
//

#import "ContactListViewController.h"
#import "iSalesNetwork.h"
#import "ContactListTableViewCell.h"
#import "CustomerEditViewController.h"
#import "ContactAdvanceSearchViewController.h"

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


@interface ContactListViewController ()

@property (nonatomic,strong) NSOperationQueue *dataOperationQueue;

@end

@implementation ContactListViewController

- (NSOperationQueue *)dataOperationQueue {
    if (!_dataOperationQueue) {
        _dataOperationQueue = [[NSOperationQueue alloc] init];
        _dataOperationQueue.maxConcurrentOperationCount = 1;
    }
    return _dataOperationQueue;
}


- (void)awakeFromNib {
    self.edit_icon = true;
    self.assig_icon = true;
    self.reset_icon=false;
}
-(void) logout
{
    self.offset = 0;
    [self.content_data removeAllObjects];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label_net_err.layer.borderColor = [UIColor darkGrayColor].CGColor;
    self.label_net_err.layer.borderWidth = 2.0;
    self.label_net_err.layer.cornerRadius=15;
    self.label_net_err.layer.masksToBounds=true;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refresh_btn_click:)];
    //            tap.minimumPressDuration = 0.8; //定义按的时间
    [self.label_net_err addGestureRecognizer:tap];
    
    
    // Do any additional setup after loading the view.
    self.offset = 0;
    self.limit = 25;
    self.content_data = [[NSMutableArray alloc]init];
    
    
    UIRefreshControl *ref = [[UIRefreshControl alloc]init];
    ref.tag = 201 ;
    ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"Pull 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(manually_refresh) forControlEvents:UIControlEventValueChanged];
    [self.table addSubview:ref];
    
    
    
    self.reset = false;
    
    
    
////    UILabel* titleLabel= [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100
//                                                                   
//                                                                   , 44)];
//    titleLabel.text=@"Contacts";
//    //  titleLabel.backgroundColor =[UIColor yellowColor];
//    titleLabel.textAlignment=NSTextAlignmentCenter;
//    //    [titleLabel sizeToFit];
//    
//    //将搜索条放在一个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;
//    
//    
//    
//    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(searchView.frame.size.width-200.0f-8.0f,0.0f,200.0f,44.0f)];
//    self.searchBar.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
//    self.searchBar.delegate = self;
//    [self.searchBar setPlaceholder:@"name/address"];
//    //searchBar.barTintColor=[UIColor clearColor];
//    self.searchBar.searchBarStyle=UISearchBarStyleMinimal;
//    [searchView addSubview:titleLabel];
//    [searchView addSubview:self.searchBar];
//    
//    self.navigationItem.titleView = searchView;
    
//    NSMutableArray * items = [[NSMutableArray alloc]init];
//    
//    
//    UIBarButtonItem *Btnback = nil;//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSaveClick:)];
//    
//    Btnback = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
//                                               style:UIBarButtonItemStylePlain
//                                              target:self
//                                              action:@selector(onBack:)];
//    
//    
//    UIBarButtonItem *btnAS = nil;
//    btnAS =[[UIBarButtonItem alloc] initWithTitle:@"Advanced search"
//                                                style:UIBarButtonItemStylePlain
//                                               target:self
//                                               action:@selector(onASearch:)];
//    
//    
//    
//    
//    //savebtn setBackgroundImage:(nullable UIImage *) forState:<#(UIControlState)#> style:<#(UIBarButtonItemStyle)#> barMetrics:<#(UIBarMetrics)#>
//    //[savebtn setImage:[UIImage imageNamed:@"save"] ];
//    
//    
//    /*
//     UIBarMetricsDefault,
//     UIBarMetricsCompact,
//     UIBarMetricsDefaultPrompt = 101, // Applicable only in bars with the prompt property, such as UINavigationBar and UISearchBar
//     UIBarMetricsCompactPrompt
//     
//     */
//    // [savebtn setBackgroundImage:[UIImage imageNamed:@"save"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    //        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";
//    
//    
//    UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//    fixedItem.width = 20.0f;
//    
////    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
////    
////    if(appDelegate.user_type ==USER_ROLE_EMPLOYEE)
//    
//        [items addObject:Btnback];
//        
//        [items addObject:fixedItem];
//    
//    [items addObject:btnAS];
//    //        [items addObject:item2];
//    self.navigationItem.leftBarButtonItems=items;
    
    
        self.offset = 0;
        [self.content_data removeAllObjects];
    //    [self loadpage];

    

}
-(void)manually_refresh
{
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:201];
    if(self.isrefreshing)
    {
        [reF endRefreshing];
        return;
    }
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Refreshing"];
     if ([self respondsToSelector:@selector(ReloadData)])
    [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
    
}

-(void)ReloadData
{
    
    self.keywords=self.searchBar.text;
    self.offset = 0;
    [self.content_data removeAllObjects];
    [self.table reloadData];
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:201];
    
    [reF endRefreshing];
    
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Pull to refresh"];
    [self loadpage];
    
    //   [self loadpage];

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

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//        [[self navigationController] setNavigationBarHidden:NO animated:NO];
//    self.offset = 0;
//    [self.content_data removeAllObjects];
//    [self loadpage];
    
    [[self navigationController] setNavigationBarHidden:!self.showNavibar animated:NO];
}
-(void) reload_container_getdata:(bool) update_data
{
    [super reload_container_getdata:update_data];
    
    if(update_data)
    {
        self.offset = 0;
        [self.content_data removeAllObjects];
        
        [self loadpage];
    }
    else
    {
        [self.table reloadData];
    }
    
    
}

-(void) operation_loadpage
{
    if (self.dataOperationQueue.operationCount > 1) {
        return;
    }
        dispatch_async(dispatch_get_main_queue(), ^{
    if(self.isrefreshing)
        return;
    
self.label_net_err.hidden=true;
        
        self.isrefreshing=true;
    if(self.offset==0)
    {
        self.table.hidden = true;
    //    [self.params setValue:[NSString stringWithFormat:@"%ld",self.offset] forKey:@"offset"];
    self.mum.center = self.view.center;

        
        self.mum.hidden = false;
        [self.mum startAnimating];
    }
    //    self.btnrefresh.enabled = false;
    //
    //    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;
    //    self.mum.hidden = false;
    //    self.tableview.hidden = true;
    
    //    [UIView commitAnimations];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        NSMutableDictionary* content=nil;
        content=[[iSalesNetwork request_ContactList:self.offset limit : self.limit keywords:self.keywords type:self.contact_type adv_search:self.adv_search] mutableCopy];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.mum stopAnimating];
            self.isrefreshing=false;
            if (self.dataOperationQueue.operationCount > 1) {
                return ;
            }
            
            
            if([[content valueForKey:@"result"] intValue]==2)
            {
                self.table.hidden =false;
                int count = [[content valueForKey:@"count" ] intValue] ;
                
                self.offset += count;
                for(int i=0;i<count;i++)
                {
                    
                    NSDictionary* objmsg = [content objectForKey:[NSString stringWithFormat:@"item_%d",i]];
                    [self.content_data addObject:[NSMutableDictionary dictionaryWithDictionary:objmsg]];
                    
                }
                if(count<self.limit)
                {
                    
                    //                    int i =self.btnrefresh.state;
                    self.load_more_hint=@"All loaded";
                    //                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"no_more", nil);
                    //                    [self.btnrefresh setTitle:@"No more" forState:UIControlStateNormal];
                }
                else
                {
                    self.load_more_hint=@"Load more...";
                    //                    self.btnrefresh.enabled = true;
                    //                    self.btnrefresh.titleLabel.text =NSLocalizedString(@"load_more",nil);
                    //                    [self.btnrefresh setTitle:@"Load more" forState:UIControlStateNormal];
                }
                
                
                
                [self.table reloadData ];
                
                
            }
            else if([[content valueForKey:@"result"] intValue]==RESULT_NET_ERROR &&self.offset==0)
            {
                self.label_net_err.hidden=false;
                self.table.hidden = true;
            }
            else
            {
                [RAUtils message_alert:[content valueForKey:@"err_msg"] title:@"Loading Contact List" controller:self] ;
            }
           
            
            //            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            //            bool autologin =[defaults boolForKey:@"autologin"];
            //            if(!autologin)
            //            {
            //                TabBarController * viewController =[self.storyboard instantiateViewControllerWithIdentifier:@"LoginTabBar"];
            //                [self presentViewController:viewController animated:YES completion:^{
            //
            //                }];
            //            }
            
            self.isrefreshing=false;
            
        });
    });
        });
}

-(void) loadpage {
    __weak typeof(self) weakself = self;
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        
        if (weakself) {
            __strong typeof(weakself) strongself = weakself;
            [strongself operation_loadpage];
        }
        
    }];
    
    [self.dataOperationQueue addOperation:operation];
}

- (void)loadmore
{
    //    self.btnrefresh.enabled = NO;
    //    self.btnrefresh.titleLabel.text =NSLocalizedString(@"loading",nil);
    
    //    [self.btnrefresh setTitle:@"Loading..." forState:UIControlStateNormal];
    [self loadpage];
}
- (IBAction)onBack:(UIBarButtonItem *)sender {
    if(self.onCancel)
        self.onCancel();
        [self.navigationController popViewControllerAnimated:(false)];
}
- (IBAction)onASearch:(UIBarButtonItem *)sender {
    ContactAdvanceSearchViewController * vc =[ self.storyboard instantiateViewControllerWithIdentifier:@"ContactAdvanceSearchViewController"];
    
    vc.url_type = URL_REMOTE;
    
    vc.request_url=URL_CUSTOMER_ADV_SEARCH;
    
    
    
    NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
     vc.params = params;
    
    vc.data_init = self.adv_search;
    
   // vc.update_order = true;
    
   // vc.contactId=contactid;
    //  vc.delegate = self;
    
    vc.returnValue = ^(NSMutableDictionary* value){
       
        
        

        
        self.adv_search = value;
        
        self.keywords=nil;
        self.offset = 0;
        [self.content_data removeAllObjects];
       
        [self loadpage];
        
//        appDelegate.contact_id=[value valueForKey:@"customer_cid"];
//        appDelegate.customerInfo = value;
    };
    
    
    [self.navigationController pushViewController:vc animated:true];
}
- (IBAction)onNewCustomerClick:(id)sender {
    
    
        NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
    
    CustomerEditViewController * cuseditVC =[ self.storyboard instantiateViewControllerWithIdentifier:@"CustomerEditViewController"];
    
    cuseditVC.bnewcustomer=true;
    cuseditVC.url_type = URL_REMOTE;
    cuseditVC.request_url=URL_NEW_CUSTOMER;
    
    cuseditVC.params = params;
    
    cuseditVC.delegate=self;
    //
    //    if(checked.count==count)
    //    {
    //    orderinfoVC.have_tail = true
    //    }
     [[self navigationController] setNavigationBarHidden:NO animated:NO];
    [self.navigationController pushViewController:cuseditVC animated:false];
    

}
- (IBAction)resetContactId:(id)sender {
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.contact_id=nil;
    appDelegate.customerInfo = nil;
//     appDelegate.contact_name =nil;
    
    if(self.onReset)
        self.onReset();
    [self.navigationController popViewControllerAnimated:(false)];
    
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    DebugLog(@"!!!!!!!!!!!!!!!!!!!!!route!!!!!!!!!!!!!!!!!!!!!");
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [self.table reloadData];
    //    CGSize contentsize = self.scroll.contentSize;
    //    contentsize.height =330+2 * 230+29+20+20 +1 * 230+29+20+20 ;
    //    UIInterfaceOrientation orientation =[UIApplication sharedApplication].statusBarOrientation;
    //    if(orientation == UIDeviceOrientationLandscapeLeft ||orientation == UIDeviceOrientationLandscapeRight)
    //    {
    //        contentsize.height+=250;
    //    }
    //
    //    self.scroll.contentSize = contentsize;
    //    //     CGRect frame = self.view.frame;
    //    //    [self.carouselController.view removeFromSuperview];
    //    //    wait(2000);
    //    //    self.carouselController = [[FPCarouselNonXIBViewController alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 400)];
    //    //    [self.view addSubview:self.carouselController.view];
    //    //    int i = self.view.subviews.count;
    //    //    int b = 0;
    //    // [self.carouselController updateFrame:CGRectMake(0, 0, self.view.frame.size.width, 400)];
}
//
//-(void)changeCell
//{
//    //    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
//    //    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
//    [self performSelector:@selector(loadmore) withObject:nil afterDelay:1];
//    DebugLog(@"refresh!!!!!!!!");
//    
//}
- (IBAction)onAssignClick:(id)sender {
    
    UIButton* btn = (UIButton*)sender;
    
    UITableViewCell *cell = (UITableViewCell *)btn.superview.superview;;
    NSIndexPath *indexPath = [self.table indexPathForCell:cell];
    DebugLog(@"indexPath is = %i",indexPath.row);
    
    
        NSString* contactid=[self.content_data[indexPath.row] valueForKey:@"contact_id"] ;
    
    
    
    UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Getting Contact information"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary* editor_json = [iSalesNetwork request_CustomerInfo:contactid];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
            
            if([[editor_json valueForKey:@"result"] intValue]==2)
            {
                __block NSMutableDictionary* data_init = [[editor_json objectForKey:@"customerInfo" ] mutableCopy];
                
                //---------------- construct customer_contact----------------------
                NSString* customer_first_name = [data_init valueForKey:@"customer_first_name"];
                if(customer_first_name==nil)
                    customer_first_name=@"";
                
                NSString* customer_last_name= [data_init valueForKey:@"customer_last_name"];
                if(customer_last_name==nil)
                    customer_last_name=@"";
                NSString* customer_contact = [NSString stringWithFormat:@"%@ %@",customer_first_name,customer_last_name];
                customer_contact=[customer_contact stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                [data_init setValue:customer_contact forKey:@"customer_contact"];
                
                data_init[@"is_subaction"]=self.is_subaction;
                data_init[@"subaction_tag"]= self.subaction_tag;
//                [self.navigationController popViewControllerAnimated:false];
                
                
                [self.table reloadData];
                
                if(self.returnValue)
                    self.returnValue(data_init,self.from);
                
//                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//                    NSDictionary* editor_json = [iSalesNetwork update_OrderCustomer:appDelegate.order_code customerinfo:data_init];
//                    
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        
//                        
//                        if([[editor_json valueForKey:@"result"] intValue]==2)
//                        {
//                            
////                            [self.navigationController popViewControllerAnimated:false];
////                            if(self.returnValue)
////                            {
////                                
////                                self.returnValue(data_init);
////                            }
//                            
//                            
//                            
//                        }
//                        else
//                        {
//                            [RAUtils message_alert:[editor_json valueForKey:@"err_msg"] title:@"Update Order Customer Infomation" controller:self] ;
//                        }
//                        
//                        
//                        
//                    });
//                });
                
            }
            else
            {
                [RAUtils message_alert:[editor_json valueForKey:@"err_msg"] title:@"Loading Contact Information" controller:self] ;
//                self.btn_assign.enabled=false;
            }
            
            
        });
    });


    
}
#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    

    if(indexPath.row==self.content_data.count)
        return 44;
    
    NSString* value = [self.content_data[indexPath.row] valueForKey:@"name"];
    
    
    float width = tableView.frame.size.width;
    width-=74;
    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 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;
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
//{
//     NSDictionary * item_json = [self.content_data objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
//    if([item_json objectForKey:@"combine"] == nil)
//    {
//        return 120;
//    }
//    else
//        return 150;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 0;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 0;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//        UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0.0001)];
//    return myView;
//
//}

//- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView* myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0.0001)];
////    myView.backgroundColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
////    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 22)];
////    titleLabel.textColor=[UIColor whiteColor];
////    titleLabel.backgroundColor = [UIColor clearColor];
////    if(section==0)
////        titleLabel.text=NSLocalizedString(@"display_items", nil);
////    else
////        titleLabel.text=NSLocalizedString(@"hide_items", nil);
////    [titleLabel sizeToFit];
////    [myView addSubview:titleLabel];
////
//    return myView;
//}
//
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    if(section==0)
//        return nil;
//    else
//        return @"detail section";
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // NSDictionary * item_json = [self.content_data objectForKey:@"items"];
    if( self.content_data.count==0)
        return 0;
    return self.content_data.count+1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    if(tableView==self.itemListTable)
    //    {
    DebugLog(@"row %ld",(long)indexPath.row);
    if(indexPath.row==self.content_data.count)
    {
        UITableViewCell *moreCell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"mores"];
        UILabel *moreDataLabel=[[UILabel alloc] init];
        
        moreDataLabel.tag=200;
        moreDataLabel.text=self.load_more_hint;
        [moreDataLabel setFont:[UIFont systemFontOfSize:14.0f]];
        [moreDataLabel setTextAlignment:NSTextAlignmentCenter];
        moreDataLabel.frame=CGRectMake(0, 10, self.table.bounds.size.width, 20);
        [moreDataLabel setBackgroundColor:[UIColor clearColor]];
        //        [moreDataLabel addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
        moreCell.backgroundColor = [UIColor whiteColor];
        [moreCell.contentView addSubview:moreDataLabel];
        if([self.load_more_hint isEqualToString:@"Load more..."])
            [self performSelector:@selector(loadmore) withObject:nil afterDelay:1];
        //        DebugLog(@"更多...");
        return moreCell;
    }
    else
    {
// UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ContactListCell"];
        
        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        NSString *CellIdentifier = @"ContactListTableViewCell";
        ContactListTableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        NSString* value = [self.content_data[indexPath.row] valueForKey:@"name"];
        
        cell.rtlabel.text = value;
        
        cell.btn_assign.hidden = !(self.assig_icon&&(appDelegate.contact_id.length==0));
        
  /*      NSString* name= [self.content_data[indexPath.row] valueForKey:@"name"];
        NSString* address= [self.content_data[indexPath.row] valueForKey:@"address"];
        cell.detailTextLabel.text=address;
        cell.textLabel.text=name;
        
        //cell.sep
//        [UIColor rg]*/
        cell.backgroundColor = [UIColor whiteColor];
//        cell.separator.backgroundColor = [UIColor grayColor];
        return cell;
    }
   
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>self.content_data.count-1) {
        return;
    }
    
    
    NSString* contactid=[self.content_data[indexPath.row] valueForKey:@"contact_id"] ;
    
    
    bool editable =[[self.content_data[indexPath.row] valueForKey:@"can_update"]boolValue] ;
   
    CustomerInfoViewController * vc =[ self.storyboard instantiateViewControllerWithIdentifier:@"CustomerInfoViewController"];
    
    vc.url_type = URL_LOCAL;
    
    vc.request_url=LOCAL_URL_CUSTOMER_INFO_EDITOR;
    
    vc.update_order = self.update_order;
            AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(self.ui_type==CONTACT_LIST)
    {

        vc.edit_icon = self.edit_icon&&editable&&appDelegate.can_update_contact_info;
        vc.assig_icon = self.assig_icon&&(appDelegate.contact_id.length==0);
        vc.reset_icon = self.reset_icon&&(appDelegate.contact_id.length!=0);
    }
    else
    {
        vc.edit_icon = self.edit_icon&&editable&&appDelegate.can_update_contact_info;
        vc.assig_icon = self.assig_icon;
        vc.reset_icon = self.reset_icon;
    }

    
//    NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
//    //            NSString * string = [checked componentsJoinedByString:@","];
//    //            [params setValue:string forKey:@"cart2Checkbox"];
//    
//    
//    
//    
//    addressVC.params = params;
    vc.contactId=contactid;
//    vc.delegate = self;
    
    vc.from = indexPath;
    //            orderinfoVC.params = params;
    vc.returnValue = ^(NSMutableDictionary* value){
        

        
        
        value[@"is_subaction"]=self.is_subaction;
        value[@"subaction_tag"]= self.subaction_tag;
        [self.navigationController popViewControllerAnimated:false];

        
        if(self.returnValue)
            self.returnValue(value,self.from);
    };
    
    
    [self.navigationController pushViewController:vc animated:true];
    
    /*
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.contact_id=contactid;
    appDelegate.contact_name =[self.content_data[indexPath.row] valueForKey:@"name"];
    */
//    [self.navigationController popViewControllerAnimated:(false)];
//    NSString* orderid= [self.content_data[indexPath.row] valueForKey:@"order_id"];
//    OrderDetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"OrderDetailViewController" ];
//    
//    dvc.orderid=orderid;
//    [self.navigationController pushViewController:dvc animated:true];
// 
    //
}
/*
#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 - searchBar delegate;
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.keywords=searchBar.text;
    self.offset = 0;
    [self.content_data removeAllObjects];
    self.adv_search=nil;
    [self loadpage];
    DebugLog(@"search");
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    if([searchText isEqualToString:@""] && !self.reset)
    {
        DebugLog(@"clear");
        self.reset=true;
        self.keywords=nil;
        
        self.offset = 0;
        [self.content_data removeAllObjects];
        
        self.adv_search=nil;
        [self loadpage];
//        [self loadpage];
    }
    else
        self.reset = false;
}
@end
