//
//  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"
#import "QueryModel.h"

@interface SeePriceViewController ()<UITableViewDelegate,UITableViewDataSource>

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

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

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

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

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

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

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

/**
 *  查询油价
 */
@property (nonatomic,strong) QueryModel *queryModel;



@end

@implementation SeePriceViewController

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

- (NSMutableArray *)administrativeArray
{
    if (!_administrativeArray) {
        _administrativeArray = [NSMutableArray array];
        for (NSDictionary *dict in [ICRUserUtil sharedInstance].storeArray) {
            if (![_administrativeArray containsObject:dict[@"area"]]) {
                [_administrativeArray addObject:dict[@"area"]];
            }
        }
    }
    return _administrativeArray;
}

- (NSMutableArray *)distributionArray
{
    if (!_distributionArray) {
        _distributionArray = [NSMutableArray array];
        for (NSDictionary *dict in [ICRUserUtil sharedInstance].storeArray) {
            if (![_distributionArray containsObject:dict[@"deliveryArea"]]) {
                [_distributionArray addObject:dict[@"deliveryArea"]];
            }
        }
    }
    return _distributionArray;
}


- (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];
//    self.seePriceTableview.userInteractionEnabled = [ICRUserUtil sharedInstance].storeArray.count;
}

#pragma mark -获取配送区域数据、获取行政区域数据
- (void)netWorkRequest
{
    if (![[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
        [IBTLoadingView showProgressLabel:@"正在加载..."];
        [self.distributionArray removeAllObjects];
        [self.administrativeArray removeAllObjects];
        WS(weakSelf);
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_enter(group);
        //任务1->获取配送区域
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,DISTRIBUTION] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            dispatch_group_leave(group);
            if ([returnValue[@"success"] isEqualToNumber:@1]) {
                weakSelf.distributionArray = returnValue[@"data"];
            }
        } withFailed:^(NSError *failed) {
            dispatch_group_leave(group);
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
        //任务2->获取行政区域
        dispatch_group_enter(group);
        [HttpRequestManager requestNetworkwithURL:[NSString stringWithFormat:@"%@%@",HTTP_REST_API_BASE_URL,ADMINISTRATIVE] withRequestType:ONE withParameter:nil withSuccess:^(id returnValue) {
            dispatch_group_leave(group);
            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_group_leave(group);
            [IBTLoadingView showTextOnly:failed.localizedDescription];
        }];
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            [IBTLoadingView hideHUDWithText:nil];
            [weakSelf.seePriceTableview reloadData];
        });
    };
    //行政区域和配送区域都为一个时，加载数据
    if (self.administrativeArray.count == 1 && self.distributionArray.count == 1) {
        
        Condition *condition2 = [[Condition alloc] init];
        condition2.operation = @"deliveryAreaUuidEquals";
        condition2.parameters = @[self.distributionArray[0][@"uuid"]];
        Condition *condition3 = [[Condition alloc] init];
        condition3.operation = @"areaUuidEquals";
        condition3.parameters = @[self.administrativeArray[0][@"uuid"]];
        if ([[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            Condition *condition1 = [[Condition alloc] init];
            condition1.operation = @"userId";
            condition1.parameters = @[[ICRUserUtil sharedInstance].f_user_uuid];
            self.queryModel.conditions = (NSArray<Condition> *)@[condition2,condition3,condition1];
        }else {
            self.queryModel.conditions = (NSArray<Condition> *)@[condition2,condition3];
        }
        [self getOilPriceDatas:[self.queryModel toDictionary]];
    }
}

#pragma mark -获取油价数据
- (void)getOilPriceDatas:(NSDictionary *)dict
{
     WS(weakSelf);
    NSLog(@"%@",[dict JSONString]);
    [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
{
    ICRUserUtil *user = [ICRUserUtil sharedInstance];
    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 = [user.storeArray firstObject][@"name"];
        cell.storeImageView.hidden = user.storeArray.count > 1;
        cell.storeName.hidden = user.storeArray.count > 1;
        cell.datasResult = self.oilPriceObjec;
        return cell;
    }else {
       SeePriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeePriceTableViewCell" forIndexPath:indexPath];
        cell.arrowImageView.hidden = NO;
        cell.backgroundColor = [UIColor whiteColor];
        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];
        }
        //区分是否是油站经理调用
        if (self.distributionArray.count == 1 && [[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            if (indexPath.row == 0) {
                cell.distributionAreaContent.text = self.distributionArray[0][@"name"];
                self.distributionArea = self.distributionArray[0];
            }
        }
        if (self.administrativeArray.count == 1 && [[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            if (indexPath.row == 1) {
                cell.distributionAreaContent.text = [NSString stringWithFormat:@"[%@]%@",self.administrativeArray[0][@"uuid"],self.administrativeArray[0][@"name"]];
                self.administrativeArea = self.administrativeArray[0];
            }
        }
        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) {
        if (![ICRUserUtil sharedInstance].storeArray.count) {
            [IBTLoadingView showTextOnly:@"当前人员无所属油站，无法选择配送区域"];return;
        }
        if ([ICRUserUtil sharedInstance].storeArray.count == 1) {
            return;
        }
        PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
        selectArea.title = @"选择配送区域";
        selectArea.currentTitle = [cell.distributionAreaContent.text isEqualToString:@"请选择"]?nil:cell.distributionAreaContent.text;
        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;
        }];
        IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:selectArea];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf presentViewController:nav animated:YES completion:nil];
        });
    }
    if (indexPath.row == 1) {
        
        if (![ICRUserUtil sharedInstance].storeArray.count) {
            [IBTLoadingView showTextOnly:@"当前人员无所属油站，无法选择行政区域"];return;
        }
        if ([ICRUserUtil sharedInstance].storeArray.count == 1) {
            return;
        }
        if ([[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            
            PromptTableViewController *selectArea = [[PromptTableViewController alloc]init];
            selectArea.title = @"选择行政区域";
            selectArea.currentTitle = [cell.distributionAreaContent.text isEqualToString:@"请选择"]?nil:cell.distributionAreaContent.text;
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *dict in self.administrativeArray) {
                [tempArray addObject:dict[@"name"]];
            }
            selectArea.datasArray = tempArray;
            [selectArea setSelectCellTitle:^(NSString *title,NSInteger cellindex) {
                cell.distributionAreaContent.text = title?title:@"请选择";
                weakSelf.administrativeArea = [weakSelf.administrativeArray objectAtIndex:cellindex];
                [weakSelf getQueryDictionary]?[IBTLoadingView showProgressLabel:@"查询中..."]:nil;
                [weakSelf getQueryDictionary]?[weakSelf getOilPriceDatas:[weakSelf getQueryDictionary]]:nil;
            }];
            IBTUINavigationController *nav = [[IBTUINavigationController alloc]initWithRootViewController:selectArea];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf presentViewController:nav animated:YES completion:nil];
            });
            
        }else {
            
            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) {
       
        Condition *condition2 = [[Condition alloc] init];
        condition2.operation = @"deliveryAreaUuidEquals";
        condition2.parameters = @[self.distributionArea[@"uuid"]];
        Condition *condition3 = [[Condition alloc] init];
        condition3.operation = @"areaUuidEquals";
        condition3.parameters = @[self.administrativeArea[@"uuid"]];
        if ([[ICRUserUtil sharedInstance].position isEqualToString:@"storer"]) {
            Condition *condition1 = [[Condition alloc] init];
            condition1.operation = @"userId";
            condition1.parameters = @[[ICRUserUtil sharedInstance].f_user_uuid];
            self.queryModel.conditions = (NSArray<Condition> *)@[condition2,condition3,condition1];
        }else {
            self.queryModel.conditions =  (NSArray<Condition> *)@[condition2,condition3];
        }
        return [self.queryModel toDictionary];
    }
    return nil;
}

#pragma mark -lazy
- (QueryModel *)queryModel
{
    if (!_queryModel) {
        _queryModel = [[QueryModel alloc] init];
        _queryModel.pageSize = 999;
        _queryModel.pageNumber = 0;
        
    }
    return _queryModel;
}









@end
