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

#import "SATaskPointDetailViewController.h"
#import "TaskCheckViewController.h"
#import "CMPopTipView.h"
#import "SATaskDetailViewController.h"
#import "ListPartView.h"

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

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


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

@end

@interface SATaskPointCell : 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 SATaskPointDetailViewController

- (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 = @"";
    
    _descView = [[UIView alloc] init];
    _descView.backgroundColor = [UIColor colorWithRed:0.1569 green:0.6235 blue:0.7216 alpha: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/smallAreaNav_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/smallAreaNav_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];
    
    lblAreaName = [[UILabel alloc] init];
    lblAreaName.textColor = [UIColor whiteColor];
    lblAreaName.text = [DataMgr getInstance].smallAreaName;
    lblAreaName.textAlignment = NSTextAlignmentCenter;
    lblAreaName.font = [UIFont systemFontOfSize:12];
    [_descView addSubview:lblAreaName];
    [lblAreaName autoAlignAxis:ALAxisHorizontal toSameAxisOfView:btnShi];
    [lblAreaName autoPinEdge:ALEdgeRight toEdge:ALEdgeLeft ofView:lblSheng withOffset:-5];
    [lblAreaName autoPinEdge:ALEdgeLeft  toEdge:ALEdgeRight ofView:lblArea withOffset:-5];
    
    
    
    self.tableVContent.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self setViewLayoutConstraint];
    
    [self requestDatas];
    
}

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

- (void)setViewLayoutConstraint
{
    [self.tableVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 40, 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];
        }
    }
}
#pragma ---------------------   获取商场列表   -----------------------
- (void)requestDatas
{
    NSDictionary *dicParam = @{@"areaId":[DataMgr getInstance].smallAreaId,@"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 ---------------------   获取省信息   -----------------------
-(void)selectShen
{
    NSDictionary *dicParam = @{@"areaId":[DataMgr getInstance].smallAreaId};
    
    [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];
}
#pragma ---------------------   获取市信息   -----------------------
-(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];
}

#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:@"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
{
    if (sender.tag == 99) {
        if (1) {
            [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(SATaskPointDetailViewController) *weakSelf = self;
    _view1.BtnClickBlock = ^(int tag) {
        [weakSelf listBtnClick:tag];
    };
    //    _view1.closeClickBlock = ^(NSString* tag) {
    //        [weakSelf listBtnClick:@"close"];
    //    };
    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:@"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:(SATaskPointCell *)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";
    SATaskPointCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[SATaskPointCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
    }
    [self configureCell:cell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    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);
    SATaskDetailViewController* vc = [[SATaskDetailViewController alloc] init];
    vc.shopId = self.arrContents[indexPath.row][@"id"];
    vc.taskId = self.arrContents[indexPath.row][@"taskId"];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
#pragma ---------------------   自定义cell   -----------------------
@implementation SATaskPointCell

- (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 = [UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha: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];
        
        
        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