//
//  TaskPointViewController.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-4.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "BATaskPointDetailViewController.h"
#import "TaskCheckViewController.h"
#import "CMPopTipView.h"
#import "BATaskDetailViewController.h"
#import "ListPartView.h"

@interface BATaskPointDetailViewController ()< CMPopTipViewDelegate ,UIGestureRecognizerDelegate>
{
    CMPopTipView *popTipView;
    UIButton* btnSheng;
    UIButton* btnShi;
    UIButton* btnArea;
    NSString* selectType;
}
@property (nonatomic, strong) UIView *descView;

@property (nonatomic, strong) NSString *provinceId;
@property (nonatomic, strong) NSString *cityId;
@property (nonatomic, strong) NSString *QuyuId;

@property (nonatomic, strong) NSMutableArray *areaArrContents;
@property (nonatomic, strong) NSMutableArray *shenArrContents;
@property (nonatomic, strong) NSMutableArray *shiArrContents;

@property(nonatomic,strong) ListPartView* view1;

@end

@interface BATaskPointCell : UITableViewCell

@property (nonatomic, strong) UILabel *lblPoint;
@property (nonatomic, strong) UILabel *lblQy;
@property (nonatomic, strong) UILabel *lblCanSelecte;
@property (nonatomic, strong) UILabel *lblStatus;
@property (nonatomic, strong) UIImageView *imageVArrow;
@property (nonatomic, strong) UIImageView *imageVUser;

@end

@implementation BATaskPointDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *areaName = nil;
    switch ([self.areaId intValue]) {
        case 1: areaName = @"外广场"; break;
        case 2: areaName = @"商场大堂"; break;
        case 3: areaName = @"中庭"; break;
        case 4: areaName = @"过道"; break;
        case 5: areaName = @"其他"; break;
        default:
            break;
    }
    self.navigationItem.title = @"商场执行任务情况";
    
    _provinceId = @"";
    _cityId = @"";
    _QuyuId = @"";
    
    _descView = [[UIView alloc] init];
    _descView.backgroundColor = RGBColor(0, 99, 159, 1);
    [self.view addSubview:_descView];
    [_descView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeBottom];
    [_descView autoSetDimension:ALDimensionHeight toSize:35];
    
    UILabel* lblArea = [[UILabel alloc] init];
    lblArea.textColor = [UIColor whiteColor];
    lblArea.text = @"区域:";
    lblArea.font = [UIFont systemFontOfSize:12];
    [_descView addSubview:lblArea];
    [lblArea autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:8];
    [lblArea autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:8];
    
    btnShi = [[UIButton alloc] init];
    btnShi.tag = 100;
    [btnShi addTarget:self action:@selector(btnPlaceClick:) forControlEvents:UIControlEventTouchUpInside];
    [btnShi setTitle:@"全部" forState:UIControlStateNormal];
    btnShi.titleLabel.font = [UIFont systemFontOfSize:12];
    btnShi.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnShi.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [btnShi setBackgroundImage:[UIImage imageNamed:@"NavBar/bigAreaNav_bg.png"] forState:UIControlStateNormal];
    [_descView addSubview:btnShi];
    [btnShi autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:3];
    [btnShi autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:3];
    [btnShi autoSetDimensionsToSize:CGSizeMake(70, 25)];
    
    UIImageView* downImage = [[UIImageView alloc] init];
    downImage.image = [UIImage imageNamed:@"Task_Point/arrow_down_white.png"];
    [btnShi addSubview:downImage];
    [downImage autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:4];
    [downImage autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [downImage autoSetDimensionsToSize:CGSizeMake(10, 6)];
    
    UILabel* lblShi = [[UILabel alloc] init];
    lblShi.textAlignment = NSTextAlignmentCenter;
    lblShi.textColor = [UIColor whiteColor];
    lblShi.text = @"市:";
    lblShi.font = [UIFont systemFontOfSize:12];
    [_descView addSubview:lblShi];
    [lblShi autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:btnShi withOffset:-5];
    [lblShi autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [lblShi autoSetDimension:ALDimensionWidth toSize:20];
    
    btnSheng = [[UIButton alloc] init];
    btnSheng.tag = 99;
    [btnSheng addTarget:self action:@selector(btnPlaceClick:) forControlEvents:UIControlEventTouchUpInside];
    [btnSheng setTitle:@"全部" forState:UIControlStateNormal];
    btnSheng.titleLabel.font = [UIFont systemFontOfSize:12];
    btnSheng.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnSheng.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [btnSheng setBackgroundImage:[UIImage imageNamed:@"NavBar/bigAreaNav_bg.png"] forState:UIControlStateNormal];
    [_descView addSubview:btnSheng];
    [btnSheng autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:lblShi withOffset:-5];
    [btnSheng autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [btnSheng autoSetDimensionsToSize:CGSizeMake(70, 25)];
    
    UIImageView* downImage1 = [[UIImageView alloc] init];
    downImage1.image = [UIImage imageNamed:@"Task_Point/arrow_down_white.png"];
    [btnSheng addSubview:downImage1];
    [downImage1 autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:4];
    [downImage1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [downImage1 autoSetDimensionsToSize:CGSizeMake(10, 6)];
    
    UILabel* lblSheng = [[UILabel alloc] init];
    lblSheng.textColor = [UIColor whiteColor];
    lblSheng.text = @"省:";
    lblSheng.font = [UIFont systemFontOfSize:12];
    lblSheng.textAlignment = NSTextAlignmentCenter;
    [_descView addSubview:lblSheng];
    [lblSheng autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:btnSheng withOffset:-5];
    [lblSheng autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [lblSheng autoSetDimension:ALDimensionWidth toSize:20];
    
    btnArea = [[UIButton alloc] init];
    btnArea.tag = 98;
    [btnArea addTarget:self action:@selector(btnPlaceClick:) forControlEvents:UIControlEventTouchUpInside];
    [btnArea setTitle:@"全部" forState:UIControlStateNormal];
    btnArea.titleLabel.font = [UIFont systemFontOfSize:12];
    btnArea.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btnArea.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [btnArea setBackgroundImage:[UIImage imageNamed:@"NavBar/bigAreaNav_bg.png"] forState:UIControlStateNormal];
    [_descView addSubview:btnArea];
    [btnArea autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [btnArea autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:lblSheng withOffset:-5];
    [btnArea autoPinEdge:ALEdgeLeft  toEdge:ALEdgeRight ofView:lblArea withOffset:5];
    [btnArea autoSetDimension:ALDimensionHeight toSize:25];
    
    UIImageView* downImage2 = [[UIImageView alloc] init];
    downImage2.image = [UIImage imageNamed:@"Task_Point/arrow_down_white.png"];
    [btnArea addSubview:downImage2];
    [downImage2 autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:4];
    [downImage2 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [downImage2 autoSetDimensionsToSize:CGSizeMake(10, 6)];
    
    
    self.tableVContent.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setViewLayoutConstraint];
    
//    UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btnHome setBackgroundImage:[UIImage imageNamed:@"NavBar/btn_nav_home.png"] forState:UIControlStateNormal];
//    [btnHome setFrame:CGRectMake(0, 0, 25, 25)];
//    [btnHome addTarget:self action:@selector(btnHomeClick) forControlEvents:UIControlEventTouchUpInside];
//    
//    [self.navigationController navbarRightItemCustomized:@[btnHome] onwer:self.navigationItem];
    
    [self requestDatas];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([[UIApplication getObjectType:Number key:kShouldRequestDataWhenBack] boolValue]) {
        [self requestDatas];
    }
}

- (void)setViewLayoutConstraint
{
    [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 10, 0) excludingEdge:ALEdgeTop];
    [self.tableVContent autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:_descView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)btnHomeClick
{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:NSClassFromString(@"TabBarViewController")]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
-(void)selectArea
{
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryAreaListEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:nil
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

-(void)selectShen
{
    NSDictionary *dicParam = @{@"areaId":_QuyuId};
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryProvinceListEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}
-(void)selectShi
{
    NSDictionary *dicParam = @{@"provinceId":_provinceId};
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryCityListEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

- (void)requestDatas
{
    NSDictionary *dicParam = @{@"areaId":_QuyuId,@"activityId":self.activityId,@"provinceId":_provinceId,@"cityId":_cityId};
    
    [UIApplication showLoadingView:kTextShowInProgress];
    NSString *interface = @"queryShopListForReviewEX";
    
    NSOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(interface)
                                                     interface:interface
                                                        params:dicParam
                                                      dataType:BRNetMgrDataTypeJSON
                                                        method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryShopListForReviewEX"])
    {
        self.arrContents = [result[@"shopList"] validDataOfClass:[NSArray class]];
        [self.tableVContent reloadData];
        
        if (self.arrContents.count == 0) {
            self.imageVNoResult.hidden = NO;
        }
        else
        {
            self.imageVNoResult.hidden = YES;
        }
    }
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryAreaListEX"])
    {
        self.areaArrContents = [result[@"areaList"] validDataOfClass:[NSArray class]];
        selectType = @"area";
        [self addTaskPartView:self.areaArrContents andType:@"area"];
    }
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryProvinceListEX"])
    {
        self.shenArrContents = [result[@"provinceList"] validDataOfClass:[NSArray class]];
        selectType = @"shen";
        [self addTaskPartView:self.shenArrContents andType:@"shen"];
    }
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryCityListEX"])
    {
        self.shiArrContents = [result[@"cityList"] validDataOfClass:[NSArray class]];
        selectType = @"shi";
        [self addTaskPartView:self.shiArrContents andType:@"shi"];
    }
    
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}
-(void)btnPlaceClick:(UIButton*)sender
{
    [popTipView dismissAnimated:YES];
    if (sender.tag == 98) {
        if (1) {
            [self selectArea];
        }
        else
        {
        }
    }
    if (sender.tag == 99) {
        if (1) {
            if ([_QuyuId isEqualToString:@""]) {
                [UIApplication showToastViewMessage:@"请先选择区域!"];
            }
            else
            {
                [self selectShen];
            }
        }
        else
        {
        }
        
    }
    if (sender.tag == 100) {
        if (1) {
            if ([_provinceId isEqualToString:@""]) {
                [UIApplication showToastViewMessage:@"请选选择省份!"];
            }
            else
            {
                [self selectShi];
            }
        }
        else
        {
        }
        
    }
}

-(void)addTaskPartView:(NSArray*)arr andType:(NSString*)type
{
    _view1 = [[ListPartView alloc] initWithFrame:self.navigationController.view.bounds andArray:arr andType:type];
    __weak typeof(BATaskPointDetailViewController) *weakSelf = self;
    _view1.BtnClickBlock = ^(int tag) {
        [weakSelf listBtnClick:tag];
    };
    UITapGestureRecognizer* tapGesture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Actiondo:)];
    tapGesture1.delegate = self;
    [_view1 addGestureRecognizer:tapGesture1];
    [self.navigationController.view addSubview:_view1];
}
-(void)listBtnClick:(int)rowNum
{
    if ([selectType isEqualToString:@"area"]) {
        if (rowNum == 0) {
            [btnArea setTitle:@"全部" forState:UIControlStateNormal];
            _QuyuId = @"";
        }
        else
        {
            [btnArea setTitle:self.areaArrContents[rowNum-1][@"areaName"] forState:UIControlStateNormal];
            _QuyuId = self.areaArrContents[rowNum-1][@"id"];
        }
        [btnSheng setTitle:@"全部" forState:UIControlStateNormal];
        _provinceId = @"";
        [btnShi setTitle:@"全部" forState:UIControlStateNormal];
        _cityId = @"";
        [self requestDatas];
    }
    
    if ([selectType isEqualToString:@"shen"]) {
        if (rowNum == 0) {
            _provinceId = @"";
            [btnSheng setTitle:@"全部" forState:UIControlStateNormal];
        }
        else
        {
            _provinceId = self.shenArrContents[rowNum-1][@"id"];
            [btnSheng setTitle:self.shenArrContents[rowNum-1][@"name"] forState:UIControlStateNormal];
        }
        _cityId = @"";
        [btnShi setTitle:@"全部" forState:UIControlStateNormal];
        [self requestDatas];
    }
    
    if ([selectType isEqualToString:@"shi"]) {
        if (rowNum == 0) {
            _cityId = @"";
            [btnShi setTitle:@"全部" forState:UIControlStateNormal];
        }
        else
        {
            _cityId = self.shiArrContents[rowNum-1][@"id"];
            [btnShi setTitle:self.shiArrContents[rowNum-1][@"name"] forState:UIControlStateNormal];
        }
        [self requestDatas];
    }
    
    [_view1 removeFromSuperview];
}
-(void)Actiondo:(UITapGestureRecognizer*)sender
{
    CGPoint point = [sender locationInView:self.view];
    
    NSLog(@"handleSingleTap!pointx:%f,y:%f",point.x,point.y);
    
    [_view1 removeFromSuperview];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view != _view1) {
        return NO;
        
    }
    return YES;
}

- (void)configureCell:(BATaskPointCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
    cell.lblPoint.text = self.arrContents[indexPath.row][@"name"];
    cell.lblQy.text = self.arrContents[indexPath.row][@"shopExecuteActivityDesc"];
}

#pragma mark =============  UITableView DataSource  =============

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"TaskListCell";
    BATaskPointCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[BATaskPointCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
    }
    [self configureCell:cell forIndexPath:indexPath];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrContents.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35)];
    //viewHeader.backgroundColor = [UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha:1];
    viewHeader.backgroundColor = [UIColor colorWithRed:0.9333 green:0.9333 blue:0.9333 alpha:1];
    
    UILabel *lblPoint = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 35)];
    lblPoint.textColor = [UIColor lightGrayColor];
    lblPoint.backgroundColor = [UIColor clearColor];
    lblPoint.font = [UIFont boldSystemFontOfSize:13];
    lblPoint.textAlignment = NSTextAlignmentCenter;
    lblPoint.text = @"商场名称";
    [viewHeader addSubview:lblPoint];
    
    UILabel *lblArea = [[UILabel alloc] initWithFrame:CGRectMake(180, 0, 90, 35)];
    lblArea.textColor = [UIColor lightGrayColor];
    lblArea.backgroundColor = [UIColor clearColor];
    lblArea.font = [UIFont boldSystemFontOfSize:13];
    lblArea.textAlignment = NSTextAlignmentCenter;
    lblArea.text = @"任务完成状态";
    [viewHeader addSubview:lblArea];
    
    return viewHeader;
}
-(void)searchClick
{
    NSLog(@"SearchClick");
}
#pragma mark =============  UITableView Delegate  =============

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    DLog(@"You Click At Section: %d Row: %d", (int)indexPath.section, (int)indexPath.row);
    BATaskDetailViewController* vc = [[BATaskDetailViewController alloc] init];
    vc.shopId = self.arrContents[indexPath.row][@"id"];
    vc.taskId = self.arrContents[indexPath.row][@"taskId"];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark =============  CMPopTipView Delegate  =============
- (void)popTipViewWasDismissedByUser:(CMPopTipView *)popTipView
{
    
}
@end

@implementation BATaskPointCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.lblPoint = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 44)];
        _lblPoint.textColor = RGBColor(0, 99, 159, 1);
        _lblPoint.backgroundColor = [UIColor clearColor];
        _lblPoint.font = [UIFont systemFontOfSize:13];
        _lblPoint.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_lblPoint];
        
        self.lblQy = [[UILabel alloc] initWithFrame:CGRectMake(180, 0, 90, 44)];
        _lblQy.textColor = [UIColor lightGrayColor];
        _lblQy.backgroundColor = [UIColor clearColor];
        _lblQy.font = [UIFont systemFontOfSize:13];
        _lblQy.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_lblQy];
        
        self.imageVArrow = [[UIImageView alloc] initWithFrame:CGRectMake(297, 15.5, 8, 13)];
        _imageVArrow.image = [UIImage imageNamed:@"Task_Point/image_point_arrow.png"];
        [self.contentView addSubview:_imageVArrow];
        
        //        self.imageVUser = [[UIImageView alloc] initWithFrame:CGRectMake(10, 14, 15, 16)];
        //        [self.contentView addSubview:_imageVUser];
        
        UIView *viewLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 320, 0.5)];
        viewLine.backgroundColor = [UIColor colorWithRed:0.7333 green:0.7333 blue:0.7333 alpha:1];
        [self.contentView addSubview:viewLine];
        
    }
    return self;
}

@end