//
//  ReportDetailViewController.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/11/11.
//  Copyright © 2015年 Xummer. All rights reserved.
//

#import "ReportDetailViewController.h"
#import "CustomSegView.h"
#import "RSaleView.h"
#import "RPassgerView.h"
#import "FinishTimeView.h"
#import "QueryOrder.h"


@interface ReportDetailViewController ()<CustomSegViewDelegate,FinishTimeViewDelegate,UIWebViewDelegate>
@property (nonatomic,strong)CustomSegView *segView;


@property (nonatomic,strong)RSaleView *rsaleView;
@property (nonatomic,strong)UIWebView *rwebView;
@property (nonatomic,strong)UIActivityIndicatorView *ractivityView;


@property (nonatomic,strong)RPassgerView *rpassgerView;
@property (nonatomic,strong)UIWebView *rpassgerWebView;
@property (nonatomic,strong)UIActivityIndicatorView *passActivityView;


@property (nonatomic,strong)RPassgerView *rpriceView;
@property (nonatomic,strong)UIWebView *rpriceWebView;
@property (nonatomic,strong)UIActivityIndicatorView *priceActivityView;


@property (nonatomic,strong)RPassgerView *rgrossView;
@property (nonatomic,strong)UIWebView *rgrossWebView;
@property (nonatomic,strong)UIActivityIndicatorView *grossActivityView;



@property (nonatomic,strong)FinishTimeView *startTimeView;
@property (nonatomic,strong)NSString *dayType;
@property (nonatomic,strong)NSString *scopeType;
@property (nonatomic,strong)NSString *selectDay;
@property (nonatomic,strong)NSString *selectMonth;
@property (nonatomic,strong)NSString *selectWeek;

@property (nonatomic,strong)UIScrollView *scrollView;

@end

@implementation ReportDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数据
    self.dayType = @"day";
    self.scopeType = @"";
    self.title = self.compass.orgName;
    [self bulidLayout];
    [self getDataFromServer];
}

#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 - 64 - self.segView.bottom)];
    self.scrollView.showsHorizontalScrollIndicator  = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    [self.view addSubview:self.scrollView];
    
    
  
    
    //销售
    rect = CGRectMake(0, 0, ScreenSize.width, 145);
    self.rsaleView = [[RSaleView alloc]initWithFrame:rect];
    self.rsaleView.bgImage.image = [UIImage imageNamed:@"salebg_1"];
    self.rsaleView.cenImage.image = [UIImage imageNamed:@"sale_1"];
    [self.scrollView addSubview:self.rsaleView];
    
    
    rect = CGRectMake(0, self.rsaleView.bottom, ScreenSize.width,  self.scrollView.height - self.rsaleView.bottom - 64);
    CLog(@"-------%f",self.scrollView.height);
    UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,self.rsaleView.bottom, ScreenSize.width, self.scrollView.height-self.rsaleView.bottom)];
    webView.delegate = self;
    webView.scalesPageToFit = YES;
    webView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:webView];
    self.rwebView = webView;

    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((ScreenSize.width-80)/2, (webView.height-80)/2, 80, 80)];
    indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [webView addSubview:indicatorView];
    self.ractivityView = indicatorView;
    for (int i = 1; i< 4 ; i++) {
        RPassgerView *prassView = [[RPassgerView alloc]initWithFrame:CGRectMake(i*ScreenSize.width, 0, ScreenSize.width, 145) withPage:i];
        prassView.bgImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"salebg_%d",(i+1)]];
        prassView.cenImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"sale_%d",(i+1)]];
        
        UIWebView *web = [[UIWebView alloc]initWithFrame:CGRectMake(i*ScreenSize.width, prassView.bottom, ScreenSize.width,  self.scrollView.height-prassView.bottom)];
        web.scalesPageToFit = YES;
        web.delegate = self;
        web.backgroundColor = [UIColor clearColor];
       
        [self.scrollView addSubview:prassView];
        [self.scrollView addSubview:web];
        
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((ScreenSize.width-80)/2, (web.height-80)/2, 80, 80)];
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [web addSubview:indicator];
        
        if (i == 1) {
            self.rpassgerView = prassView;
            self.rpassgerWebView = web;
            self.passActivityView = indicator;
        }else if (i == 2) {
            self.rpriceView = prassView;
            self.rpriceWebView = web;
            self.priceActivityView = indicator;
        }else if (i == 3) {
            self.rgrossView = prassView;
            self.rgrossWebView = web;
            self.grossActivityView = indicator;
        }
    }

    self.scrollView.contentSize = CGSizeMake(ScreenSize.width*4, ScreenSize.height - 64 - self.segView.bottom);
    
    //加载webView
    [self loadWebViewFromServer];
   
}
#pragma mark- 请求webView
- (void)loadWebViewFromServer{
#warning 测试
    NSString *passgerUrl = [NSString stringWithFormat:@"%@/%@?enterprise=%@&dateScopeType=%@&dateScope=%@&orgUuid=%@",HTTP_REST_API_BASE_URL,PassengerWebUrl,[ICRUserUtil sharedInstance].orgId,self.dayType,self.scopeType,self.compass.orgUuid];
    [self.rpassgerWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:passgerUrl]]];
    
    NSString *priceUrl = [NSString stringWithFormat:@"%@/%@?enterprise=%@&dateScopeType=%@&dateScope=%@&orgUuid=%@",HTTP_REST_API_BASE_URL,PriceWebUrl,[ICRUserUtil sharedInstance].orgId,self.dayType,self.scopeType,self.compass.orgUuid];
    [self.rpriceWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:priceUrl]]];
    
    NSString *grossUrl = [NSString stringWithFormat:@"%@/%@?enterprise=%@&dateScopeType=%@&dateScope=%@&orgUuid=%@",HTTP_REST_API_BASE_URL,GrossWebUrl,[ICRUserUtil sharedInstance].orgId,self.dayType,self.scopeType,self.compass.orgUuid];
    [self.rgrossWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:grossUrl]]];
    
    NSString *saleUrl = [NSString stringWithFormat:@"%@/%@?enterprise=%@&dateScopeType=%@&dateScope=%@&orgUuid=%@",HTTP_REST_API_BASE_URL,SaleWebUrl,[ICRUserUtil sharedInstance].orgId,self.dayType,self.scopeType,self.compass.orgUuid];
    [self.rwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:saleUrl]]];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if (webView == self.rwebView) {
        [self.ractivityView startAnimating];
        
    }else if (webView == self.rpassgerWebView) {
        [self.passActivityView startAnimating];
        
    }else if (webView == self.rpriceWebView) {
        [self.priceActivityView startAnimating];
        
    }else if (webView == self.rgrossWebView) {
        [self.grossActivityView startAnimating];
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView { //webview 自适应高度
    if (webView == self.rwebView) {
        [self.ractivityView stopAnimating];
        
    }else if (webView == self.rpassgerWebView) {
        [self.passActivityView stopAnimating];
        
    }else if (webView == self.rpriceWebView) {
        [self.priceActivityView stopAnimating];
        
    }else if (webView == self.rgrossWebView) {
        [self.grossActivityView stopAnimating];
    }
}


- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        //赋值
        [IBTLoadingView hideHUDWithText:nil];
        [strongSelf prepareData:data];
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
        
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    NSMutableArray *orderArr =[NSMutableArray array];
    if (orderArr.count == 0) {
        QueryOrder *order = [QueryOrder new];
        order.field = @"orgCode";
        order.direction = @"desc";
        [orderArr addObject:[order dictForCommit]];
    }
    NSDictionary *dict = @{
                           @"dataScopeType":self.dayType,
                           @"dataScope":self.scopeType,
                           @"orgUuid":self.compass.orgUuid,
                           @"fetchScope":@"childs",
                           @"queryOrders":orderArr,
                           @"pageNumber":@0,
                           @"pageSize":@100
                           };
    [[ICRHTTPController sharedController] queryHomepageWith:dict success:succ failure:fail];
}

#pragma mark- 成功之后的操作
- (void)prepareData:(id)data{
    if (data) {
        NSInteger success = [data[@"success"] integerValue];
        NSString *message  = data[@"message"] ;
        if (success == 1) {
            NSDictionary *compassDict = data[ @"data" ][@"salesData"];
            NSArray *arr = compassDict[@"records"];
            if (arr.count > 0) {
                for (NSDictionary *comDict in arr) {
                    Compass *com = [[Compass alloc]init];
                    [com setValuesForKeysWithDictionary:comDict];
                    self.compass = com;
                }
            }
            [self.rsaleView setValueInSaleView:self.compass];
            [self.rpassgerView setPassengerWithCompass:self.compass];
            [self.rpriceView setPersalesWithCompass:self.compass];
            [self.rgrossView setGrossprofitWithCompass:self.compass];
            self.rsaleView.weekLabelStr = self.dayType;
            self.rpassgerView.weekLabelStr = self.dayType;
            self.rpriceView.weekLabelStr = self.dayType;
            self.rsaleView.weekLabelStr = self.dayType;
        }else{
            [IBTLoadingView showTips:message];
        }
    }else{
        [IBTLoadingView showTips:@"      无记录      "];
    }
}
#pragma mark -CustomSegViewDelegate
- (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"];
    }
    CLog(@"-------%@",self.scopeType);
    self.dayType = dayType;
    [self getDataFromServer];
    //加载webView
    [self loadWebViewFromServer];

}
- (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 getDataFromServer];
    //加载webView
    [self loadWebViewFromServer];

}
#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)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.startTimeView) {
        [self.startTimeView removeFromSuperview];
        self.startTimeView = nil;
    }
}


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

/*
#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.
}
*/

@end
