//
//  ReportViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/11/6.
//  Copyright © 2015年 Xummer. All rights reserved.
// 报表

#import "ReportViewController.h"
#import "SaleViewController.h"
#import "PassengerViewController.h"
#import "PassgerPriceViewController.h"
#import "GrossRateViewController.h"
#import "CustomSegView.h"
#import "FinishTimeView.h"
#import "SearchReportViewController.h"
#import "OrgCompass.h"
@interface ReportViewController ()<UIScrollViewDelegate,CustomSegViewDelegate,FinishTimeViewDelegate>
{
    SaleViewController *svc;
    PassengerViewController *pvc;
    PassgerPriceViewController *ppvc;
    GrossRateViewController *gvc;
}
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,assign)NSInteger currentPage;
@property (nonatomic,strong)CustomSegView *segView;
@property (nonatomic,strong)NSString *dayType;
@property (nonatomic,strong)FinishTimeView *startTimeView;
@property (nonatomic,strong)NSString *scopeType;
@property (nonatomic,strong)NSString *selectDay;
@property (nonatomic,strong)NSString *selectMonth;
@property (nonatomic,strong)NSString *selectWeek;
//组织范围
@property (nonatomic,strong)NSString *orgScope;
//数据源数组
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)NSMutableArray *totalArr;
@property (nonatomic,strong)Compass *compass;
@property (nonatomic,assign)NSInteger storeCount;
@property (nonatomic,strong)NSIndexPath *currentIndex;
@property (nonatomic,strong)NSMutableArray *selectArr;

@end

@implementation ReportViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNextDetailData:) name:KNOTIFICATION_GetNextDetailData object:nil];
    }
    return self;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //布局
#if 0
    self.dataArr = [NSMutableArray array];
    self.totalArr = [NSMutableArray array];
    self.selectArr = [NSMutableArray array];
    [self bulidLayout];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:ReportColor] forBarMetrics:UIBarMetricsDefault];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchClick)];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    self.dayType = @"day";
     self.scopeType = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM-dd"];
    [self getDataFromServer];
#else
    CGRect rect = CGRectMake(0, 200, self.view.width, 30);
    IBTUILabel *lbl = [[IBTUILabel alloc]initWithFrame:rect];
    lbl.text = @"哎呦，功能还没实现呢，下次再来看看吧。";
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:15];
    lbl.textColor = GXF_NAVIGAYION_COLOR;
    [self.view addSubview:lbl];
#endif
}
- (void)searchClick{
    SearchReportViewController *srvc = [SearchReportViewController new];
    [self PushViewController:srvc animated:YES];
}

#pragma mark - 假数据
- (void)setTestValue{
    Compass *compass = [[Compass alloc]init];
    compass.dateScope = @"2012-03-04";
    compass.sales = @"222,33";
    compass.salesChainSign = ReportChainSignPlus;
    compass.salesChainRate = @12.35;
    compass.salesYoYSign = ReportChainSignPlus;
    compass.salesYoYRate = @33.43;
    compass.salesTargetRate = @55.5;
    compass.dailysalesPerStore = @"98.4";
    compass.passengerdate = @"2015-04-06";
    compass.passenger = @"345.44";
    compass.passengerChainSign = ReportChainSignMinus;
    compass.passengerChainRate = @44.5;
    compass.passengerYoYSign = ReportChainSignPlus;
    compass.passengerYoYRate = @33.4;
    compass.persalesdate = @"2013-07-04";
    compass.persales = @"332,55";
    compass.persalesChainSign = ReportChainSignPlus;
    compass.persalesChainRate = @66;
    compass.persalesYoYRate = @44.4;
    compass.persalesYoYSign = ReportChainSignMinus;
    compass.grossprofitdate = @"2001-03-04";
    compass.grossprofitChainSign = ReportChainSignPlus;
    compass.grossprofitChainRate = @11.11;
    compass.grossprofitYoYSign = ReportChainSignMinus;
    compass.grossprofitYoYRate = @44.55;
    self.compass = compass;
}
- (NSArray *)setOrgTestValue{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        OrgCompass *compass = [[OrgCompass alloc]init];
        compass.orguuid = [NSString stringWithFormat:@"%d",i+1];
        compass.orgname = [NSString stringWithFormat:@"00%d第一片区",i];
        compass.isleaf = NO;

        compass.sales = @"222,33";
        compass.salesChainSign = ReportChainSignPlus;
        compass.salesChainRate = @12.3;
        compass.salesTargetRate = @55.5;
        
        compass.passenger = @"345.44";
        compass.passengerChainSign = ReportChainSignMinus;
        compass.passengerChainRate = @44.5;
        
        compass.persales = @"332,55";
        compass.persalesChainSign = ReportChainSignPlus;
        compass.persalesChainRate = @66;
        
        
        compass.grossprofit = @"4444";
        compass.grossprofitChainSign = ReportChainSignPlus;
        compass.grossprofitChainRate = @11.11;
        compass.expand = YES;
        compass.level = 0;
        [arr addObject:compass];
    }
    return arr;
}
- (NSArray *)setTwoOrgTestValue{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        OrgCompass *compass = [[OrgCompass alloc]init];
        compass.parentuuid = @"1";
        compass.orguuid = [NSString stringWithFormat:@"%d",i+6];
        compass.orgname = [NSString stringWithFormat:@"00%d第一片区",i];
        compass.isleaf = NO;
        
        compass.sales = @"222,33";
        compass.salesChainSign = ReportChainSignPlus;
        compass.salesChainRate = @12.3;
        compass.salesTargetRate = @55.57;
        
        compass.passenger = @"345.44";
        compass.passengerChainSign = ReportChainSignMinus;
        compass.passengerChainRate = @44.5;
        
        compass.persales = @"332,55";
        compass.persalesChainSign = ReportChainSignPlus;
        compass.persalesChainRate = @66;
        
        
        compass.grossprofit = @"4444";
        compass.grossprofitChainSign = ReportChainSignPlus;
        compass.grossprofitChainRate = @11.11;
        compass.expand = NO;
        compass.level = 1;
        [arr addObject:compass];
    }
    return arr;
}
- (NSArray *)setThreeOrgTestValue{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 5; i++) {
        OrgCompass *compass = [[OrgCompass alloc]init];
        compass.parentuuid = @"6";
        compass.orguuid = [NSString stringWithFormat:@"%d",i+11];
        compass.orgname = [NSString stringWithFormat:@"00%d第一片区",i];
        compass.isleaf = NO;
        
        compass.sales = @"222,33";
        compass.salesChainSign = ReportChainSignPlus;
        compass.salesChainRate = @12.3;
        compass.salesTargetRate = @55.5;
        
        compass.passenger = @"345.44";
        compass.passengerChainSign = ReportChainSignMinus;
        compass.passengerChainRate = @44.5;
        
        compass.persales = @"332,55";
        compass.persalesChainSign = ReportChainSignPlus;
        compass.persalesChainRate = @66;
        
        
        compass.grossprofit = @"4444";
        compass.grossprofitChainSign = ReportChainSignPlus;
        compass.grossprofitChainRate = @11.11;
        compass.expand = NO;
        compass.level = 2;
        [arr addObject:compass];
    }
    return arr;
}
#pragma mark - 获取上部数据
- (void)getDataFromServer{
    
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        //赋值
        [strongSelf prepareDataInScrollView:data];
        [strongSelf getBottomData:nil];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
#warning 测试数据
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [self setTestValue];
        [self setValueInScrollView];
        [strongSelf getBottomData:nil];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    NSDictionary *dict = @{
                           @"userUuid":userUtil.userId,
                           @"dateScopeType":self.dayType,
                           @"dateScope":self.scopeType,
                           @"orgScopeType":@"all",
                           @"orgScope":@""
                           };
    [[ICRHTTPController sharedController] queryHomepageWith:dict success:succ failure:fail];
}

- (void)prepareDataInScrollView:(id)data{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            NSDictionary *compassDict = data[ @"data" ];
            Compass *com = [[Compass alloc]init];
            [com setValuesForKeysWithDictionary:compassDict];
            self.compass = com;
            [self setValueInScrollView];
        }else{
            [IBTLoadingView showTips:message];
        }
    }else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
}
- (void)setValueInScrollView{
    [svc setValueInSale:self.compass];
    [pvc setValueInPassenger:self.compass];
    [ppvc setValueInPassgerPrice:self.compass];
    [gvc setValueInGrossRate:self.compass];
}

//获取底部详情数据
- (void)getBottomData:(NSIndexPath *)indexPath{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        //赋值
        [IBTLoadingView hideHUDWithText:nil];

        [strongSelf downLoadData:data indexPath:indexPath];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
#warning mark - 测试数据
        self.storeCount = 33333;

        NSArray *arr = [self setOrgTestValue];

        if (indexPath) {
            arr = [self setTwoOrgTestValue];
        }else{
            [self.dataArr addObjectsFromArray:arr];
            //刷新tableView
            [self refreshAllTable];
        }
        [self.totalArr addObjectsFromArray:arr];
        if (indexPath) {
            [self actionTableView:indexPath];
        }
    };
    ICRUserUtil *userUtil = [ICRUserUtil sharedInstance];
    if (!self.orgScope) {
       self.orgScope = @"";
    }
    NSDictionary *dict = @{
                           @"userUuid":userUtil.userId,
                           @"dateScopeType":self.dayType,
                           @"dateScope":self.scopeType,
                           @"orgScopeType":@"all",
                           @"orgScope":self.orgScope
                           };
    [[ICRHTTPController sharedController] queryOrgdataWith:dict success:succ failure:fail];
}

- (void)downLoadData:(id)data indexPath:(NSIndexPath *)indexPath{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            NSArray *recodesArr = data[ @"data" ][ @"records" ];
            self.storeCount =[data[ @"data" ][ @"storeamount" ] integerValue];
            for (NSDictionary *orgDict in recodesArr) {
                OrgCompass *orgCompass = [[OrgCompass alloc]init];
                [orgCompass setValuesForKeysWithDictionary:orgDict];
                if ([self.orgScope isEqualToString:@""]) {
                    if (self.dataArr.count > 0) {
                        [self.dataArr removeAllObjects];
                    }
                    if (self.totalArr.count > 0) {
                        [self.totalArr removeAllObjects];
                    }
                    if (self.selectArr.count > 0) {
                        [self.selectArr removeAllObjects];
                    }
                    [self.dataArr addObject:orgCompass];
                    //刷新tableView
                    [self refreshAllTable];
                }
                [self.totalArr addObject:orgCompass];
                if (indexPath) {
                    [self actionTableView:indexPath];
                }
            }
            
        }else{
            [IBTLoadingView showTips:message];
        }
    }else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
}
#pragma mark - 刷新所有的tableView
- (void)refreshAllTable{
    svc.count = self.storeCount;
    pvc.count = self.storeCount;
    ppvc.count = self.storeCount;
    gvc.count = self.storeCount;
    svc.dataArr = self.dataArr;
    pvc.dataArr = self.dataArr;
    ppvc.dataArr = self.dataArr;
    gvc.dataArr = self.dataArr;
    [svc.tableView reloadData];
    [pvc.tableView reloadData];
    [ppvc.tableView reloadData];
    [gvc.tableView reloadData];
}

#pragma mark - 布局
- (void)bulidLayout{
    
    self.view.backgroundColor = [UIColor whiteColor];
    CGRect rect = CGRectMake(10, 10, ScreenSize.width - 10*2, 30);
    NSArray *arr = @[SaleDay,SaleWeek,SaleMonth];
    self.segView = [[CustomSegView alloc]initWithFrame:rect withArr:arr];
    self.segView.delegate = self;
    [self.view addSubview:self.segView];
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.segView.bottom, ScreenSize.width, ScreenSize.height - 49 - 64- self.segView.bottom)];
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator  = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    [self.view addSubview:self.scrollView];
    
    svc = [SaleViewController new];
    [self addChildViewController:svc];
    
    pvc = [PassengerViewController new];
    [self addChildViewController:pvc];
    
    ppvc = [PassgerPriceViewController new];
    [self addChildViewController:ppvc];
    
    gvc = [GrossRateViewController new];
    [self addChildViewController:gvc];
    
    rect = CGRectMake(0, 0, ScreenSize.width, self.scrollView.height);
    svc.view.frame = rect;
    [self.scrollView addSubview:svc.view];
    
    rect = CGRectMake(self.scrollView.width,0 , ScreenSize.width, self.scrollView.height);
    pvc.view.frame = rect;
    [self.scrollView addSubview:pvc.view];
    
    rect = CGRectMake(self.scrollView.width*2, 0, ScreenSize.width, self.scrollView.height);
    ppvc.view.frame = rect;
    [self.scrollView addSubview:ppvc.view];
    
    rect = CGRectMake(self.scrollView.width*3, 0, ScreenSize.width, self.scrollView.height);
    gvc.view.frame = rect;
    [self.scrollView addSubview:gvc.view];
    
    self.scrollView.contentSize = CGSizeMake(self.scrollView.width * 4, self.scrollView.height);
}

#pragma mark - segViewDelegate
- (void)customSegOneClick:(NSString *)title{
    //日周年切换
    NSString *dayType = @"";
    if ([title isEqualToString:SaleDay]) {
        dayType = @"day";
        self.scopeType = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM-dd"];
    }else if ([title isEqualToString:SaleWeek]) {
        dayType = @"week";
        self.scopeType = [IBTCommon getWeekFromDate];
    }else if ([title isEqualToString:SaleMonth]) {
        dayType = @"month";
        self.scopeType = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM"];
    }
    self.orgScope = @"";
    CLog(@"-------%@",self.scopeType);
    self.dayType = dayType;
    [self getDataFromServer];
}
- (void)customSegTwoClick:(NSString *)title{
    //选择历史查看
    if ([title isEqualToString:SaleDay]) {
        [self startDatePickView:SaleEnDay];
    }else if ([title isEqualToString:SaleWeek]) {
        [self startDatePickView:SaleEnWeek];
    }else if ([title isEqualToString:SaleMonth]) {
        [self startDatePickView:SaleEnMonth];
    }
}

- (void)startDatePickView:(NSString *)type{
    if (!self.startTimeView) {
        
        NSString *currentStr  = @"";
        if ([type isEqualToString:SaleEnDay]) {
            if (self.selectDay) {
                currentStr =  self.selectDay;
            }else{
                currentStr = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM-dd"];
            }
            
        }else if([type isEqualToString:SaleEnMonth]){
            if (self.selectMonth) {
                currentStr =  self.selectMonth;
            }else{
                currentStr = [IBTCommon stringFromDateWithFormat:[NSDate date] format:@"yyyy-MM"];
            }
        }else{
            if (self.selectWeek) {
                currentStr =  self.selectWeek;
            }else{
                currentStr = [IBTCommon getWeekFromDate];
            }
        }

        self.startTimeView = [[FinishTimeView alloc] initWithFrame:CGRectMake(0, ScreenSize.height, ScreenSize.width, ScreenSize.height - 64) withDate:currentStr type:type];
        self.startTimeView.delegate = self;
        self.startTimeView.backgroundColor        = RGBA(0, 0, 0 ,0.5);
        [AppWindow addSubview:self.startTimeView];
        
        [UIView animateWithDuration:0.15 animations:^{
            CGRect startFrame =  self.startTimeView.frame;
            startFrame.origin.y =  64;
            self.startTimeView.frame = startFrame;
        } completion:^(BOOL finished) {
            
        }];
    }
}
- (void)cancelTimeView{
    [self clearDatePickView];
}
- (void)okTimeView:(NSString *)time withType:(NSString *)type{
    CLog(@"--------%@",time);
    // 关闭选择器
    [self clearDatePickView];
    if ([type isEqualToString:SaleEnDay]) {
        self.selectDay = time;
    }else if ([type isEqualToString:SaleEnWeek]) {
        self.selectWeek = time;
    }else if ([type isEqualToString:SaleEnMonth]) {
        self.selectMonth = time;
    }
    
    self.scopeType = time;
    self.orgScope = @"";
    [self getDataFromServer];
}
#pragma mark - 取消
- (void)clearDatePickView{
    [UIView animateWithDuration:0.15 animations:^{
        CGRect startFrame =  self.startTimeView.frame;
        startFrame.origin.y = ScreenSize.height;
        self.startTimeView.frame = startFrame;
    } completion:^(BOOL finished) {
        [self.startTimeView removeFromSuperview];
        self.startTimeView = nil;
    }];
}
- (void)getNextDetailData:(NSNotification *)fication{
    NSDictionary *dict = fication.userInfo;
    NSIndexPath *indexPath = dict[@"indexPath"];
        OrgCompass *parentCompass = [self.dataArr objectAtIndex:indexPath.row];
        //如果当前点击的不是删除，则要先获取数据在进行插入
        if (![self isHaveIndexPath:indexPath]) {
            self.orgScope = parentCompass.orguuid;
            if (parentCompass.isleaf) {
                //如果是子节点就不用进行网络请求
                return;
            }//不是子节点进行网络请求
            if ([parentCompass.parentuuid isEqualToString:@"1"]) {
                NSArray *arr =  [self setThreeOrgTestValue];
                [self.totalArr addObjectsFromArray:arr];
                if (indexPath) {
                    [self actionTableView:indexPath];
                }
            }else{
                [self getBottomData:indexPath];

            }
            return;
        }
    [self actionTableView:indexPath];
}
- (void)actionTableView:(NSIndexPath *)indexPath{
    OrgCompass *parentCompass = [self.dataArr objectAtIndex:indexPath.row];
    NSInteger startPosition = indexPath.row+1;
    NSInteger endPosition = startPosition;
    BOOL expand = NO;
    for (int i=0; i<self.totalArr.count; i++) {
        OrgCompass *node = [self.totalArr objectAtIndex:i];
        if ([node.parentuuid isEqualToString:parentCompass.orguuid]) {
            //修改二级节点的属性为为原属性相反属性
            node.expand = !node.expand;
            if (node.expand) {
                [self.dataArr insertObject:node atIndex:endPosition];
                expand = YES;
                endPosition++;
            }else{
                expand = NO;
                endPosition = [self removeAllNodesAtParentNode:parentCompass];
                break;
            }
        }
    }
    
    //获得需要修正的indexPath
    NSMutableArray *indexPathArray = [NSMutableArray array];
    for (NSInteger i=startPosition; i<endPosition; i++) {
        NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [indexPathArray addObject:tempIndexPath];
    }
    
    //插入或者删除相关节点
    if (expand) {
        [self.selectArr addObject:indexPath];
        [self insertDataWithTable:svc.tableView arr:indexPathArray];
        [self insertDataWithTable:ppvc.tableView arr:indexPathArray];
        [self insertDataWithTable:pvc.tableView arr:indexPathArray];
        [self insertDataWithTable:gvc.tableView arr:indexPathArray];
    }else{
        [self.selectArr removeObject:indexPath];
        [self deleteDataWithTable:svc.tableView arr:indexPathArray];
        [self deleteDataWithTable:pvc.tableView arr:indexPathArray];
        [self deleteDataWithTable:ppvc.tableView arr:indexPathArray];
        [self deleteDataWithTable:gvc.tableView arr:indexPathArray];
    }
    [self refreshAllTable];

}

- (void)insertDataWithTable:(UITableView *)tableView arr:(NSMutableArray *)arr{
    [tableView insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
}
- (void)deleteDataWithTable:(UITableView *)tableView arr:(NSMutableArray *)arr{
    [tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
}
/**
 *  删除该父节点下的所有子节点（包括孙子节点）
 *
 *  @param parentNode 父节点
 *
 *  @return 该父节点下一个相邻的统一级别的节点的位置
 */
-(NSUInteger)removeAllNodesAtParentNode : (OrgCompass *)parentNode{
    NSUInteger startPosition = [self.dataArr indexOfObject:parentNode];
    NSUInteger endPosition = startPosition;
        for (NSUInteger i=startPosition+1; i<self.dataArr.count; i++) {
            OrgCompass *node = [self.dataArr objectAtIndex:i];
            endPosition++;
            if (node.level <= parentNode.level) {
                break;
            }
            if(endPosition == self.dataArr.count-1){
                endPosition++;
                node.expand = NO;
                break;
            }
            node.expand = NO;
        }
        if (endPosition>startPosition) {
            for (NSInteger i = startPosition+1; i < endPosition; i++) {
                OrgCompass *parentCompass = self.dataArr[i];
                for (OrgCompass *orgCompass in self.totalArr) {
                    if (parentCompass.orguuid == orgCompass.orguuid) {
                        [self.totalArr removeObject:orgCompass];
                        break;
                    }
                }
            }
            [self.dataArr removeObjectsInRange:NSMakeRange(startPosition+1, endPosition-startPosition-1)];
        }
    return endPosition;
}

- (BOOL)isHaveIndexPath:(NSIndexPath *)indexPath{
    for (NSIndexPath *path in self.selectArr) {
        if (path.row == indexPath.row) {
            return YES;
        }
    }
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
