//
//  CategoryFilterViewController.m
//  iSales-NPD
//
//  Created by Ray on 3/4/16.
//  Copyright © 2016 United Software Applications, Inc. All rights reserved.
//

#import "CategorySearchFilterViewController.h"
#import "AppDelegate.h"
#import "DefaultAppearance.h"
#import "RAUtils.h"


@interface CategorySearchFilterViewController ()

@end

@implementation CategorySearchFilterViewController


-(void) initUI{
    self.textModelName.text = self.modelname;
    
    self.textModelDescription.text = self.modeldescrip;
    
    UIApplication * app = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
    if(appDelegate.bLogin)
    {
        self.labelPrice.hidden=false;
        self.buttonPrice.hidden=false;
        
    }
    else
    {
        self.labelPrice.hidden=true;
        self.buttonPrice.hidden=true;
    }
    
    
    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
                                                                    style:UIBarButtonItemStylePlain
                                                                   target:self
                                                                   action:@selector( onCloseClick:)];
    
    
    self.navigationItem.rightBarButtonItem = closeButton;
    
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    
    {
        
        NSString* qty =@"";
        int count = [[self.qty_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.qty_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                qty = [qty stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        if(qty.length>0)
            [self.buttonQTY setTitle:qty forState:UIControlStateNormal];
        
    }
    
    
    {
        
        NSString* price =@"";
        int count = [[self.price_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.price_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                price = [price stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        if(price.length>0)
            [self.buttonPrice setTitle:price forState:UIControlStateNormal];
        
    }
    
    {
        
        NSString* availiablity =@"";
        int count = [[self.availability_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.availability_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                availiablity = [availiablity stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        if(availiablity.length>0)
            [self.buttonAvailability setTitle:availiablity forState:UIControlStateNormal];
        
    }
    
    {
        NSString* alert =@"";
        int count = [[self.alert_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.alert_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                alert = [alert stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        if(alert.length>0)
            [self.buttonAlert setTitle:alert forState:UIControlStateNormal];
    }
    
    
    {
        NSString* bestseller =@"";
        int count = [[self.bestseller_cadedate valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[self.bestseller_cadedate objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                bestseller = [bestseller stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        if(bestseller.length>0)
            [self.buttonBestSeller setTitle:bestseller forState:UIControlStateNormal];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    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;
    //    treeView.allowsSelection = true;
    //    treeView.allowsMultipleSelection = true;
    
    /*
     
     UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 100.000001)];
     
     [line setBackgroundColor:[UIColor clearColor]];
     self.treeView.treeHeaderView = line;
     */
    
    
    NSString* value =[DefaultAppearance get_noneappearance_value:@"DefaultColor" valuename:@"frontcolor"];
    
    if(value==nil)
        value=@"";
    unsigned long frontcolor = strtoul([value UTF8String],0,16);
    
    UILabel *CategoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5.5, self.view.frame.size.width, 33)];
    CategoryLabel.textColor=UIColorFromRGB(frontcolor);
    //    CategoryLabel.backgroundColor = [UIColor redColor];
    CategoryLabel.text=NSLocalizedString(@" Category", nil);
    //    [CategoryLabel sizeToFit];
    
    self.treeView.treeHeaderView = CategoryLabel;
    
    [self.treeContainer addSubview:treeView];

//    self.treeView.layer.shadowPath =[UIBezierPath bezierPathWithRect:self.treeView.bounds].CGPath;
//    self.treeView.layer.masksToBounds = false;
//    //添加四个边阴影
//    
//    self.treeView.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.treeView.layer.shadowOffset = CGSizeMake(0, 0);
//    self.treeView.layer.shadowOpacity = 0.5;
//    self.treeView.layer.shadowRadius = 2.0;
    self.treeView.layer.borderColor=[UIColor lightGrayColor].CGColor;
        self.treeView.layer.borderWidth = 0.5;
//        self.treeView.layer.shadowRadius = 2.0;

    [self initUI];

    // Do any additional setup after loading the view.
}

- (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.
 }
 */
-(NSMutableDictionary*) resetFilter:(NSMutableDictionary*)filter
{
    NSString* str= [RAUtils dict2string:filter];
    str=[str stringByReplacingOccurrencesOfString:@"\"check\":1" withString:@"\"check\":0"];
    str=[str stringByReplacingOccurrencesOfString:@"\"check\":\"1\"" withString:@"\"check\":\"0\""];
    filter=[[RAUtils string2dict:str]mutableCopy];
    filter[@"model_name"]=@"";
    filter[@"model_description"]=@"";
    filter[@"price"][@"val_0"][@"check"]=@"1";
    filter[@"alert"][@"val_0"][@"check"]=@"1";
    filter[@"qty"][@"val_0"][@"check"]=@"1";
    filter[@"availability"][@"val_0"][@"check"]=@"1";
    filter[@"best_seller"][@"val_1"][@"check"]=@"1";
    return filter;
}
- (IBAction)onResetClick:(id)sender {
    
    self.default_filter= [self resetFilter:self.default_filter];
    
    
    //  self.default_filter = [self.default_filter mutableCopy];
    
 //   self.categoryMenu = [self.default_filter objectForKey:@"category"];
    self.alert_cadedate =[self.default_filter objectForKey:@"alert"];
    self.modelname=[self.default_filter valueForKey:@"model_name"];
    self.modeldescrip=[self.default_filter valueForKey:@"model_description"];
    
    
    self.qty_cadedate=[self.default_filter objectForKey:@"qty"];
    self.availability_cadedate=[self.default_filter objectForKey:@"availability"];
    self.price_cadedate=[self.default_filter objectForKey:@"price"];
    self.bestseller_cadedate=[self.default_filter objectForKey:@"best_seller"];
    
    
    [self initUI];
}
- (IBAction)onCloseClick:(id)sender {
    [self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)onAvailabilityClick:(id)sender {
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
  //  enumvc.delegate = self;
    enumvc.max_select = 1;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = [self.availability_cadedate mutableCopy];
    enumvc.title = @"";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =true;
    
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        self.availability_cadedate = value;
        
        
        NSString* available =@"";
        int count = [[value valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[value objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                available = [available stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        
        [self.buttonAvailability setTitle:available forState:UIControlStateNormal];
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
}

- (IBAction)onBestSellerClick:(id)sender {
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
    //   enumvc.delegate = self;
    enumvc.max_select = 1;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = [self.bestseller_cadedate mutableCopy];
    enumvc.title = @"";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =true;
    
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        self.bestseller_cadedate = value;
        
        
        NSString* qty =@"";
        int count = [[value valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[value objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                qty = [qty stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        
        [self.buttonBestSeller setTitle:qty forState:UIControlStateNormal];
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
}

- (IBAction)onQTYClick:(id)sender {
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
 //   enumvc.delegate = self;
    enumvc.max_select = 1;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = [self.qty_cadedate mutableCopy];
    enumvc.title = @"";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =true;
    
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        self.qty_cadedate = value;
        
        
        NSString* qty =@"";
        int count = [[value valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[value objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                qty = [qty stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        
        [self.buttonQTY setTitle:qty forState:UIControlStateNormal];
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
}
- (IBAction)onPriceClick:(id)sender {
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
    //   enumvc.delegate = self;
    enumvc.max_select = 1;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = [self.price_cadedate mutableCopy];
    enumvc.title = @"";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =true;
    
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        self.price_cadedate = value;
        
        
        NSString* price =@"";
        int count = [[value valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[value objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                price = [price stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        
        [self.buttonPrice setTitle:price forState:UIControlStateNormal];
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
}
- (IBAction)onAlertClick:(id)sender {
    
    
    
    
    
    
    
    EnumSelectViewController* enumvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"EnumSelectorViewController"];
 //   enumvc.delegate = self;
    enumvc.max_select = 1;
    //enumvc.updatePosition = indexPath;
    //        if([[required lowercaseString] isEqualToString:@"true"])
    //        enumvc.canbeEmpty = false;
    //        else
    //        enumvc.canbeEmpty =true;
    enumvc.cadedate = [self.alert_cadedate mutableCopy];
    enumvc.title = @"";
    //       enumvc.value = [value_json mutableCopy];
    enumvc.single_select =true;
    
    enumvc.returnValue = ^(NSMutableDictionary* value){
        self.alert_cadedate = value;
        
        
        NSString* alert =@"";
        int count = [[value valueForKey:@"count"] intValue];
        for(int i=0;i<count;i++)
        {
            NSDictionary* val_json =[value objectForKey:[NSString stringWithFormat:@"val_%d",i]];
            int check = [[val_json valueForKey:@"check"] intValue];
            if(check==1)
            {
                alert = [alert stringByAppendingString:[val_json valueForKey:@"value"]];
                break;
            }
        }
        
        [self.buttonAlert setTitle:alert forState:UIControlStateNormal];
    };
    
    [self.navigationController pushViewController:enumvc animated:true];
    
}
- (IBAction)onSearchClick:(id)sender {
    
    NSString* modelname = self.textModelName.text;
    if(modelname.length==0)
        modelname = nil;
    
    NSString* modeldescrip = self.textModelDescription.text;
    if(modeldescrip.length==0)
        modeldescrip = nil;
    
    NSString* qty = [self.buttonQTY titleForState:UIControlStateNormal];
    if(qty.length==0 || [qty isEqualToString:@"Click to select"])
        qty = nil;
    
    NSString* price = [self.buttonPrice titleForState:UIControlStateNormal];
    if(price.length==0 || [price isEqualToString:@"Click to select"])
        price = nil;
    
    NSString* available = [self.buttonAvailability titleForState:UIControlStateNormal];
    if(available.length==0 || [available isEqualToString:@"Click to select"])
        available = nil;
    
    NSString* alert = [self.buttonAlert titleForState:UIControlStateNormal];
    if(alert.length==0 || [alert isEqualToString:@"Click to select"])
        alert = nil;
    
    NSString* bestseller = [self.buttonBestSeller titleForState:UIControlStateNormal];
    if(bestseller.length==0 || [bestseller isEqualToString:@"Click to select"])
        alert = nil;

    
    if(self.OkClick)
        self.OkClick( modelname, modeldescrip,available, qty, alert,price,bestseller);
    [self dismissViewControllerAnimated:true completion:nil];
}
#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[@"id"] isEqualToString:self.categoryid] )
        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* _id =  [data valueForKey:@"cid"];
//        
//        NSDictionary* ddd=[self check:_id source:[self.categoryMenu mutableCopy]];
//        self.categoryMenu=ddd;
//        UITableViewCell *cell = (UITableViewCell *)[self.treeView cellForItem:item];
//        
//        
//        
//        int check=[self is_check:_id source:self.categoryMenu];
//        if(check==1)
//            cell.accessoryType = UITableViewCellAccessoryCheckmark;
//        else
//            cell.accessoryType=UITableViewCellAccessoryNone;
//        
//        
//        
//    }
//    
//    
//    
//    
//    
//    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);
//    }
//}

- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    } 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;
    cell.accessoryType =UITableViewCellAccessoryNone;
    //  if (treeNodeInfo.treeDepthLevel == 0) {
    //      cell.detailTextLabel.textColor = [UIColor blackColor];
    NSString* _id =  [((NSDictionary *)item) valueForKey:@"cid"];
    //    int check=[self is_check:_id source:self.categoryMenu];
    if([[((NSDictionary *)item) valueForKey:@"id"] isEqualToString:self.categoryid]&& [item[@"count"] intValue]==0)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
        cell.accessoryType =UITableViewCellAccessoryNone;
    
    
    
    
    return cell;
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
    if (item == nil) {
        
        //        UIApplication * app = [UIApplication sharedApplication];
        //        AppDelegate *appDelegate = (AppDelegate *)[app delegate];
        return [[self.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 =[self.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];
     */
}

@end
