//
//  SeePriceViewController.m
//  total
//
//  Created by 曹云霄 on 16/6/21.
//  Copyright © 2016年 free. All rights reserved.
//

#import "SeePriceViewController.h"
#import "SeePriceTableViewCell.h"
#import "SeePriceCollectionReusableView.h"
#import "SeePriceDetailsTableViewCell.h"
#import "CustomSelectCityViewController.h"
#import "WYPopoverController.h"
#import "PromptTableViewController.h"

@interface SeePriceViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 *  titleName
 */
@property (nonatomic,strong) NSArray *titleArray;

/**
 *  行政区域数据源
 */
@property (nonatomic,strong) NSArray *administrativeArray;

/**
 *  弹出框
 */
@property (nonatomic,strong)  WYPopoverController *settingsPopoverController;

/**
 *  油价数据源
 */
@property (nonatomic,strong) QueryResult *oilPriceObjec;

/**
 *  配送区域数据源
 */
@property (nonatomic,strong) NSArray *distributionArray;

/**
 *  记录选择配送区
 */
@property (nonatomic,strong) NSDictionary *distributionArea;

/**
 *  记录选择行政区
 */
@property (nonatomic,strong) NSDictionary *administrativeArea;

/**
 *  油站列表信息
 */
@property (nonatomic,strong) NSArray *oilListDatas;


@end

@implementation SeePriceViewController


- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = [NSArray arrayWithObjects:@"配送区域:",@"行政区域:",@"当前时间:",nil];
    }
    return _titleArray;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self uiConfigAction];
    [self netWorkRequest];
}

#pragma mark -UI
- (void)uiConfigAction
{
    self.title = @"查看油品价格";
    self.view.backgroundColor = [UIColor whiteColor];
    self.seePriceTableview.delegate = self;
    self.seePriceTableview.dataSource = self;
    self.seePriceTableview.tableFooterView = [UIView new];
}

#pragma mark -获取配送区域数据、获取行政区域数据
- (void)netWorkRequest
{
    WS(weakSelf);
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    dispatch_queue_t aQueue = dispatch_queue_create("顺序执行", DISPATCH_QUEUE_SERIAL);
    //创建1个queue group
    dispatch_group_t queueGroup = dispatch_group_create();
    //任务1->获取配送区域
    dispatch_group_async(queueGroup, aQueue, ^{
        dispatch_suspend(aQueue);
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,DISTRIBUTION] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                weakSelf.distributionArray = returnValue[@"data"];
            }
            dispatch_resume(aQueue);
        } withFailed:^(NSError *failed) {
            dispatch_resume(aQueue);
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
    //任务2->获取行政区域
    dispatch_group_async(queueGroup, aQueue, ^{
        dispatch_suspend(aQueue);
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,ADMINISTRATIVE] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            dispatch_resume(aQueue);
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                NSArray *array = returnValue[@"data"];
                NSMutableArray *tempArray = [NSMutableArray array];
                for (NSDictionary *dict in array) {
                    [tempArray addObject:dict[@"childrenUnits"]];
                }
                weakSelf.administrativeArray = tempArray;
            }
        } withFailed:^(NSError *failed) {
            dispatch_resume(aQueue);
           [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
    //任务3->获取油站列表
    dispatch_group_async(queueGroup, aQueue, ^{
        dispatch_suspend(aQueue);
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@/mdata/store/getsByUser/%@",HTTP_REST_API_BASE_URL,[ICRUserUtil sharedInstance].f_user_uuid] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            dispatch_resume(aQueue);
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                weakSelf.oilListDatas = returnValue[@"data"];
                [weakSelf.seePriceTableview reloadData];
            }
        } withFailed:^(NSError *failed) {
            dispatch_resume(aQueue);
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
    });
    //任务4->获取油价列表/默认加载全部
    dispatch_group_async(queueGroup, aQueue, ^{
        NSDictionary *queryDictionary = nil;
        if ([[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            queryDictionary =   @{@"pageSize" : @0,
                                  @"orders" : @[@{@"field" : @"string",
                                                  @"direction" : @"asc"}],
                                  @"conditions" : @[
                                          @{@"operation":@"userId",
                                            @"parameters":@[[ICRUserUtil sharedInstance].f_user_uuid]
                                            }
                                          ],
                                  @"pageNumber" : @0};
        }else
        {
            queryDictionary =   @{@"pageSize" : @0,
                                  @"orders" : @[@{@"field" : @"string",
                                                  @"direction" : @"asc"}],
                                  @"conditions" : @[
                                          @{@"operation":[NSNull null],
                                            @"parameters":[NSNull null]
                                            }
                                          ],
                                  @"pageNumber" : @0};
        }
      [self getOilPriceDatas:queryDictionary];
    });
}

#pragma mark -获取油价数据
- (void)getOilPriceDatas:(NSDictionary *)dict
{
     WS(weakSelf);
    [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,OILPRICE] withRequestType:ZERO withParameter:dict withSuccess:^(id returnValue) {
        
        [IBTLoadingView hideHUDWithText:nil];
        if ([returnValue[@"success"] isEqualToNumber:@1]) {
            QueryResult *oilPrice = [[QueryResult alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.oilPriceObjec = oilPrice;
            [weakSelf.seePriceTableview reloadData];
        }else {
            [IBTLoadingView showTextOnly:returnValue[@"message"]];
        }
    } withFailed:^(NSError *failed) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:failed.localizedDescription];
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3) {
        SeePriceDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeePriceDetailsTableViewCell" forIndexPath:indexPath];
        cell.separatorInset = UIEdgeInsetsMake(0, ScreenSize.width, 0, 0);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.storeName.text = [self.oilListDatas firstObject][@"name"];
        cell.storeImageView.hidden = self.oilListDatas.count > 1;
        cell.storeName.hidden = self.oilListDatas.count > 1;
        cell.datasResult = self.oilPriceObjec;
        return cell;
    }else {
       SeePriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeePriceTableViewCell" forIndexPath:indexPath];
        cell.arrowImageView.hidden = NO;
        cell.distributionAreaContent.font = [UIFont systemFontOfSize:15];
        cell.distributionAreaLabe.text = [self.titleArray objectAtIndex:indexPath.row];
        if (indexPath.row != 0) {
            cell.separatorInset = UIEdgeInsetsMake(0, ScreenSize.width, 0, 0);
        }
        if (indexPath.row == 2) {
            cell.arrowImageView.hidden = YES;
            cell.backgroundColor = RGBA(251, 244, 228, 1);
            cell.distributionAreaContent.text = [GTOCommonTools GetCurrenttime];
            cell.distributionAreaContent.font = [UIFont systemFontOfSize:17];
        }else
        {
            cell.backgroundColor = [UIColor whiteColor];
        }
        //区分是否是油站经理调用
        if (self.oilListDatas.count == 1 && [[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            if (indexPath.row == 0) {
                cell.distributionAreaContent.text = self.oilListDatas[0][@"deliveryArea"][@"name"];
            }
            if (indexPath.row == 1) {
                cell.distributionAreaContent.text = [NSString stringWithFormat:@"[%@]%@",self.oilListDatas[0][@"area"][@"uuid"],self.oilListDatas[0][@"area"][@"name"]];
            }
            cell.userInteractionEnabled = NO;
        }
        return cell;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3) {
        return 300;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeePriceTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    WS(weakSelf);
    if (indexPath.row == 0) {
        PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
        selectArea.title = @"选择配送区域";
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dict in self.distributionArray) {
            [tempArray addObject:dict[@"name"]];
        }
        selectArea.datasArray = tempArray;
        //选择配送区后回调
        [selectArea setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
            cell.distributionAreaContent.text = title?title:@"请选择";
            weakSelf.distributionArea = [weakSelf.distributionArray objectAtIndex:cellindex];
            [weakSelf getQueryDictionary]?[IBTLoadingView showProgressLabel:@"查询中..."]:nil;
            [weakSelf getQueryDictionary]?[weakSelf getOilPriceDatas:[weakSelf getQueryDictionary]]:nil;
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }];
        IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:selectArea];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf presentViewController:nav animated:YES completion:nil];
        });
    }
    if (indexPath.row == 1) {
        
        CustomSelectCityViewController *selectCity = [[CustomSelectCityViewController alloc]init];
        //选择行政区域后回调
        [selectCity setCompleteSelectCityBlock:^(NSArray *array) {
            weakSelf.administrativeArea = [array lastObject];
            cell.distributionAreaContent.text = [NSString stringWithFormat:@"[%@]%@[%@]%@",[array[0] objectForKey:@"uuid"],[array[0] objectForKey:@"name"],[array[1] objectForKey:@"code"],[array[1] objectForKey:@"name"]];
            [weakSelf getQueryDictionary]?[IBTLoadingView showProgressLabel:@"查询中..."]:nil;
            [weakSelf getQueryDictionary]?[weakSelf getOilPriceDatas:[weakSelf getQueryDictionary]]:nil;
        }];
        selectCity.preferredContentSize = CGSizeMake(ScreenSize.width, 200);
        selectCity.datasArray = self.administrativeArray;
        self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:selectCity];
        self.settingsPopoverController.popoverLayoutMargins = UIEdgeInsetsMake(10, 20, 10, 20);
        self.settingsPopoverController.wantsDefaultContentAppearance = NO;
        [self.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                               options:WYPopoverAnimationOptionFadeWithScale];
    }
}

#pragma mark -获取queryDictionary
- (NSDictionary *)getQueryDictionary
{
    if (self.distributionArea && self.administrativeArea) {
        NSDictionary *queryDictionary = @{@"pageSize" : @999,
                                          @"orders" : @[@{@"field" : @"uuid",
                                                          @"direction" : @"asc"}],
                                          @"conditions" : @[
                                                  @{@"operation" : @"deliveryAreaUuidEquals",
                                                    @"parameters" : @[self.distributionArea[@"uuid"]]},
                                                  @{@"operation" : @"areaUuidEquals",
                                                    @"parameters" : @[self.administrativeArea[@"uuid"]]},
                                                  @{@"operation" : @"categoryEquals",
                                                    @"parameters" : @[@"salePrice"]},
                                                  
                                                  ],
                                          @"pageNumber" : @0};
        return queryDictionary;
    }
    return nil;
}









@end
