//
//  InspectTaskViewController.m
//  redstar
//
//  Created by admin on 15/10/27.
//  Copyright © 2015年 ZWF. All rights reserved.
//

#import "InspectTaskViewController.h"
#import "InspectSortTableCell.h"

#import "TaskGroup.h"
#import "TaskModel.h"
#import "InspectHeaderView.h"
#import "HttpClient.h"

#import "TaskDetailModel.h"
#import <MBProgressHUD.h>

#import "InspectNotUploadViewController.h"
#import "InspectUploadedViewController.h"

#define kTaskSortCell @"InspectTaskSortCell"


#import "InspectTaskDetailCell.h"
#define kTaskDetailCell @"inspectTaskDetailCell"

#import "InspectTitleTableViewCell.h"
#define kTAskTitleCell @"inspectTitleTaViewCell"

@interface InspectTaskViewController () <UITableViewDelegate, UITableViewDataSource, InspectHeaderDelegate>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *taskData;
@property (nonatomic, assign) BOOL isOpen;
@property (nonatomic, strong) TaskDetailModel *taskDetail;
@end

@implementation InspectTaskViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = kSectionBackGroundColor;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    [backBtn setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"口碑巡检任务"];
    customLab.font = [UIFont boldSystemFontOfSize:19];
    self.navigationItem.titleView = customLab;
    
    
    // 口碑巡检明细
    [self requestRankingDetail];
    _isOpen = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(requestCurrentList)
                                                 name:kRefreshInspectPointNotification
                                               object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

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



#pragma mark - Private Methods


- (void)requestCurrentList
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@/%@",kRedStarURL, kInspectDetailURL, self.uuid, self.store_uuid];
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpClient getPraiseDetailWithParameters:nil completion:^(id response, NSError *error) {
        NSLog(@"口碑巡检明细PraiseDetail = %@", response);
        NSDictionary *dataDict = response[@"data"];
        TaskDetailModel *taskDetail = [TaskDetailModel taskDetailModelWithDict:dataDict];
        _taskDetail = taskDetail;
        
        NSArray *dataArray = dataDict[@"categories"];
        
        NSMutableArray *tgArray = [NSMutableArray array];
        for (NSDictionary *dict in dataArray) {
            TaskGroup *taskGroup = [TaskGroup taskGroupWithDict:dict];
            [tgArray addObject:taskGroup];
        }
        
        _taskData = tgArray;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.tableView reloadData];
    }];

}

// 返回上一页面
- (void)doBack:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)requestRankingDetail
{
    NSString *url = [NSString stringWithFormat:@"%@%@%@/%@",kRedStarURL, kInspectDetailURL, self.uuid, self.store_uuid];
    NSLog(@"url = %@", url);
    HttpClient *httpClient = [[HttpClient alloc] initWithUrl:url];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [httpClient getPraiseDetailWithParameters:nil completion:^(id response, NSError *error) {
        NSLog(@"口碑巡检明细PraiseDetail = %@", response);
        NSLog(@"error = %@", error);
        NSDictionary *dataDict = response[@"data"];
        TaskDetailModel *taskDetail = [TaskDetailModel taskDetailModelWithDict:dataDict];
        _taskDetail = taskDetail;
        
        NSArray *dataArray = dataDict[@"categories"];
        
        NSMutableArray *tgArray = [NSMutableArray array];
        for (NSDictionary *dict in dataArray) {
            TaskGroup *taskGroup = [TaskGroup taskGroupWithDict:dict];
            [tgArray addObject:taskGroup];
        }
        
        _taskData = tgArray;
        
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, CGFLOAT_MIN)];
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];
}

- (void)unfoldCilck:(UIButton *)sender
{
    _isOpen = !_isOpen;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
}
#pragma mark - TableView Delegate/DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _taskData.count + 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    } else {
        TaskGroup *taskGroup = _taskData[section - 1];
        NSInteger count = taskGroup.isOpened ? taskGroup.answers.count : 0;
        return count;
    }
   
}

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            InspectTaskDetailCell *cell=[tableView dequeueReusableCellWithIdentifier:kTaskDetailCell];
            if (!cell) {
                cell = [[InspectTaskDetailCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTaskDetailCell];
            }
            cell.taskDetail = _taskDetail;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.unfoldBtn addTarget:self action:@selector(unfoldCilck:) forControlEvents:UIControlEventTouchUpInside];
            if (_isOpen) {
                cell.introDetailLabel.text = [NSString stringWithFormat:@"%@", _taskDetail.remark];
            } else {
                cell.introDetailLabel.text = @"";
            }

            return cell;

        } else {
            InspectTitleTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:kTAskTitleCell];
            if (!cell) {
                cell = [[InspectTitleTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTAskTitleCell];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    } else {
        InspectSortTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kTaskSortCell];
        if (!cell) {
            cell = [[InspectSortTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTaskSortCell];
        }
        
        TaskGroup *taskGroup = _taskData[indexPath.section - 1];
        TaskModel *task = taskGroup.answers[indexPath.row];
        cell.task = task;
        cell.titleLabel.text = [NSString stringWithFormat:@"%d、%@", (int)indexPath.row + 1 ,task.title];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        return cell;
    }

    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return;
    } else {
        TaskGroup *taskGroup = _taskData[indexPath.section - 1];
        TaskModel *task = taskGroup.answers[indexPath.row];
        
        if (task.state == 0) {
            
            NSArray *permissions = [[NSUserDefaults standardUserDefaults] objectForKey:@"permissions"];
            if ([permissions containsObject:@"500103"]) {
                
                if ([task.readonly isEqualToString:@"1"]) {
                    InspectUploadedViewController *inspectVC = [[InspectUploadedViewController alloc] init];
                    inspectVC.questionCount = taskGroup.questionCount;
                    inspectVC.taskModel = task;
                    [self.navigationController pushViewController:inspectVC animated:YES];
                } else {
                    InspectNotUploadViewController *inspectNotVC = [[InspectNotUploadViewController alloc] init];
                    inspectNotVC.questionCount = taskGroup.questionCount;
                    inspectNotVC.taskModel = task;
                    inspectNotVC.store_uuid = _taskDetail.store_uuid;
                    inspectNotVC.praiseUuid = _taskDetail.uuid;
                    inspectNotVC.questionUuid = task.uuid;
                    [self.navigationController pushViewController:inspectNotVC animated:YES];
                }
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有编辑检查点的权限！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
            }
        } else {
            InspectUploadedViewController *inspectVC = [[InspectUploadedViewController alloc] init];
            inspectVC.questionCount = taskGroup.questionCount;
            inspectVC.taskModel = task;
            [self.navigationController pushViewController:inspectVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 50;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

// 自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    } else {
        InspectHeaderView *headView = [InspectHeaderView headViewWithTableView:tableView];
        headView.delegate = self;
        headView.taskGroup = _taskData[section - 1];
        return headView;
    }
}

- (void)clickHeadView
{
    [_tableView reloadData];
}
#pragma mark - lazy loading
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[InspectSortTableCell class] forCellReuseIdentifier:kTaskSortCell];
        [_tableView registerClass:[InspectTaskDetailCell class] forCellReuseIdentifier:kTaskDetailCell];
        [_tableView registerClass:[InspectTitleTableViewCell class] forCellReuseIdentifier:kTAskTitleCell];

        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 150.0;
        
        [self.view addSubview:_tableView];
        
        NSLayoutConstraint *tableTop = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        [self.view addConstraint:tableTop];
        
        NSLayoutConstraint *tableLeft = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
        [self.view addConstraint:tableLeft];
        
        NSLayoutConstraint *tableRight = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
        [self.view addConstraint:tableRight];
        
        NSLayoutConstraint *tableBottom = [NSLayoutConstraint constraintWithItem:_tableView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [self.view addConstraint:tableBottom];
    }
    return _tableView;
}

@end
