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

#import "SelectorViewController.h"
#import "iSalesNetwork.h"
@interface SelectorViewController ()

@end

@implementation SelectorViewController
@synthesize selectordelegate;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.superview.layer.cornerRadius
    = 0;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#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 - Table view data source

//- (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;
//    
//    NSDictionary* related_json = [self.detail_data objectForKey:@"related_model"];
//    if(related_json==nil)
//    {
//        NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",section-1]];
//        return [section_json valueForKey:@"title"] ;
//    }
//    else
//    {
//        if(section==1)
//            return @"related model";
//        else
//        {
//            NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",section-2]];
//            return [section_json valueForKey:@"title"] ;
//        }
//    }
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
//- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    DebugLog(@"canMoveRowAtIndexPath");
//
//    if([tableView numberOfRowsInSection:indexPath.section]>1)
//        return true;
//    else
//        return false;
//}
//- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
//{
//    NSMutableArray * from;
//    NSMutableArray * to ;
//    if(fromIndexPath.section==0)
//        from  = self.displayfields;
//    else
//        from  = self.hidefields;
//    if(toIndexPath.section==0)
//        to  = self.displayfields;
//    else
//        to  = self.hidefields;
//    id content=from[fromIndexPath.row];
//    [from removeObjectAtIndex:fromIndexPath.row];
//    [to insertObject:content atIndex:toIndexPath.row];
//
//    [tableView reloadData];
//
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return      [[self.selector valueForKey:@"count"] intValue];
//    
//    if(section==0)
//        return 1;
//    NSDictionary* related_json = [self.detail_data objectForKey:@"related_model"];
//    if(related_json==nil)
//    {
//        NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",section-1]];
//        return [[section_json valueForKey:@"count"] intValue];
//    }
//    else
//    {
//        if(section==1)
//            return 1;
//        else
//        {
//            NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",section-2]];
//            return [[section_json valueForKey:@"count"] intValue];
//        }
//    }
//    
    
    
}
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleNone;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果两次点击的时间间隔小于1秒，则断定为双击事件
    NSDictionary* item = [self.selector objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];

    NSDictionary* params = [item objectForKey:@"params"];
    
    NSString* detail_id=[[[params objectForKey:@"param_0"] valueForKey:@"val" ] stringValue];
    
//    NSString* category=[self.selector objectForKey:[NSString stringWithFormat:@"item_%ld",indexPath.row]] valueForKey:<#(NSString *)#>

    [selectordelegate selected:detail_id category:nil];
    [self dismissViewControllerAnimated:false completion:^{}];
//    
//    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;
//    }
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    
    return 70;
   // SelectorCell
    
//    if(indexPath.section ==0)
//        return 550;
//    
//    NSDictionary* related_json = [self.detail_data objectForKey:@"related_model"];
//    if(related_json==nil)
//    {
//        NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",indexPath.section-1]];
//        
//        NSDictionary* item_json =[section_json objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]];
//        
//        NSString* type=[section_json valueForKey:@"type"] ;
//        
//        if([type isEqualToString:@"kv"])
//        {
//            float width = tableView.frame.size.width;
//            width-=CELL_MARGIN*2;
//            CGSize constraintkey = CGSizeMake(width*0.4-2*LABEL_MARGIN, 20000.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 =[item_json valueForKey:@"key"] ;
//            
//            //   [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 = constraintval;
//            frame.origin.x=0;
//            frame.origin.y=0;
//            RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
//            [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
//            //        rtlabel.lineSpacing = 20.0;
//            [rtlabel setText: val];
//            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 = MAX(sizekey.height,sizeval.height);
//            height = MAX(height+LINE_WIDTH, DEF_CELL_HEIGHT);
//            
//            
//            return height;
//        }
//        else if([type isEqualToString:@"img"])
//        {
//            int img_count = [[item_json valueForKey:@"count"] intValue];
//            double ret = 0;
//            for(int j=0;j<img_count;j++)
//            {
//                NSDictionary* img_json =[item_json objectForKey:[NSString stringWithFormat:@"image_%d",j ]];
//                float width = [[img_json valueForKey:@"width"]floatValue];
//                float height = [[img_json valueForKey:@"height"]floatValue];
//                ret+=height*tableView.bounds.size.width / width;
//            }
//            
//            return ret;
//        }
//        else if([type isEqualToString:@"content"])
//            return 270;
//        return 44;
//    }
//    else
//    {
//        if(indexPath.section==1)
//            return 270;
//        else
//        {
//            NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",indexPath.section-2]];
//            
//            NSDictionary* item_json =[section_json objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]];
//            
//            NSString* type=[section_json valueForKey:@"type"] ;
//            
//            if([type isEqualToString:@"kv"])
//            {
//                float width = tableView.frame.size.width;
//                width-=CELL_MARGIN*2;
//                CGSize constraintkey = CGSizeMake(width*0.4-2*LABEL_MARGIN, 20000.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 =[item_json valueForKey:@"key"] ;
//                
//                //   [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 = constraintval;
//                frame.origin.x=0;
//                frame.origin.y=0;
//                RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
//                [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
//                //        rtlabel.lineSpacing = 20.0;
//                [rtlabel setText: val];
//                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 = MAX(sizekey.height,sizeval.height);
//                height = MAX(height+LINE_WIDTH, DEF_CELL_HEIGHT);
//                
//                
//                return height;
//            }
//            else if([type isEqualToString:@"img"])
//            {
//                int img_count = [[item_json valueForKey:@"count"] intValue];
//                double ret = 0;
//                for(int j=0;j<img_count;j++)
//                {
//                    NSDictionary* img_json =[item_json objectForKey:[NSString stringWithFormat:@"image_%d",j ]];
//                    float width = [[img_json valueForKey:@"width"]floatValue];
//                    float height = [[img_json valueForKey:@"height"]floatValue];
//                    ret+=height*tableView.bounds.size.width / width;
//                }
//                
//                return ret;
//            }
//            return 44;
//        }
//    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    DebugLog(@"cellForRowAtIndexPath");
    
 
        NSString *CellIdentifier = @"SelectorCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        NSDictionary* item = [self.selector objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row]];
        
     cell.imageView.image=[UIImage imageNamed:@"loading_s"];   
    cell.textLabel.text=[item valueForKey:@"title"];
    NSString* img_url = [item valueForKey:@"pic_url"];
    NSString* file_name=[img_url lastPathComponent];
    NSData* img_data=[iSalesDB load_cached_img:file_name];
    if(img_data!=nil)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage * img =[UIImage imageWithData:img_data];
            cell.imageView.image=img;
        });
    }
    else
    {
        NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            if(downloadimg_data!=nil)
            {
                [iSalesDB cache_img:downloadimg_data :file_name ];
                
                UIImage * img =[UIImage imageWithData:downloadimg_data];
                cell.imageView.image=img;
            }
            else
                cell.imageView.image=[UIImage imageNamed:@"notfound_s"];
            
        });
    }
        //        cell.selector_valLabel.text =[[section_json objectForKey:@"selector"] valueForKey:@"name"];
    
        
        
        return cell;
    
    }
    //    else
    //    {
    //        if(indexPath.section==1)
    //        {
    //            NSString *CellIdentifier = @"DetailRelatedCell";
    //
    //
    //
    //            // NSDictionary* section_json = [self.detail_data objectForKey:@"related_model"];
    //            DetailRelatedCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    //            cell.itemdelegate = self;
    //            cell.related_data = related_json;
    //            return cell;
    //
    //        }
    //        else
    //        {
    //            NSString *CellIdentifier = @"DetailInfoCell";
    //
    //
    //
    //            NSDictionary* section_json = [self.detail_data objectForKey:[NSString stringWithFormat:@"detail_%d",indexPath.section-2]];
    //
    //            NSDictionary* item_json =[section_json objectForKey:[NSString stringWithFormat:@"item_%ld",(long)indexPath.row ]];
    //
    //            NSString* type=[section_json valueForKey:@"type"] ;
    //
    //            if([type isEqualToString:@"kv"])
    //            {
    //                float width = tableView.frame.size.width;
    //
    //                width-=CELL_MARGIN*2;
    //                CGSize constraintkey = CGSizeMake(width*0.4-2*LABEL_MARGIN, 20000.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 =[item_json valueForKey:@"key"] ;
    //
    //                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 = constraintval;
    //                frame.origin.x=0;
    //                frame.origin.y=0;
    //                RTLabel* rtlabel = [[RTLabel alloc] initWithFrame:frame];
    //                [rtlabel setLineBreakMode: RTTextLineBreakModeWordWrapping];
    //                //        rtlabel.lineSpacing = 20.0;
    //                [rtlabel setText: val];
    //                CGSize sizeval=rtlabel.optimumSize;
    //                CGSize sizekey = [key sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
    //
    //                float height = MAX(sizekey.height,sizeval.height);
    //                height = MAX(height, DEF_CELL_HEIGHT-LINE_WIDTH);
    //                sizekey.height = height;
    //                sizekey.width = constraintkey.width;
    //                // sizeval.height = height;
    //                sizeval.width =constraintval.width;
    //
    //                //    NSString *CellIdentifier = @"detail_item_kv";
    //                DetailKVCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    //                if(cell==nil)
    //                    DebugLog(@"cell is nil.........................");
    //
    //
    //
    //
    //                CGRect framekey = cell.keyLabel.frame;
    //                framekey.origin.x=CELL_MARGIN+LABEL_MARGIN;
    //                framekey.origin.y=LINE_WIDTH;
    //                framekey.size = sizekey;
    //                cell.keyLabel.frame = framekey;
    //                cell.keyLabel.text=key;
    //                CGRect frameval = cell.valLabel.frame;
    //                frameval.origin.x=constraintkey.width+CELL_MARGIN+3*LABEL_MARGIN; //2 margin for key 1 margin for value self
    //                frameval.origin.y=LINE_WIDTH;
    //                frameval.size = sizeval;
    //                cell.valLabel.frame = frameval;
    //                //        [cell.valLabel setTextAlignment:RTTextAlignmentCenter];
    //                cell.valLabel.text= val;
    //                CGPoint rcenter;
    //                rcenter.x = width * 0.4+width * 0.6/2;
    //                rcenter.y = height /2;
    //                cell.valLabel.center=rcenter;
    //                //        cell.valLabel.backgroundColor =[UIColor redColor];
    //
    //                //        cell.contentView.superview.backgroundColor = [UIColor clearColor];
    //                //        cell.backgroundColor = [UIColor whiteColor];
    //                UIView * lineview = [[LineView alloc] initWithFrame:cell.contentView.frame];
    //                lineview.userInteractionEnabled = NO;// 不设为NO会屏蔽cell的点击事件
    //                lineview.backgroundColor = [UIColor clearColor];// 设为透明从而使得cell.backgroundColor有效.
    //                lineview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //                [cell.contentView addSubview:lineview];// cell.contentView是个readonly属性,所以别想着替换contentView了.
    //
    //
    //
    //                return cell;
    //            }
    //            else if ([type isEqualToString:@"img"])
    //            {
    //                DetailImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailImageCell" forIndexPath:indexPath];
    //
    //                int img_count = [[item_json valueForKey:@"count"] intValue];
    //                double posy = 0;
    //                for(int j=0;j<img_count;j++)
    //                {
    //                    NSDictionary* img_json =[item_json objectForKey:[NSString stringWithFormat:@"image_%d",j ]];
    //                    float width = [[img_json valueForKey:@"width"]floatValue];
    //                    float height = [[img_json valueForKey:@"height"]floatValue];
    //                    //
    //                    UIImageView * imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, posy, tableView.bounds.size.width , height*tableView.bounds.size.width / width)];
    //                    NSString* img_url = [img_json valueForKey:@"img_url"];
    //                    posy+=height*tableView.bounds.size.width / width;
    //                    NSString* file_name=[img_url lastPathComponent];
    //                    NSData* img_data=[iSalesDB load_cached_img:file_name];
    //                    if(img_data!=nil)
    //                    {
    //
    //                        UIImage * img =[UIImage imageWithData:img_data];
    //                        imgview.image = img;
    //                        [cell addSubview:imgview];
    //                    }
    //                    else
    //                    {
    //
    //                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //
    //                            NSData*  downloadimg_data = [NSData dataWithContentsOfURL:[NSURL URLWithString:img_url]];
    //
    //                            dispatch_async(dispatch_get_main_queue(), ^{
    //
    //
    //
    //                                if(downloadimg_data!=nil)
    //                                {
    //                                    [iSalesDB cache_img:downloadimg_data :file_name ];
    //
    //                                    UIImage * img =[UIImage imageWithData:downloadimg_data];
    //                                    imgview.image = img;
    //                                    [cell addSubview:imgview];
    //                                }
    //                                
    //                            });
    //                        });
    //                        
    //                        
    //                    }
    //                    
    //                    
    //                }
    //                return cell;
    //            }
    //            
    //            return nil;
    //            
    //            
    //        }
    //    }
    

@end
