//
//  InspectionTableViewController.m
//  patrol
//
//  Created by 曹云霄 on 16/9/1.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "InspectionTableViewController.h"
#import "InspectionPlanTableViewCell.h"
#import "InspectionHeaderTableViewCell.h"
#import "InspectionDetailTableViewController.h"
#import "SuspensionView.h"
#import "ParametersModel.h"
#import "InspectionResultModel.h"
#import "FilterManager.h"


#define CELL_HEIGHT 50

@interface InspectionTableViewController ()<InspectionPlanClickEventDelegate>

/**
 *  悬浮条
 */
@property (nonatomic,strong) SuspensionView *headerView;

/**
 *  头视图任务数
 */
@property (weak, nonatomic) IBOutlet UILabel *planNumberLabel;

/**
 *  督导人数
 */
@property (weak, nonatomic) IBOutlet UILabel *supervisionNumberLabel;

/**
 *  门店次数
 */
@property (weak, nonatomic) IBOutlet UILabel *storesNumberLabel;

/**
 *  排序条件
 */
@property (nonatomic,strong) ParametersModel *queryResultModel;

/**
 * VI检查列表结果
 */
@property (nonatomic,strong) InspectionResultModel *resultModel;

/**
 *  数据源数组,在需要分页的情况下用数组来持有对象
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 保存筛选后的筛选条件数据
 */
@property (nonatomic, strong) FilterViewModel *filterViewModel;

/**
 筛选条件管理
 */
@property (nonatomic, strong) FilterManager *filter;

/**
 任务数
 */
@property (weak, nonatomic) IBOutlet UILabel *taskNumberTitleLabel;

/**
 督导人数
 */
@property (weak, nonatomic) IBOutlet UILabel *supervisorTitleLabel;

/**
 门店次数
 */
@property (weak, nonatomic) IBOutlet UILabel *storeNumberTitleLabel;

@end

@implementation InspectionTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createBackBtn];
    [self uiConfigAction];
    [self addChooseButton];
}

#pragma mark -自定义返回视图
- (void)createBackBtn{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"result_back_icon"] forState:UIControlStateNormal];
    btn.frame  = CGRectMake(0, 0, 40, 40);
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [btn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
}

#pragma mark -返回
- (void)backClicked {
    if (self.isBackRootVc) {
        [self PopToRootViewControllerAnimated:YES];
    }else {
        [self PopViewControllerAnimated:YES];
    }
}


#pragma mark - UI
- (void)uiConfigAction
{
    self.title = @"VI检查结果";
    self.taskNumberTitleLabel.text = @"任务数";
    self.supervisorTitleLabel.text = @"督导人数";
    self.storeNumberTitleLabel.text = @"门店次数";
}

#pragma mark -添加筛选按钮
- (void)addChooseButton
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:kChooseImage style:UIBarButtonItemStyleDone target:self action:@selector(chooseButtonAction)];
}

#pragma mark -筛选VI检查结果
- (void)chooseButtonAction
{
    self.filter.filterViewModel = self.filterViewModel;
    @weakify(self);
    self.filter.completedBlock = ^(id returnValue) {
        @strongify(self);
        FilterViewModel *model = returnValue;
        self.filterViewModel = model;
        self.queryResultModel = (ParametersModel *)model.useQueryModel;
        self.queryResultModel.userUuid = kUser.f_user_uuid;
        [self.tableView.mj_header beginRefreshing];
    };
    [self pushViewController:self.filter.filterListVc animated:YES];
}

#pragma mark -获取数据
- (void)loadWebDataSource
{
    self.queryResultModel.pageNumber = self.pullPageIndex;
    [self getInspectionResultDatas];
}

#pragma mark - 获取VI检查结果数据
- (void)getInspectionResultDatas
{
    @weakify(self);
    [IBTLoadingView showProgressLabel:@"加载中"];
    [RequestManager request_QueryPatrolInspectResult:self.queryResultModel success:^(id returnValue) {
        [IBTLoadingView hideHUDWithText:nil];
        @strongify(self);
        if (self.pullPageIndex == ZERO) {
            [self.datasArray removeAllObjects];
        }
        if ([BaseViewModel verifyData:returnValue]) {
            self.resultModel = [[InspectionResultModel alloc]initWithDictionary:[BaseViewModel formatData:returnValue] error:nil];
            if (self.queryResultModel.pageNumber >= self.resultModel.planCount) {
                [self endRefresh:EndRefreshNotData];
            }else {
                [self endRefresh:EndRefreshDefault];
            }
            [self.datasArray addObjectsFromArray:self.resultModel.records];
            [self headerViewassignment];
        }else {
            [self endRefresh:EndRefreshNotData];
        }
        [self.tableView reloadData];
    } failure:^(id errorValue) {
        @strongify(self);
        [self endRefresh:EndRefreshNotData];
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:errorValue];
        [self.tableView reloadData];
    }];
}

#pragma mark - TableViewHeaderView赋值
- (void)headerViewassignment
{
    self.planNumberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.resultModel.planCount];
    self.supervisionNumberLabel.text = [NSString stringWithFormat:@"%ld",(long)self.resultModel.manTimes];
    //门店数，富文本
    NSString *string = [NSString stringWithFormat:@"%ld(%@%ld)",(long)self.resultModel.storeCount,@"剩",self.resultModel.remainStoreCount];
    NSRange storeRange = [string rangeOfString:[NSString stringWithFormat:@"(%@%ld)",@"剩",(long)self.resultModel.remainStoreCount]];
    NSString *stringRemain = [NSString stringWithFormat:@"%ld",(long)self.resultModel.remainStoreCount];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string];
    [attributedString addAttribute:NSForegroundColorAttributeName value:RGBA(225, 94, 94, 1) range:NSMakeRange(string.length - stringRemain.length-1, stringRemain.length)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10] range:storeRange];
    self.storesNumberLabel.attributedText = attributedString;
    //悬浮headerView
    [self.headerView.taskNumberButton setTitle:self.planNumberLabel.text forState:UIControlStateNormal];
    [self.headerView.inspectionNumberButton setTitle:self.supervisionNumberLabel.text forState:UIControlStateNormal];
    [self.headerView.storeNumberButton setAttributedTitle:attributedString forState:UIControlStateNormal];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.datasArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    InspectionPlanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[InspectionPlanTableViewCell className] forIndexPath:indexPath];
    cell.delegate = self;
    cell.planResultModel = self.datasArray[indexPath.section];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    InspectionHeaderTableViewCell *header = [tableView dequeueReusableCellWithIdentifier:[InspectionHeaderTableViewCell className]];
    header.planModel = self.datasArray[section];
    header.contentView.backgroundColor = [UIColor whiteColor];
    return header.contentView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self calculateCellHeight:indexPath];
}

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

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

#pragma mark - <InspectionPlanClickEventDelegate>
- (void)storesClickEvent:(NSIndexPath *)indexPath inspectionPerson:(Inspectors *)inspectors planResults:(Results *)results planUuid:(NSString *)uuid
{
    InspectionDetailTableViewController *details = [InspectionDetailTableViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_PATROLINSPECTRESULT];
    details.inspectorsModel = inspectors;
    details.resultsModel = results;
    details.planUuid = uuid;
    [self pushViewController:details animated:YES];
}

#pragma mark - 改变悬浮条alpha
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat scrollOffsetY = scrollView.mj_offsetY;
    self.headerView.alpha = scrollOffsetY/100;
}

#pragma mark - 计算每个cell所需高度
- (CGFloat)calculateCellHeight:(NSIndexPath *)indexPath
{
    Records *model = self.datasArray[indexPath.section];
    CGFloat height = 0;
    height += CELL_HEIGHT * model.inspectors.count;
    for (int i=0; i<model.inspectors.count; i++) {
        Inspectors *person = model.inspectors[i];
        for (int i=0; i<person.results.count; i++) {
            height += CELL_HEIGHT;
        }
    }
    return height;
}

#pragma mark - lazy
- (ParametersModel *)queryResultModel
{
    if (!_queryResultModel) {
        _queryResultModel = [[ParametersModel alloc]init];
        _queryResultModel.pageSize = PAGESIZE;
        _queryResultModel.pageNumber = ZERO;
//        _queryResultModel.userUuid = kUser.f_user_uuid;
        NSString *dateString = [[NSDate date] yearMonthDayString];
        NSString *beginDateString = [NSString stringWithFormat:@"%@ 00:00:00",[ToolsManager getTimeby:-7]];
        NSString *endDateString = [NSString stringWithFormat:@"%@ 23:59:59", dateString];
        _queryResultModel.beginDate = beginDateString;
        _queryResultModel.endDate = endDateString;
        InspectQuickLookQuery *conditions = [[InspectQuickLookQuery alloc]init];
        conditions.field = @"beginDate";
        conditions.direction = @"desc";
        _queryResultModel.queryOrders = (NSArray<InspectQuickLookQuery> *)@[conditions];
    }
    return _queryResultModel;
}

- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

- (FilterManager *)filter
{
    if (!_filter) {
        _filter = [[FilterManager alloc] initWithClass:self queryModel:self.queryResultModel];
    }
    return _filter;
}

- (SuspensionView *)headerView
{
    if (!_headerView) {
        _headerView = [SuspensionView initializeView];
    }
    return _headerView;
}


@end
