//
//  PatrolTaskViewController.m
//  patrol
//
//  Created by 曹云霄 on 2017/2/23.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "PatrolTaskViewController.h"
#import "PatrolTaskCollectionViewCell.h"
#import "PatrolTaskCollectionReusableView.h"
#import "PatrolTaskCollectionFooterView.h"
#import "ParametersModel.h"
#import "InspectionResultModel.h"
#import "PatrolTaskCustomModel.h"
#import "PatrolExamViewController.h"
#import "FilterManager.h"


@interface PatrolTaskViewController ()

/**
 *  查询条件
 */
@property (nonatomic,strong) ParametersModel *queryPlanModel;

/**
 数据源array
 */
@property (nonatomic,strong) NSMutableArray *datasArray;

/**
 数据源model
 */
@property (nonatomic,strong) InspectionResultModel *resultModel;

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

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


@end

@implementation PatrolTaskViewController

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

#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.collectionFlowLayout.itemSize = CGSizeMake((ScreenSize.width-30)/2.0, 130);
    self.collectionFlowLayout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
    self.collectionFlowLayout.minimumLineSpacing = 10;
    self.collectionFlowLayout.minimumInteritemSpacing = 10;
    [kNotification addObserver:self selector:@selector(updatePatrolOnline) name:UPDATEPATROLONLINELIST object:nil];
}

#pragma mark -更新VI检查任务列表
- (void)updatePatrolOnline
{
    self.pullPageIndex = ZERO;
    [self loadWebDataSource];
}

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

#pragma mark -筛选VI检查任务
- (void)chooseButtonClickAction
{
    self.filter.filterViewModel = self.filterViewModel;
    @weakify(self);
    self.filter.completedBlock = ^(id returnValue) {
        @strongify(self);
        FilterViewModel *model = returnValue;
        self.filterViewModel = model;
        self.queryPlanModel = (ParametersModel *)model.useQueryModel;
        [self.collectionView.mj_header beginRefreshing];
    };
    [self pushViewController:self.filter.filterListVc animated:YES];
}

#pragma mark -获取数据
- (void)loadWebDataSource
{
    self.queryPlanModel.pageNumber = self.pullPageIndex;
    [RequestManager request_PatrolPlan:self.queryPlanModel success:^(id returnValue) {
        [IBTLoadingView hideHUDWithText:nil];
        if ([BaseViewModel verifyData:returnValue]) {
            InspectionResultModel *resultModel = [[InspectionResultModel alloc]initWithDictionary:[BaseViewModel formatData:returnValue] error:nil];
            self.resultModel = resultModel;
            [self analysisDatas];
            if (self.pullPageIndex >= resultModel.paging.pageCount - ONE) {
                [self endRefresh:EndRefreshNotData];
            }else {
                [self endRefresh:EndRefreshDefault];
            }
            return;
        }
        [IBTLoadingView showTextOnly:[BaseViewModel messageData:returnValue]];
    } failure:^(id errorValue) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTextOnly:errorValue];
        [self endRefresh:EndRefreshDefault];
        [self.collectionView reloadData];
    }];
    [IBTLoadingView showProgressLabel:@"加载中"];
}

#pragma mark -解析数据
- (void)analysisDatas
{
    if (self.pullPageIndex == ZERO) {
        [self.datasArray removeAllObjects];
    }
    for (Records *result in self.resultModel.records) {
        NSMutableArray *array = [NSMutableArray array];
        PatrolTaskCustomModel *customModel = [[PatrolTaskCustomModel alloc] initWithDictionary:[result toDictionary] error:nil];
        for (Inspectors *object in result.inspectors) {
            for (Results *store in object.results) {
                [array addObject:store];
            }
            customModel.results = (NSArray<Results> *)array;
        }
        [self.datasArray addObject:customModel];
    }
    [self.collectionView reloadData];
}


#pragma mark -<UICollectionViewDataSource,UICollectionViewDelegate>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    PatrolTaskCustomModel *customModel = self.datasArray[section];
    return customModel.results.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PatrolTaskCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[PatrolTaskCollectionViewCell className] forIndexPath:indexPath];
    PatrolTaskCustomModel *customModel = self.datasArray[indexPath.section];
    [cell refreshCellCustomModel:customModel withStoreModel:[customModel.results yx_objectAtIndex:indexPath.item]];
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.datasArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        PatrolTaskCollectionFooterView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:[PatrolTaskCollectionFooterView className] forIndexPath:indexPath];
        return footerView;
    }
    PatrolTaskCollectionReusableView *sectionHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[PatrolTaskCollectionReusableView className] forIndexPath:indexPath];
    sectionHeaderView.taskModel = self.datasArray[indexPath.section];
    return sectionHeaderView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PatrolTaskCustomModel *customModel = self.datasArray[indexPath.section];
    Results *result = [customModel.results yx_objectAtIndex:indexPath.item];
    PatrolExamViewController *examVC = [PatrolExamViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_PATROLINSPECT];
    PatrolExamViewModel *viewVM = [PatrolExamViewModel new];
    viewVM.storeResult = result;
    viewVM.plan = customModel;
    examVC.viewModel = viewVM;
    [self pushViewController:examVC animated:YES];
}

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

#pragma mark - lazy
- (ParametersModel *)queryPlanModel
{
    if (!_queryPlanModel) {
        _queryPlanModel = [[ParametersModel alloc]init];
        _queryPlanModel.pageSize = PAGESIZE;
        _queryPlanModel.isTemp = self.isTempTask ? @"true" : @"false";
        _queryPlanModel.pageNumber = self.pullPageIndex;
        InspectQuickLookQuery *conditions = [[InspectQuickLookQuery alloc]init];
        conditions.field = @"beginDate";
        conditions.direction = @"desc";
        _queryPlanModel.userUuid = kUser.f_user_uuid;
        _queryPlanModel.optionType = @"inspector";
        _queryPlanModel.queryOrders = (NSArray<InspectQuickLookQuery> *)@[conditions];
    }
    return _queryPlanModel;
}

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

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


@end
