//
//  CardBeenUseViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2016/10/19.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "CardBeenUseViewController.h"
#import "CardCollectionViewCell.h"
#import "CardOrderInformationReusableView.h"
#import "CardAmplificationViewController.h"

@interface CardBeenUseViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


@property (nonatomic,strong) RsJingDongECardRequest *requestModel;
@property (nonatomic,strong) WYPopoverController *settingsPopoverController;

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

/**
 *  总页数
 */
@property (nonatomic,assign) NSInteger totalPage;
@end

@implementation CardBeenUseViewController

#pragma mark - lazy
- (RsJingDongECardRequest *)requestModel
{
    if (!_requestModel) {
        _requestModel = [[RsJingDongECardRequest alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ZERO;
        page.rows = KROWS;
        page.order = @"desc";
        _requestModel.guideIdEquals = [Shoppersmanager manager].Shoppers.employee.fid;
        _requestModel.stateEquals = self.cardState;
        _requestModel.page = page;
    }
    return _requestModel;
}

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

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.beenUseCardCollectionView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupCollectionView];
    [self setupRefreshAction];
}

#pragma mark - 设置刷新
- (void)setupRefreshAction
{
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        weakSelf.requestModel.page.page = ZERO;
        [weakSelf.beenUseCardCollectionView.mj_footer resetNoMoreData];
        [weakSelf getCardDatasAction:YES];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.beenUseCardCollectionView.mj_header = headerRefresh;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (++ weakSelf.requestModel.page.page > weakSelf.totalPage) {
            [weakSelf.beenUseCardCollectionView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getCardDatasAction:NO];
        }
    }];
    footer.automaticallyHidden = YES;
    self.beenUseCardCollectionView.mj_footer = footer;
}


#pragma mark - 获取卡劵
- (void)getCardDatasAction:(BOOL)isRemove
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(CARDINFORMATION) WithCallClass:weakSelf WithRequestType:ZERO WithParameter:self.requestModel WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        weakSelf.beenUseCardCollectionView.emptyDataSetSource = self;
        weakSelf.beenUseCardCollectionView.emptyDataSetDelegate = self;
        [weakSelf endRefreshingForTableView:weakSelf.beenUseCardCollectionView];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            RsJingDongECardResponse *cardInformation = [[RsJingDongECardResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.totalPage = cardInformation.totalpages;
            if (isRemove) {
                [weakSelf.datasArray removeAllObjects];
            }
            [weakSelf.datasArray addObjectsFromArray:cardInformation.list];
            [weakSelf.beenUseCardCollectionView reloadData];
        }else{
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf endRefreshingForTableView:weakSelf.beenUseCardCollectionView];
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf endRefreshingForTableView:weakSelf.beenUseCardCollectionView];
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}

#pragma mark - 使用京东卡劵
- (void)useJDECard:(NSString *)JDECardNumber
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(USEJDECARD),JDECardNumber] WithCallClass:weakSelf WithRequestType:ZERO WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [weakSelf deleteUsedJDECard:JDECardNumber];
        }else{
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}

#pragma mark - 区分已经使用的E卡
- (void)deleteUsedJDECard:(NSString *)eCardNumber
{
    //@property (nonatomic, strong) NSMutableArray<TOJingdongEcardEntity> *eCards;
    // 手动改为可变数组
    for (int i=0; i<self.datasArray.count; i++) {
        GroupByOrderNumber *order = self.datasArray[i];
        for (int j=0; j<order.eCards.count; j++) {
            TOJingdongEcardEntity *ecard = order.eCards[j];
            if ([eCardNumber isEqualToString:ecard.cardNumber]) {
                ecard.state = USED;
                [self.beenUseCardCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:j inSection:i]]];
            }
        }
    }
}

#pragma mark - UICollectionView
- (void)setupCollectionView
{
    self.beenUseLayout.itemSize = CGSizeMake((ScreenWidth-48-20*4)/3, 200);
    self.beenUseLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    self.beenUseLayout.minimumLineSpacing = 20;
    self.beenUseLayout.minimumInteritemSpacing = 20;
    [self.beenUseCardCollectionView registerNib:[UINib nibWithNibName:@"CardOrderInformationReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CardOrderInformationReusableView"];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CardCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CardCollectionViewCell" forIndexPath:indexPath];
    GroupByOrderNumber *model = self.datasArray[indexPath.section];
    cell.Cardmodel = model.eCards[indexPath.row];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    GroupByOrderNumber *model = self.datasArray[section];
    return model.eCards.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    CardOrderInformationReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CardOrderInformationReusableView" forIndexPath:indexPath];
    headerView.model = self.datasArray[indexPath.section];
    headerView.uploadReceiptsButton.hidden = true;
    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(0, 65);
}

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CardAmplificationViewController *cardVC = [[CardAmplificationViewController alloc]init];
    self.settingsPopoverController = [[WYPopoverController alloc] initWithContentViewController:cardVC];
    self.settingsPopoverController.theme.fillBottomColor = [UIColor clearColor];
    self.settingsPopoverController.theme.fillTopColor = [UIColor clearColor];
    [self.settingsPopoverController presentPopoverAsDialogAnimated:YES
                                                           options:WYPopoverAnimationOptionFadeWithScale];
    [self.settingsPopoverController beginThemeUpdates];
    GroupByOrderNumber *model = self.datasArray[indexPath.section];
    cardVC.cardModel = model.eCards[indexPath.row];
    cardVC.preferredContentSize = CGSizeMake(500, 370);
    [self.settingsPopoverController endThemeUpdates];
    // 更新E卡状态
    WS(weakSelf);
    [cardVC setRefreshJDCardList:^(NSString *cardNumber) {
        [weakSelf.settingsPopoverController dismissPopoverAnimated:YES completion:^{
            [weakSelf useJDECard:cardNumber];
        }];
    }];
}

#pragma mark -友好界面
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

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


@end
