//
//  HomeViewController.m
//  RedAnt ERP Suite
//
//  Created by Ray on 14-5-23.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "HomeViewController.h"
#import "iSalesNetwork.h"
#import "const.h"
#import "HomeTableViewCellBanner.h"
#import "DetailViewController.h"
#import "MainViewController.h"
#import "HomeTableViewCellButtonBanner.h"
#import "WebViewController.h"

//#import "MainViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController
-(void) refresh_on_login
{
    // do not refresh on login;
}
-(void) reload_container_getdata:(bool)update_data
{
    [super reload_container_getdata:update_data];
    if(update_data)
    [  self LoadData];
    else
    [self.homeTable reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
}
-(void)manually_refresh
{
    
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
    
    if(self.isrefreshing)
    {
        [reF endRefreshing];
        return;
    }
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Refreshing"];
    [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
    //    DebugLog(@"refresh!!!!!!!!");
    
}
-(void) LoadData
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(self.isrefreshing)
        {
            return;
        }
        self.isrefreshing=true;
        DebugLog(@"HOMEVIEW BEGIN LOAD");
        
        self.mum.hidden = false;
        [self.mum startAnimating];
        self.mum.center = self.view.center;

        self.label_net_err.hidden=true;
        
        self.homeTable.hidden=true;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            
            //debug
//            NSData* json =[NSData dataWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"home_template" ofType:@"json" ]];
//            NSError *error=nil;
//            NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
//            
//            NSMutableDictionary* data=[jsobj mutableCopy];
            NSMutableDictionary* data=[[iSalesNetwork load_HomePage:0 customid:0] mutableCopy];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                [self.mum stopAnimating];
                
                self.content = data;
                [self.homeTable reloadData];
                self.homeTable.hidden=false;
                if([[data valueForKey:@"result"] intValue]==2)
                {
                    DebugLog(@"HOMEVIEW JSON LOADED!");
                    
                    //debug
                    //                NSData* json =[NSData dataWithContentsOfFile:[[NSBundle mainBundle]  pathForResource:@"button_banner1" ofType:@"json" ]];
                    //                NSError *error=nil;
                    //                NSDictionary *jsobj = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingMutableLeaves error:&error];
                    //                [data setObject:jsobj forKey:@"view_3" ];
                    
                }
                else
                if([[data valueForKey:@"result"] intValue]==RESULT_NET_ERROR)
                {
                    self.label_net_err.hidden=false;
                }
                else
                {
                    [RAUtils message_alert:[data valueForKey:@"err_msg"] title:@"Loading Home" controller:self] ;
                }
                
                self.isrefreshing=false;
                
                
                
            });
        });
    });
}
-(void) ReloadData
{
    UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
    
    [reF endRefreshing];
    
    reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"Pull to refresh"];
    [self LoadData];
    
    
}

- (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;
    
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refresh_btn_click:)];
    //            tap.minimumPressDuration = 0.8; //定义按的时间
    [self.label_net_err addGestureRecognizer:tap];
    
    
    //    [[self navigationController] setNavigationBarHidden:YES animated:NO];
    
    UIRefreshControl *ref = [[UIRefreshControl alloc]init];
    ref.tag = 200 ;
    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.homeTable addSubview:ref];
    
    
    
    
    
    
    
    RATreeView *treeView = [[RATreeView alloc] initWithFrame:self.treeContainer.frame];
    
    treeView.delegate = self;
    treeView.dataSource = self;
    treeView.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
    
    [treeView reloadData];
    //  [treeView expandRowForItem:phone withRowAnimation:RATreeViewRowAnimationLeft]; //expands Row
    [treeView setBackgroundColor:UIColorFromRGB(0xF7F7F7)];
    
    self.treeView = treeView;
    [self.treeContainer addSubview:treeView];
    
    //   UIApplication * app = [UIApplication sharedApplication];
    
    
    
}
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//
//    CGRect rt1 = self.treeContainer.bounds;
//    CGRect rt2 = self.treeContainer.frame;
//
//
//
//    self.treeView.frame = self.treeContainer.bounds;
//}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //    CGRect rt = self.treeContainer.bounds;
    //    CGRect rt1 = self.treeContainer.frame;
    self.treeView.frame = self.treeContainer.bounds;
    
    //    if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
    //        CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
    //        float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;
    //        self.treeView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
    //        self.treeView.contentOffset = CGPointMake(0.0, -heightPadding);
    //    }
    
    //    self.homeTable.contentSize = self
    //     self.scroll.contentSize = self.contentsize;
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    DebugLog(@"!!!!!!!!!!!!!!!!!!!!!route!!!!!!!!!!!!!!!!!!!!!");
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [self.homeTable 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)];
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
  //  UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
    //    if (UIInterfaceOrientationIsLandscape(orientation)|| UIInterfaceOrientationIsPortrait(orientation))
    //    {
    //        self.orientation = orientation;
    //        [self.collectionview.collectionViewLayout invalidateLayout];
    //        DebugLog(@"routed");
    //    }
    
    
    NSDictionary* view_json = [self.content objectForKey:[NSString stringWithFormat:@"view_%ld",(long)indexPath.section ]];
    
    NSString* type = [view_json valueForKeyPath:@"type"];
    if([type isEqualToString:@"slideview"])
    {
        //        if(UIInterfaceOrientationIsPortrait(orientation))
        //        return 400;
        //        else
        //            return 533;
        
        
        int i_width = 981;
        int i_height = 512;
        
        int ui_height = (tableView.frame.size.width * i_height)/i_width;
        return ui_height;
        
    }
    else if([type isEqualToString:@"topicview"])
    {
//        int item_count =[[view_json valueForKey:@"item_count"] intValue];
//        if(UIInterfaceOrientationIsPortrait(orientation))
//        return item_count/4 * 230 +49;
        return 310;
    }
    else if([type isEqualToString:@"banner"])
    {
        //        if(UIInterfaceOrientationIsPortrait(orientation))
        //            return 327;//[[view_json valueForKey:@"height"] intValue];
        
        int i_width = 498;
        int i_height = 197;
        
        int ui_height = (tableView.frame.size.width * i_height)/i_width;
        return ui_height;
        
    }
    else if([type isEqualToString:@"button_banner"])
    {
        int i_width = [[view_json valueForKey:@"width"]intValue];
        int i_height = [[view_json valueForKey:@"height"]intValue];
        float ui_height = (tableView.frame.size.width * i_height)/(float)i_width;
        return ui_height;
    }
    
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    //-----debug!!
    //    if(self.content !=nil)
    //        return 2;
    return [[self.content valueForKeyPath:@"count"]intValue];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary* view_json = [self.content objectForKey:[NSString stringWithFormat:@"view_%ld",(long)indexPath.section ]];
    
    //    NSString* type = [view_json valueForKeyPath:@"type"];
    
    NSString* action = [view_json valueForKeyPath:@"action"];
    
    if([action isEqualToString:@"itemSearch"])
    {
        NSString* covertype = [view_json valueForKeyPath:@"covertype"];
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
        
        [main_vc switchToItemSearch:covertype];
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = nil;
    
    NSDictionary* view_json = [self.content objectForKey:[NSString stringWithFormat:@"view_%ld",(long)indexPath.section ]];
    
    NSString* type = [view_json valueForKeyPath:@"type"];
    if([type isEqualToString:@"slideview"])
    {
        NSString *CellIdentifier = @"HomeTableViewCellSlide";
        cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        // return cell;
        
        for(UIView* v in cell.contentView.subviews)
        {
            [v removeFromSuperview];
            
        }
        
        int i_width = 981;
        int i_height = 512;
        
        int ui_height = (tableView.frame.size.width * i_height)/i_width;
        
        
        
        CycleScrollView *imgScroll =  [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, ui_height)  animationDuration:5];
        imgScroll.autoresizingMask =     UIViewAutoresizingFlexibleHeight  |UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
        int slide_item_count = [[view_json valueForKey:@"count"] intValue];
        //imgScroll.frame =CGRectMake(0, 5, width, 300);
        [imgScroll reset];
        [imgScroll animationDuration:5];
        imgScroll.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];
        
        for(int i = 0;i<slide_item_count;i++)
        {
            NSDictionary * slide_itemjson =[view_json objectForKey:[NSString stringWithFormat:@"item_%d",i] ];
            
            
            SliderPage * tempview = [[SliderPage alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, ui_height)];
            tempview.autoresizingMask =    UIViewAutoresizingFlexibleHeight  |UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
            NSString* img_url = [slide_itemjson valueForKey:@"img"];
            
            
            tempview.contentMode = UIViewContentModeScaleToFill;
            tempview.img_url = img_url;
            //                tempview.url =@"";
            //                tempview.action_type = ;
            //                tempview.params = ;
            
            [imgScroll addPage:tempview];
            
            
            
        }
        
        
        //Capturing strongly  warring;
        __block CycleScrollView *brimgScroll= imgScroll;
        
        imgScroll.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
            
            
            
            SliderPage* page =brimgScroll.arr_Pages[pageIndex];
            [page loadImage];
            
            
            
            return page ;
            
            //                UIImageView * v= viewsArray[pageIndex];
            //                return viewsArray[pageIndex];
        };
        imgScroll.totalPagesCount = ^NSInteger(void){
            return brimgScroll.arr_Pages.count; //viewsArray.count;
        };
        imgScroll.TapActionBlock = ^(NSInteger pageIndex){
            DebugLog(@"点击了第%ld个",(long)pageIndex);
            //            NSDictionary * slide_itemjson =[view_json objectForKey:[NSString stringWithFormat:@"item_%d",pageIndex] ];
            //
            //            NSString*
            //
            //            DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
            ////            dvc
            //
            //            dvc.product_id=@"5008";
            //            dvc.category_id=@"003001";
            //            dvc.ispush = true;
            //
            //            [dvc reload];
            //            [self.navigationController pushViewController:dvc animated:true];
        };
        
        [cell.contentView addSubview:imgScroll];
        
        
        
    }
    else if([type isEqualToString:@"topicview"])
    {
        
//        NSString *CellIdentifier = @"HomeTableViewCellTopic";
//        cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//        
//        // NSDictionary * topicview_json =[topicjson objectForKey:[NSString stringWithFormat:@"topicview_%d",i] ];
//        int item_count =[[view_json valueForKey:@"item_count"] intValue];
//        NSString * topictitle =[view_json valueForKey:@"title"];
//        
//        
//        TopicViewController* topicview = [self.storyboard instantiateViewControllerWithIdentifier:@"TopicViewController"];
//        topicview.content = view_json;
//        [topicview itemCount:item_count];
//        
//        topicview.view.frame = CGRectMake(0, 0, self.view.frame.size.width, item_count/4 * 230 +49);
//        CGRect rt = topicview.TopicCollection.frame;// =CGRectMake(0, 20+29, self.view.frame.size.width, item_count/4 * 230);
//        rt.size.height = item_count/4 * 230;
//        topicview.TopicCollection.frame = rt;
//        //                [topicview.TopicCollection sizeToFit];
//        //                [topicview.view sizeToFit];
//        topicview.topicTitle.text = topictitle;
//        topicview.rootViewController = self.parentViewController;
        
//
//        
//        
//        [cell.contentView addSubview:topicview.view];
        
        
        NSString *CellIdentifier = @"HomeTableViewCellTopic";
        
        
        
        // NSDictionary* section_json = [self.detail_data objectForKey:@"related_model"];
        HomeTableViewCellTopic * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.itemdelegate = self;
        cell.related_data = view_json;
        [cell.topicCollectionView reloadData];
        
        
        
         
        NSString * topictitle =[view_json valueForKey:@"title"];
        cell.label_title.text =topictitle;
        
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
        
    }
    else if([type isEqualToString:@"banner"])
    {
        
        NSString *CellIdentifier = @"HomeTableViewCellBanner";
        cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        HomeTableViewCellBanner * bannercell=cell;
        NSString* img_url =[view_json valueForKeyPath:@"img"];
        NSString* file_name=[img_url lastPathComponent];
        NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
        if(img_data!=nil)
        {
            
            UIImage * img =[UIImage imageWithData:img_data];
            bannercell.BannerImageView.image = img;
        }
        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 filename:file_name saveTo:img_url];
                        
                        UIImage * img =[UIImage imageWithData:downloadimg_data];
                        bannercell.BannerImageView.image = img;
                    }
                    else
                    bannercell.BannerImageView.image=[UIImage imageNamed:@"notfound_l"];
                });
            });
            
            
        }
        cell.backgroundColor = [UIColor whiteColor];
        
        
  
        
    }
    else if([type isEqualToString:@"button_banner"])
    {
        
        
        //        CellIdentifier = @"CommonEditorCellEdit";
        //        UITableViewCell * cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        //        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        //        cell.backgroundColor = [UIColor whiteColor];
        //        return cell;
        
        int cell_width = [[view_json valueForKey:@"width"]intValue];
        int cell_height = [[view_json valueForKey:@"height"]intValue];
        float ui_height = (tableView.frame.size.width * cell_height)/(float)cell_width;
        float ui_width = tableView.frame.size.width ;
        NSString *CellIdentifier = @"HomeTableViewCellButtonBanner";
        cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        //   HomeTableViewCellButtonBanner * bannercell=(HomeTableViewCellButtonBanner*)cell;
        for(UIView* v in cell.contentView.subviews)
        {
            [v removeFromSuperview];
        }
        
        int count = [[view_json valueForKey:@"count"] intValue];
        
        for(int i_item = 0;i_item<count;i_item++)
        {
            NSDictionary* item_json = [view_json objectForKey:[NSString stringWithFormat:@"item_%d",i_item]];
            int x = [[item_json valueForKey:@"x"]intValue];
            int y = [[item_json valueForKey:@"y"]intValue];
            
            int i_width = [[item_json valueForKey:@"width"]intValue];
            int i_height = [[item_json valueForKey:@"height"]intValue];
            
            float f_width = i_width/(cell_width/ui_width);
            float f_htight = i_height/(cell_height/ui_height);
            
            float fx = x/(cell_width/ui_width);
            float fy = y/(cell_height/ui_height);
            UIButton* btn_item = [[UIButton alloc] initWithFrame:CGRectMake(fx, fy, f_width, f_htight)];
            long tag = indexPath.section*1000+ indexPath.row*100+i_item;
            btn_item.tag = tag;
            [btn_item addTarget:self action:@selector(ButtonBannerClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [cell.contentView addSubview:btn_item];
            NSString* img_url =[item_json valueForKeyPath:@"img"];
            NSString* file_name=[img_url lastPathComponent];
            NSData* img_data=[iSalesDB load_cached_img:file_name loadFrom:img_url];
            if(img_data!=nil)
            {
                
                UIImage * img =[UIImage imageWithData:img_data];
                [btn_item setBackgroundImage:img forState:UIControlStateNormal];
            }
            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 filename:file_name saveTo:img_url];
                            
                            UIImage * img =[UIImage imageWithData:downloadimg_data];
                            [btn_item setBackgroundImage:img forState:UIControlStateNormal];
                        }
                        else
                        [btn_item setBackgroundImage:[UIImage imageNamed:@"notfound_l"] forState:UIControlStateNormal];
                        
                    });
                });
                
                
            }
            
            
            
        }
        cell.backgroundColor = [UIColor whiteColor];
        
        
        //        // NSDictionary * topicview_json =[topicjson objectForKey:[NSString stringWithFormat:@"topicview_%d",i] ];
        //        int item_count =[[view_json valueForKey:@"item_count"] intValue];
        //        NSString * topictitle =[view_json valueForKey:@"title"];
        //
        //
        //
        //
        //
        //
        //        TopicViewController* topicview = [self.storyboard instantiateViewControllerWithIdentifier:@"TopicViewController"];
        //        topicview.content = view_json;
        //        [topicview itemCount:item_count];
        //
        //        topicview.view.frame = CGRectMake(0, 0, self.view.frame.size.width, item_count/4 * 230 +49);
        //        CGRect rt = topicview.TopicCollection.frame;// =CGRectMake(0, 20+29, self.view.frame.size.width, item_count/4 * 230);
        //        rt.size.height = item_count/4 * 230;
        //        topicview.TopicCollection.frame = rt;
        //        //                [topicview.TopicCollection sizeToFit];
        //        //                [topicview.view sizeToFit];
        //        topicview.topicTitle.text = topictitle;
        //        topicview.rootViewController = self.parentViewController;
        //
        //
        //
        //
        //        [cell.contentView addSubview:topicview.view];
        
    }
    return cell;
    
    
}
-(void)ButtonBannerClick:(id)sender{
    //这个sender其实就是UIButton，因此通过sender.tag就可以拿到刚才的参数
    int tag = [sender tag];
    int section = tag/1000;
    int row = (tag-section*1000)/100;
    int idx =(tag-section*1000 - row*100);
    NSDictionary* view_json = [self.content objectForKey:[NSString stringWithFormat:@"view_%ld",(long)section ]];
    NSDictionary* item_json = [view_json objectForKey:[NSString stringWithFormat:@"item_%d",idx]];
    NSString* action = [item_json valueForKeyPath:@"action"];
    
    if([action isEqualToString:@"itemSearch"])
    {
        NSString* covertype = [item_json valueForKeyPath:@"covertype"];
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
        
        [main_vc switchToItemSearch:covertype];
    }
    else if([action isEqualToString:@"category"])
    {
        NSString* cid = [item_json valueForKeyPath:@"category_id"];
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
        
        [main_vc switchToCagegory:cid];
    }
    else if([action isEqualToString:@"webview"])
    {
        NSString* url = [item_json valueForKeyPath:@"url"];
        
        
        NSString* title = [item_json valueForKeyPath:@"title"];
//        UIApplication * app = [UIApplication sharedApplication];
//        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
//        MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
//        
//        
        
        WebViewController *ViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebViewController"];
        ViewController.url = url;
        ViewController.title = title;
        
 
        
        [self.navigationController pushViewController:ViewController animated:YES];
        
    }
}
#pragma mark TreeView Delegate methods
- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 47;
}

- (NSInteger)treeView:(RATreeView *)treeView indentationLevelForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 3 * treeNodeInfo.treeDepthLevel;
}

- (BOOL)treeView:(RATreeView *)treeView shouldExpandItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return YES;
}

- (BOOL)treeView:(RATreeView *)treeView shouldItemBeExpandedAfterDataReload:(id)item treeDepthLevel:(NSInteger)treeDepthLevel
{
    if ([item isEqual:self.expanded]) {
        return YES;
    }
    
    return NO;
}
- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    
    NSDictionary *data = item;
    int count = [[data valueForKey:@"count"] intValue];
    if(count==0)
    {
        //        NSString* category = [data valueForKey:@"id"];
        
        //        if (self.CateMenu_delegate && [self.CateMenu_delegate respondsToSelector:@selector(SelectCategory:)]) {
        //            [self.CateMenu_delegate SelectCategory:category];
        //        }
        //        /* MainViewController* pvc = (MainViewController*)self.rootViewController;
        //         [pvc switchToCagegory:category];*/
        //        [self dismissViewControllerAnimated:YES
        //                                 completion:^{
        //                                     //一定要移除手势 否则下次 没有子视图的时候 点击 会崩溃拉
        //                                     AppDelegate *app = [[UIApplication sharedApplication] delegate];
        //                                     [app.window removeGestureRecognizer:self.tapGesture];
        //                                 }];
    }
    
    //    if (item == nil) {
    //        NSDictionary * ret =[self.categoryMenu objectForKey:[NSString stringWithFormat:@"category_%d",index] ];
    //
    //    }
    //    else
    //        data=[data objectForKey:[NSString stringWithFormat:@"category_%d",index]];
    DebugLog(@"menu select %@",data);
}

- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.backgroundColor = UIColorFromRGB(0xF7F7F7);
    } else if (treeNodeInfo.treeDepthLevel == 1) {
        cell.backgroundColor = UIColorFromRGB(0xD1EEFC);
    } else if (treeNodeInfo.treeDepthLevel == 2) {
        cell.backgroundColor = UIColorFromRGB(0xE0F8D8);
    }
}

#pragma mark TreeView Data Source

- (UITableViewCell *)treeView:(RATreeView *)treeView cellForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    //  NSInteger numberOfChildren = [treeNodeInfo.children count];
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    //    if(numberOfChildren>0)
    //        cell.detailTextLabel.text = [NSString stringWithFormat:@"Number of children %@", [@(numberOfChildren) stringValue]];
    cell.textLabel.text = [((NSDictionary *)item) valueForKey:@"title"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.detailTextLabel.textColor = [UIColor blackColor];
    }
    
    return cell;
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
    if (item == nil) {
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        return [[appDelegate.categoryMenu valueForKey:@"count" ] intValue];
        //   return [self.data count];
    }
    
    NSDictionary* data = item;
    return [[data valueForKey:@"count"] intValue];
    //  RADataObject *data = item;
    //  return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item
{
    NSDictionary *data = item;
    
    if (item == nil) {
        
        UIApplication * app = [UIApplication sharedApplication];
        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        NSDictionary * ret =[appDelegate.categoryMenu objectForKey:[NSString stringWithFormat:@"category_%ld",(long)index] ];
        return  ret;
    }
    
    return[data objectForKey:[NSString stringWithFormat:@"category_%ld",(long)index]];
    /*
     
     RADataObject *data = item;
     if (item == nil) {
     return [self.data objectAtIndex:index];
     }
     
     return [data.children objectAtIndex:index];
     */
}
#pragma mark - Topic cell delegate
-(void) TopicItemClicked:(NSString*) product_id category:(NSString*) category
{
    DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
    //            dvc
    
    dvc.product_id=product_id;
    dvc.category_id=category;
    dvc.ispush=true;
    [dvc reload];
    [self.navigationController pushViewController:dvc animated:true];
}
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    MainViewController* pvc = (MainViewController*)self.parentViewController;
// //   [pvc categoryMenuSelected:indexPath.row];
//}
@end
