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

#import "GoodExampleViewController.h"
#import "TaskDetailViewController.h"
#import "TaskHistoryViewController.h"
#import "BRNetworkMgr.h"
#import "RDVTabBarController.h"
#import <UIImageView+WebCache.h>
#import <SDImageCache.h>
#import "TaskNewDetailViewController.h"

@interface ExampleListCell : BaseTableViewCell

@property (nonatomic, strong) UIImageView *imageVContent;
@property (nonatomic, strong) UILabel *lblTitle;
@property (nonatomic, strong) UILabel *lblDueTime;
@property (nonatomic, strong) UILabel *lblNumber;
@property (nonatomic, strong) UIImageView *imageVLocation;
@property (nonatomic, strong) UILabel *lblAddress;
@property (nonatomic, strong) UILabel *lblStatus;
@property (nonatomic, strong) UIView *viewLine;

@property (nonatomic, strong) UIImageView *imageVUser;

@end

@interface GoodExampleViewController () < BRNetworkMgrDelegate >

@property(nonatomic,strong)UITableView* tableView;

@end

@implementation GoodExampleViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"优秀案例";
        
//        self.heightOfButtons = 50.0f;
//        self.numberOfItems = 2;
//        self.arrItemTitles = [NSMutableArray arrayWithArray:@[@"未完成(0)", @"已完成(0)"]];
//        self.arrItemBgNorImages = @[[UIImage imageNamed:@"TabBar/tasktab_undone_off.png"],[UIImage imageNamed:@"TabBar/tasktab_done_off.png"]];
//        self.arrItemBgPreImages = @[[UIImage imageNamed:@"TabBar/tasktab_undone_on.png"],[UIImage imageNamed:@"TabBar/tasktab_done_on.png"]];
//        self.titleInsets = UIEdgeInsetsMake(22, 0, 0, 0);
//        self.arrItemTitleNorColors = @[[UIColor whiteColor], [UIColor whiteColor]];
//        self.arrItemTitlePreColors = @[[UIColor colorWithRed:0.2118 green:0.7098 blue:0.9490 alpha:1], [UIColor colorWithRed:0.2118 green:0.7098 blue:0.9490 alpha:1]];
//        self.titleFontNor = [UIFont systemFontOfSize:12];
//        self.TitleFontPre = [UIFont boldSystemFontOfSize:12];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _tableView = [[UITableView alloc] init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    self.lastIndexOfItem = 01;
    [self.dictTableDatas removeAllObjects];
   // [self reRequestTableViewDatas];
    // Do any additional setup after loading the view.
    
    //[self queryInitCount];
    //[self reloadItemTitles];
    
    UIImageView* image = [[UIImageView alloc] init];
    image.image = [UIImage imageNamed:@"pic_zanwushuju.png"];
    [self.view addSubview:image];
    [image autoAlignAxis:ALAxisVertical toSameAxisOfView:self.view];
    [image autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.view];
    [image autoSetDimensionsToSize:CGSizeMake(250, 270)];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.leftBarButtonItems = nil;
    self.navigationController.navigationBarHidden = NO;
    self.rdv_tabBarController.navigationController.navigationBarHidden = YES;
    
    
    if ([[UIApplication getObjectType:Number key:kShouldRequestDataWhenBack] boolValue]) {
        [self.dictTableDatas removeAllObjects];
        [self reRequestTableViewDatas];
        [UIApplication saveObject:@NO type:Number key:kShouldRequestDataWhenBack];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)queryInitCount
{
    NSString *interface = @"queryInitCount";
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseURL(interface)
                                                                interface:interface
                                                                   params:nil
                                                                 dataType:BRNetMgrDataTypeJSON
                                                                   method:BRNetMgrMethodPost];
    [self.networkMgr startOperation:operation];
}

//- (void)reRequestTableViewDatas
//{
//    NSString *interface = @"queryTaskList";
//    //  状态有未完成，已完成，过期 对应01，02，03
//    NSDictionary *dicParam = @{@"status":[NSString stringWithFormat:@"%02d", (int)self.lastIndexOfItem+1]};
//    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseURL(interface)
//                                                                interface:interface
//                                                                   params:dicParam
//                                                                 dataType:BRNetMgrDataTypeJSON
//                                                                   method:BRNetMgrMethodPost];
//    [operation setUserInfo:@{@"interface":interface,
//                             @"lastIndexOfItem":kDataForTableKey(self.lastIndexOfItem)}];
//    [self.networkMgr startOperation:operation];
//}

#pragma mark =============  BRNetworkMgr Delegate  =============
- (void)httpOperationSuccess:(AFHTTPRequestOperation *)operation
                      result:(NSDictionary *)result
{
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryTaskList"]) {
        NSString *keyForTable = operation.userInfo[@"lastIndexOfItem"];
        [self.dictTableDatas setObject:[result[@"taskList"] validDataOfClass:[NSArray class]]
                                forKey:keyForTable];
        
        [_tableView reloadData];
    }
    
    if ([operation.userInfo[@"interface"] isEqualToString:@"queryInitCount"]) {
        
        self.arrItemTitles = [NSMutableArray arrayWithArray:
                              @[[NSString stringWithFormat:@"未完成(%@)", result[@"unFinishedTaskCount"]],
                                [NSString stringWithFormat:@"已完成(%@)", result[@"finishedTaskCount"]]]];
        [self reloadItemTitles];
        
        UITabBarItem *itemNotice = [ self.rdv_tabBarController.tabBar.items objectAtIndex:1];
        int unReadNoticeCount = [result[@"unReadNoticeCount"] intValue];
        if (unReadNoticeCount == 0) {
            [itemNotice setBadgeValue:nil];
        }else {
            [itemNotice setBadgeValue:[NSString stringWithFormat:@"%d", unReadNoticeCount]?:@""];
        }
        
    }
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"TaskListCell";
    ExampleListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[ExampleListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    NSArray *arrContents = self.dictTableDatas[@"indexOfItem_1"];
    cell.lblTitle.text = arrContents[indexPath.row][@"activityName"];
    cell.lblDueTime.text = [NSString stringWithFormat:@"%@到期", arrContents[indexPath.row][@"endDate"]];
    cell.lblNumber.text = [NSString stringWithFormat:@"编号：%@", arrContents[indexPath.row][@"id"]];
    cell.lblAddress.text = arrContents[indexPath.row][@"shopName"];
    cell.lblStatus.text = @"已完成";
    [cell.imageVContent sd_setImageWithURL:[NSURL URLWithString:arrContents[indexPath.row][@"pictureURL"]]
                          placeholderImage:[UIImage imageNamed:@"pic_jiazaizhogn.png"]
                                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
                                     if (!image) {
                                         [cell.imageVContent setImage:[UIImage imageNamed:@"pic_jiazaishibai.png"]];
                                     }
                                 }];
    if ([[DataMgr getInstance].roleId isEqualToString:@"2"]) {
        cell.imageVUser.image = [UIImage imageNamed:@"icon_jiancha.png"];
    }else {
        cell.imageVUser.image = [UIImage imageNamed:@"icon_hecha.png"];
    }
    
    return cell;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arrContents = self.dictTableDatas[@"indexOfItem_1"];
    return arrContents.count;
}


#pragma mark =============  UITableView Delegate  =============

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndexPath = indexPath;
    
    //NSArray *arrContents = self.dictTableDatas[kDataForTableKey(tableView.tag)];
    if (self.lastIndexOfItem == 2 || self.lastIndexOfItem == 1) {
        //        TaskHistoryViewController *detailVC = [[TaskHistoryViewController alloc] initWithNibName:nil bundle:nil];
        //        detailVC.taskId = arrContents[indexPath.row][@"id"];
        //        detailVC.activityName = arrContents[indexPath.row][@"activityName"];
        TaskNewDetailViewController* detailVC = [[TaskNewDetailViewController alloc] init];
        [self.rdv_tabBarController.navigationController pushViewController:detailVC animated:YES];
    }else {
        TaskNewDetailViewController* detailVC = [[TaskNewDetailViewController alloc] init];
        //        TaskDetailViewController *detailVC = [[TaskDetailViewController alloc] initWithNibName:nil bundle:nil];
        //        detailVC.taskId = arrContents[indexPath.row][@"id"];
        //        detailVC.activityName = arrContents[indexPath.row][@"activityName"];
        [self.rdv_tabBarController.navigationController pushViewController:detailVC animated:YES];
    }
    
}

- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2 == 0) {
        cell.contentView.backgroundColor = RGBColor(239, 238, 239, 1);
    }else{
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    
}

@end

@implementation ExampleListCell

- (void)dealloc
{
    self.imageVContent = nil;
    self.lblTitle = nil;
    self.lblDueTime = nil;
    self.lblNumber = nil;
    self.lblAddress = nil;
    self.lblStatus = nil;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        [self.imageVContent autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(10, 10, 10, 0) excludingEdge:ALEdgeRight];
        [self.imageVContent autoSetDimension:ALDimensionWidth toSize:80];
        
        //NSArray *arrTitles = @[self.lblTitle, self.lblDueTime, self.lblAddress];
        [self.lblTitle autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.imageVContent withOffset:10];
        [self.lblTitle autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.imageVContent];
        [self.lblTitle autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
        //[arrTitles autoDistributeViewsAlongAxis:ALAxisVertical alignedTo:ALAttributeRight withFixedSize:20 insetSpacing:YES];
        
        [self.lblDueTime autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblTitle];
        [self.lblDueTime autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblTitle withOffset:5];
        
        [self.lblNumber autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblDueTime withOffset:10];
        [self.lblNumber autoPinEdge:ALEdgeTop toEdge:ALEdgeTop ofView:self.lblDueTime];
        
        [self.lblAddress autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblTitle withOffset:10];
        [self.lblAddress autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblNumber withOffset:5];
        
        [self.imageVLocation autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.imageVContent withOffset:10];
        [self.imageVLocation autoSetDimensionsToSize:CGSizeMake(8, 13)];
        [self.imageVLocation autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblAddress];
        
        [self.lblStatus autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:6];
        [self.lblStatus autoPinEdgeToSuperviewEdge:ALEdgeBottom];
        [self.lblStatus autoSetDimensionsToSize:CGSizeMake(90, 20)];
        
        //        [self.imageVUser autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:5];
        //        [self.imageVUser autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:5];
        //        [self.imageVUser autoSetDimensionsToSize:CGSizeMake(15, 16)];
        
        //        [self.viewLine autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeTop];
        //        [self.viewLine autoSetDimension:ALDimensionHeight toSize:0.5];
        //        self.imageVContent.frame = CGRectMake(5, 5, 120, 90);
        //        self.lblAddress.frame = CGRectMake(145, 70, 165, 20);
        //        self.lblDueTime.frame = CGRectMake(135, 50, 175, 20);
        //        self.lblNumber.frame = CGRectMake(135, 30, 175, 20);
        //        self.lblTitle.frame = CGRectMake(135, 10, 175, 20);
        //        self.imageVLocation.frame = CGRectMake(135, 70, 8, 13);
        
        
        
    }
    return self;
}

#pragma mark =============  LazyLoad Properties  =============

- (UIImageView *)imageVContent
{
    if (!_imageVContent) {
        self.imageVContent = [UIImageView newAutoLayoutView];
        self.imageVContent.layer.cornerRadius = 5;
        self.imageVContent.clipsToBounds = YES;
        [self.contentView addSubview:_imageVContent];
    }
    return _imageVContent;
}

- (UIImageView *)imageVUser
{
    if (!_imageVUser) {
        self.imageVUser = [UIImageView newAutoLayoutView];
        //[self.contentView addSubview:_imageVUser];
    }
    return _imageVUser;
}

- (UIImageView *)imageVLocation
{
    if (!_imageVLocation) {
        self.imageVLocation = [UIImageView newAutoLayoutView];
        _imageVLocation.image = [UIImage imageNamed:@"Task/icon_location_task.png"];
        [self.contentView addSubview:_imageVLocation];
    }
    return _imageVLocation;
}

//- (UIView *)viewLine
//{
//    if (!_viewLine) {
//        self.viewLine = [UIView newAutoLayoutView];
//        _viewLine.backgroundColor = RGBColor(0, 120, 193, 1);
//        [self.contentView addSubview:_viewLine];
//    }
//    return _viewLine;
//}

- (UILabel *)lblTitle
{
    if (!_lblTitle) {
        self.lblTitle = [self getAutoLayoutLabel];
        _lblTitle.font = [UIFont boldSystemFontOfSize:15];
        _lblTitle.textColor = [UIColor darkGrayColor];
        [self.contentView addSubview:_lblTitle];
    }
    return _lblTitle;
}

- (UILabel *)lblStatus
{
    if (!_lblStatus) {
        self.lblStatus = [self getAutoLayoutLabel];
        _lblStatus.font = [UIFont boldSystemFontOfSize:13];
        _lblStatus.backgroundColor = [UIColor lightGrayColor];
        _lblStatus.textColor = [UIColor whiteColor];
        _lblStatus.textAlignment = NSTextAlignmentCenter;
        [self.contentView addSubview:_lblStatus];
    }
    return _lblStatus;
}

- (UILabel *)lblDueTime
{
    if (!_lblDueTime) {
        self.lblDueTime = [self getAutoLayoutLabel];
        _lblDueTime.font = [UIFont systemFontOfSize:13];
        _lblDueTime.textColor = [UIColor colorWithRed:0.2118 green:0.7098 blue:0.9490 alpha:1];
        [self.contentView addSubview:_lblDueTime];
    }
    return _lblDueTime;
}

- (UILabel *)lblNumber
{
    if (!_lblNumber) {
        self.lblNumber = [self getAutoLayoutLabel];
        _lblNumber.textColor = [UIColor darkGrayColor];
        [self.contentView addSubview:_lblNumber];
    }
    return _lblNumber;
}

- (UILabel *)lblAddress
{
    if (!_lblAddress) {
        self.lblAddress = [self getAutoLayoutLabel];
        _lblAddress.textColor = [UIColor darkGrayColor];
        [self.contentView addSubview:_lblAddress];
    }
    return _lblAddress;
}

- (UILabel *)getAutoLayoutLabel
{
    UILabel *lblTemp = [UILabel newAutoLayoutView];
    lblTemp.textAlignment = NSTextAlignmentLeft;
    lblTemp.backgroundColor = [UIColor clearColor];
    lblTemp.textColor = [UIColor blackColor];
    lblTemp.font = [UIFont systemFontOfSize:13];
    lblTemp.numberOfLines = 1;
    return lblTemp;
}


@end
