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

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

#import "InspectDetailHeaderView.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"


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

@property (nonatomic, strong) NSArray *taskData;

@property (nonatomic, strong) InspectDetailHeaderView *detailHeaderView;
@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];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(requestCurrentList)
                                                 name:@"kReloadTableView"
                                               object:nil];
}

- (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];
    
    __block InspectTaskViewController *weakSelf = self;
    [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];
        weakSelf.detailHeaderView.taskDetail = taskDetail;
        _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];
    
    __block InspectTaskViewController *weakSelf = self;
    [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];
        weakSelf.detailHeaderView.taskDetail = taskDetail;
        _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;

        [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];
}

#pragma mark - TableView Delegate/DataSource

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


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

// cell显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InspectSortTableCell *cell=[tableView dequeueReusableCellWithIdentifier:kTaskSortCell];
    if (!cell) {
        cell = [[InspectSortTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kTaskSortCell];
    }
    
    TaskGroup *taskGroup = _taskData[indexPath.section];
    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
{
    
    TaskGroup *taskGroup = _taskData[indexPath.section];
    TaskModel *task = taskGroup.answers[indexPath.row];
    
    if (task.state == 0) {
        
        NSArray *permissions = [[NSUserDefaults standardUserDefaults] objectForKey:@"permissions"];
        if ([permissions containsObject:@"500103"]) {
            
            //InspectNoUpLoadViewController *inspectNotVC = [[InspectNoUpLoadViewController alloc] init];
            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];
    }
}

// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

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

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

// 自定义section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    InspectHeaderView *headView = [InspectHeaderView headViewWithTableView:tableView];
    headView.delegate = self;
    headView.taskGroup = _taskData[section];
    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.tableHeaderView = self.detailHeaderView;
        [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;
}

- (InspectDetailHeaderView *)detailHeaderView
{
    if (!_detailHeaderView) {
        _detailHeaderView = [[InspectDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 285)];
    }
    return _detailHeaderView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
