//
//  SelectStoreViewController.m
//  redstar
//
//  Created by admin on 15/12/13.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "SelectStoreViewController.h"
#import "SelectStoreHeadView.h"
#import "CheckBoxButton.h"

#import "HttpClient.h"
#import <MBProgressHUD.h>

#import "TreeView.h"
#import "TreeNodeModel.h"

@interface SelectStoreViewController () <TreeDelegate>
@property (nonatomic, strong) SelectStoreHeadView *headerView;
@property (nonatomic, strong) TreeView *treeView;
@property (nonatomic, strong) UIButton *sureButton;

@property (nonatomic, strong) NSMutableArray *allTreeArray;

@property (nonatomic, strong) NSMutableArray *selectTreeArray;

@end

@implementation SelectStoreViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    self.view.backgroundColor = kFootViewBackGroundColor;
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"选择商场"];
    customLab.font = [UIFont boldSystemFontOfSize:19];
    self.navigationItem.titleView = customLab;
    
    self.allTreeArray = [NSMutableArray array];
    self.selectTreeArray = [NSMutableArray array];

    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    
    [backBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.treeView.backgroundColor = [UIColor whiteColor];
    [self requestQueryLowerOrgs];
    
    [self.sureButton addTarget:self action:@selector(sureClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)resetClick:(UIButton *)sender
{
    
}

- (void)sureClick:(UIButton *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(deliverWithArray:)]) {
        [_delegate deliverWithArray:self.treeView.selectTreeArray];
    }
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)doBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)requestQueryLowerOrgs
{
    NSString *url = [NSString stringWithFormat:@"%@%@", kRedStarURL, kQueryLowerOrgsURL];
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    NSDictionary *parameters = @{@"path":@"",
                                 @"pageNumber":@(0),
                                 @"pageSize":@(999)
                                 };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpClient queryLowerOrgsWithParameters:parameters completion:^(id response, NSError *error) {
        NSDictionary *data = response[@"data"];
        NSArray *dataArray = data[@"records"];
        NSMutableArray *oneTree = [NSMutableArray array];
        NSMutableArray *twoTree = [NSMutableArray array];
        NSMutableArray *threeTree = [NSMutableArray array];
        NSMutableArray *fourTree = [NSMutableArray array];
        for (NSDictionary *dict in dataArray) {
            TreeNodeModel *tree = [[TreeNodeModel alloc] init];
            [tree setValuesForKeysWithDictionary:dict];
            [_allTreeArray addObject:tree];

            if (tree.level == 1) {
                [oneTree addObject:tree];
            } else if (tree.level == 2) {
                [twoTree addObject:tree];
            } else if (tree.level == 3){
                [threeTree addObject:tree];
            } else {
                [fourTree addObject:tree];
            }
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (oneTree.count == 0) {
            return;
        }
        
        TreeNodeModel *tree1 = oneTree[0];
        for (int k = 0; k < twoTree.count; k++) {
            TreeNodeModel *tree2 = twoTree[k];
            if ([tree2.upper isEqualToString:tree1.code]) {
                [tree1 insertChild:tree2];
            }
        }
        
        for (int i = 0; i < twoTree.count; i++) {
            TreeNodeModel *tree2 = twoTree[i];
            for (int k = 0; k < threeTree.count; k++) {
                TreeNodeModel *tree3 = threeTree[k];
                if ([tree3.upper isEqualToString:tree2.code]) {
                    [tree2 insertChild:tree3];
                }
            }

        }
        
        for (int i = 0; i < threeTree.count; i++) {
            TreeNodeModel *tree3 = threeTree[i];
            for (int k = 0; k < fourTree.count; k++) {
                TreeNodeModel *tree4 = fourTree[k];
                if ([tree4.upper isEqualToString:tree3.code]) {
                    [tree3 insertChild:tree4];
                }
            }
            
        }
        self.treeView.nodeData = tree1;
        [self.treeView reloadData];
    }];
}

#pragma mark - TreeDelegate
- (void)tree:(TreeView *)tree didClickTitleAtNode:(TreeNodeCell *)node
{
    node.titleButton.selected = !node.titleButton.selected;
    node.nodeData.isChoose = node.titleButton.selected;
    NSString *path = node.nodeData.path;
    
    // 对子类做处理
    if (node.nodeData.isChoose) {
        for (TreeNodeModel *model in _allTreeArray) {
            if (model.path.length < path.length) {
                continue;
            }

            NSString *modelPath = [model.path substringToIndex:path.length];
            if ([path isEqualToString:modelPath]) {
                model.isChoose = YES;
            }
        }
    } else {
        for (TreeNodeModel *model in _allTreeArray) {
            if (model.path.length < path.length) {
                continue;
            }
            NSString *modelPath = [model.path substringToIndex:path.length];
            if ([path isEqualToString:modelPath]) {
                model.isChoose = NO;
            }
        }
    }
    
    NSMutableArray *chooseArray = [NSMutableArray array];
    for (TreeNodeModel *model in _allTreeArray) {
        if (model.isChoose == YES) {
            [chooseArray addObject:model];
        }
    }
    
    NSMutableArray *repeatArray = [NSMutableArray array];
    for (int i = 0; i < chooseArray.count; i++) {
        TreeNodeModel *tree1 = chooseArray[i];
        for (int j = 0; j < chooseArray.count; j++) {
            TreeNodeModel *tree2 = chooseArray[j];
            if ([tree1.code isEqualToString:tree2.upper]) {
                [repeatArray addObject:tree2];
            }
        }
    }
    
    [chooseArray removeObjectsInArray:repeatArray];
    
    self.treeView.selectTreeArray = chooseArray;
    [self.treeView reloadData];
}

- (TreeView *)treeView
{
    if (!_treeView) {
        _treeView = [[TreeView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 70)];
        _treeView.treeDelegate = self;
       // _treeView.tableHeaderView = self.headerView;
        
        _treeView.tableFooterView = [UIView new];
        [self.view addSubview:_treeView];
    }
    return _treeView;
}

- (SelectStoreHeadView *)headerView
{
    if (!_headerView) {
        _headerView = [[SelectStoreHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    }
    return _headerView;
}


- (UIButton *)sureButton
{
    if (!_sureButton) {
        _sureButton = [[UIButton alloc] initWithFrame:CGRectMake(20, kScreenHeight - 64 - 55, kScreenWidth - 40, 40)];
        _sureButton.backgroundColor = kNavigationBarColor;
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
        [self.view addSubview:_sureButton];
    }
    return _sureButton;
}


@end
