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

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

@interface TaskListCell : BaseTableViewCell

@property (nonatomic, strong) UIImageView *imageVContent;
@property (nonatomic, strong) UILabel *lblTitle;
@property (nonatomic, strong) UILabel *lblDueTime;
@property (nonatomic, strong) UILabel *lblActivityEndTime;
@property (nonatomic, strong) UIImageView *imageVLocation;
@property (nonatomic, strong) UILabel *lblProcess;
@property (nonatomic, strong) UILabel *lblStatus;

@property (nonatomic, strong) UIView *viewProcess;
@property (nonatomic, strong) UIView *viewProcessBG;

@property (nonatomic, strong) UIView *viewLine;

@property (nonatomic, strong) UIImageView *imageVUser;

@end

@interface TaskListViewController () < BRNetworkMgrDelegate ,UIGestureRecognizerDelegate>
@property(nonatomic,strong) SATaskPartView* view1;

@end

@implementation TaskListViewController

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

        self.heightOfButtons = 50.0f;
        self.numberOfItems = 2;
        self.arrItemTitles = [NSMutableArray arrayWithArray:@[@"未完成", @"已完成"]];
        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:14];
        self.TitleFontPre = [UIFont boldSystemFontOfSize:14];
        
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
    statusView.backgroundColor = [UIColor colorWithRed:0.2431 green:0.7137 blue:0.9373 alpha:1];
    [self.view addSubview:statusView];
    
    UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnHome setBackgroundImage:[UIImage imageNamed:@"Task/icon_filter1.png"] forState:UIControlStateNormal];
    [btnHome setFrame:CGRectMake(0, 0, 23, 23)];
    [btnHome addTarget:self action:@selector(btnHomeClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navigationController navbarRightItemCustomized:@[btnHome] onwer:self.navigationItem];
    
    

    [self reloadItemTitles];
}

-(void)btnHomeClick
{
    [self addTaskPartView];
}



#pragma mark =============  AddTaskPartView  =============

-(void)addTaskPartView
{
    _view1 = [[SATaskPartView alloc] initWithFrame:self.navigationController.view.bounds];
    __weak typeof(TaskListViewController) *weakSelf = self;
    _view1.BtnClickBlock = ^(NSString* 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:(NSString*)Name
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* str = @"";
    if ([Name isEqualToString:@"daoshi"]) {
        str=@"导视";
        _btnType = kDaoshicode;
    }
    if ([Name isEqualToString:@"meichen"]) {
        str=@"美陈";
        _btnType = kMeichengcode;
    }
    if ([Name isEqualToString:@"xiuxiqu"]) {
        str=@"公共区域";
        _btnType = kXiuxiqucode;
    }
    if ([Name isEqualToString:@"guanggaowei"]) {
        str=@"广告位";
        _btnType = kGuanggaoweicode;
    }
    if ([Name isEqualToString:@"beijingyinyue"]) {
        str=@"背景音乐";
        _btnType = kBeijingyinyuecode;
    }
    if ([Name isEqualToString:@"yingyunwuliao"]) {
        str=@"综合物料";
        _btnType = kYingyunwuliaocode;
    }
    if ([Name isEqualToString:@"dacuxiao"]) {
        str=@"大促销";
        _btnType = kDacuxiaocode;
    }
    if ([Name isEqualToString:@"xiaocuxiao"]) {
        str=@"小促销";
        _btnType = kXiaocuxiaocode;
    }
    self.title=[[NSString alloc] initWithFormat:@"任务一览-%@",str];
    [self reRequestTableViewDatas];
    [_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)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.rdv_tabBarController.navigationController.navigationBarHidden = YES;    
    
    //[self reRequestTableViewDatas];
    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)reRequestTableViewDatas
{
    NSString *interface = @"queryTaskListEX";
    [UIApplication showLoadingView:@"正在加载数据..."];
    //  状态有未完成，已完成，过期 对应01，02，03
    NSDictionary *dicParam = @{@"status":[NSString stringWithFormat:@"%02d", (int)self.lastIndexOfItem+1],@"type":self.btnType};
    AFHTTPRequestOperation *operation = [self.networkMgr operationWithURL:kBaseEXURL(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:@"queryTaskListEX"]) {
        NSString *keyForTable = operation.userInfo[@"lastIndexOfItem"];
        [self.dictTableDatas setObject:[result[@"taskList"] validDataOfClass:[NSArray class]]
                                forKey:keyForTable];
        
        [self reloadTableView];
        
        self.arrItemTitles = [NSMutableArray arrayWithArray:
                              @[[NSString stringWithFormat:@"未完成(%@)", result[@"unFinishedNum"]],
                                [NSString stringWithFormat:@"已完成(%@)", result[@"finishedNum"]]]];
        [self reloadItemTitles];
    }
}

- (void)httpOperationFailed:(AFHTTPRequestOperation *)operation
                      error:(NSError *)error
{
    self.arrItemTitles = [NSMutableArray arrayWithArray:
                          @[[NSString stringWithFormat:@"未完成(%@)",@"0"],
                            [NSString stringWithFormat:@"已完成(%@)", @"0"]]];
    [self reloadItemTitles];
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"TaskListCell";
    TaskListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[TaskListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    if ([DataMgr getInstance].lastIndexOfItemNum) {
        NSLog(@"1");
    }
    else
    {
        NSLog(@"0");
    }
    NSArray *arrContents = self.dictTableDatas[kDataForTableKey(tableView.tag)];
    cell.lblTitle.text = arrContents[indexPath.row][@"activityName"];
    cell.lblDueTime.text = [NSString stringWithFormat:@"%@", arrContents[indexPath.row][@"reportEndDate"]];
    cell.lblActivityEndTime.text = [NSString stringWithFormat:@"上报截止"];
    
    int i = (int)self.lastIndexOfItem+1;
    NSString* process = [NSString stringWithFormat:@"%@",arrContents[indexPath.row][@"progress"]];
    if (i == 2) {
        cell.lblProcess.text = [NSString stringWithFormat:@"评分: %@",arrContents[indexPath.row][@"score"]];
        cell.lblProcess.hidden = NO;
        cell.viewProcess.hidden = YES;
        cell.viewProcessBG.hidden = YES;
    }
    else
    {
        cell.lblProcess.text = [NSString stringWithFormat:@"%@个检查点 | %@%@",arrContents[indexPath.row][@"checkPointCount"],process,@"%"];
    }
    CGFloat f = [process floatValue]/100;
    
    [cell.viewProcessBG autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeRight];
    [cell.viewProcessBG autoSetDimension:ALDimensionWidth toSize:100*f];
    
    NSString*status = arrContents[indexPath.row][@"reviewStatus"];
    cell.lblStatus.text = arrContents[indexPath.row][@"reviewStatusDesc"];
    
    if ([status isEqualToString:kWeitijiaocode]) {
        cell.lblStatus.backgroundColor = [UIColor lightGrayColor];
    }
    else if ([status isEqualToString:kWeishenhecode]) {
        cell.lblStatus.backgroundColor = RGBColor(53, 181, 242, 1);
    }
    else if ([status isEqualToString:kShenhetongguocode]) {
        cell.lblStatus.backgroundColor = RGBColor(125, 211, 32, 1);
    }
    else if ([status isEqualToString:kDaizhenggaicode]) {
        cell.lblStatus.backgroundColor = RGBColor(255, 173, 37, 1);
    }
    else if ([status isEqualToString:kYizhenggaicode]) {
        cell.lblStatus.backgroundColor = RGBColor(53, 181, 242, 1);
    }
    else if ([status isEqualToString:kZhenggaishenhetongguocode]) {
        cell.lblStatus.backgroundColor = RGBColor(125, 211, 32, 1);
    }
    else
    {
        cell.lblStatus.backgroundColor = [UIColor lightGrayColor];
    }
    
    [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 85;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arrCurrent = self.dictTableDatas[kDataForTableKey(self.lastIndexOfItem)];
    if (arrCurrent.count == 0) {
        [UIApplication showNoResultImageView:tableView imageName:@"pic_zanwushuju.png"];

    }else {
        [UIApplication hideNoResultImageView:tableView];
    }
    
    NSArray *arrContents = self.dictTableDatas[kDataForTableKey(tableView.tag)];
    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) {

        TaskNewDetailViewController* detailVC = [[TaskNewDetailViewController alloc] init];
        detailVC.taskID = arrContents[indexPath.row][@"id"];
        detailVC.btnType = self.btnType;
        [self.navigationController pushViewController:detailVC animated:YES];
    }else {
        TaskNewDetailViewController* detailVC = [[TaskNewDetailViewController alloc] init];
        detailVC.taskID = arrContents[indexPath.row][@"id"];
        detailVC.btnType = self.btnType;

        [self.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 TaskListCell

- (void)dealloc
{
    self.imageVContent = nil;
    self.lblTitle = nil;
    self.lblDueTime = nil;
    self.lblActivityEndTime = nil;
    self.lblProcess = 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];
        

        [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];
        [self.lblDueTime autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblTitle];
        [self.lblDueTime autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblTitle withOffset:4];
        
        [self.lblActivityEndTime autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:self.lblDueTime withOffset:2];
        [self.lblActivityEndTime autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.lblDueTime];
        
        [self.lblProcess autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblTitle];
        [self.lblProcess autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblActivityEndTime withOffset:4];
        
        
        [self.viewProcess autoPinEdge:ALEdgeLeft toEdge:ALEdgeLeft ofView:self.lblTitle];
        [self.viewProcess autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.lblProcess withOffset:5];
        [self.viewProcess autoSetDimensionsToSize:CGSizeMake(100, 6)];
        
        

        [self.lblStatus autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
        [self.lblStatus autoPinEdgeToSuperviewEdge:ALEdgeBottom];
        [self.lblStatus autoSetDimensionsToSize:CGSizeMake(90, 20)];
        

        
        UIView* lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor colorWithRed:0.9143 green:0.9143 blue:0.9143 alpha:1];
        [self addSubview:lineView];
        [lineView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0) excludingEdge:ALEdgeTop];
        [lineView autoSetDimension:ALDimensionHeight toSize:1];
    }
    return self;
}

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

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

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



- (UIView *)viewProcess
{
    if (!_viewProcess) {
        self.viewProcess = [UIView newAutoLayoutView];
        _viewProcess.backgroundColor = [UIColor clearColor];
        _viewProcess.layer.borderWidth =1.5;
        _viewProcess.layer.borderColor = RGBColor(16, 133, 201, 1).CGColor;
        _viewProcess.layer.cornerRadius = 3;
        [self.contentView addSubview:_viewProcess];
    }
    return _viewProcess;
}

- (UIView *)viewProcessBG
{
    if (!_viewProcessBG) {
        self.viewProcessBG = [UIView newAutoLayoutView];
        _viewProcessBG.backgroundColor = RGBColor(16, 133, 201, 1);
        _viewProcessBG.layer.cornerRadius = 3;
        [self.viewProcess addSubview:_viewProcessBG];
    }
    return _viewProcessBG;
}



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

- (UILabel *)lblStatus
{
    if (!_lblStatus) {
        self.lblStatus = [self getAutoLayoutLabel];
        _lblStatus.font = [UIFont boldSystemFontOfSize:14];
        _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:12];
        _lblDueTime.textColor = [UIColor lightGrayColor];
        [self.contentView addSubview:_lblDueTime];
    }
    return _lblDueTime;
}

- (UILabel *)lblActivityEndTime
{
    if (!_lblActivityEndTime) {
        self.lblActivityEndTime = [self getAutoLayoutLabel];
        _lblActivityEndTime.font = [UIFont systemFontOfSize:12];
        _lblActivityEndTime.textColor = RGBColor(255, 173, 37, 1);
        [self.contentView addSubview:_lblActivityEndTime];
    }
    return _lblActivityEndTime;
}

- (UILabel *)lblProcess
{
    if (!_lblProcess) {
        self.lblProcess = [self getAutoLayoutLabel];
        _lblProcess.font = [UIFont systemFontOfSize:12];
        _lblProcess.textColor = [UIColor darkGrayColor];
        [self.contentView addSubview:_lblProcess];
    }
    return _lblProcess;
}

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


@end
