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

#import "CardViewController.h"
#import "CardCollectionViewCell.h"
#import "CardDetailsViewController.h"
#import "CardAmplificationViewController.h"
#import "LuckyDrawViewController.h"

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

//** 查询最近10张卡劵 */
@property (nonatomic,strong) RsJingDongECardRequest *requestModel;

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

@end

@implementation CardViewController

#pragma mark - lazy
- (RsJingDongECardRequest *)requestModel
{
    if (!_requestModel) {
        _requestModel = [[RsJingDongECardRequest alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ZERO;
        page.rows = KROWS;
        _requestModel.guideIdEquals = [Shoppersmanager manager].shoppers.employee.fid;
        _requestModel.page = page;
    }
    return _requestModel;
}

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

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getCardDatasAction:YES];
}

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

#pragma mark - 查询卡劵
- (void)getCardDatasAction:(BOOL)isRefresh
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefaultWithView:self.view];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(QUERYALLJDECARD)  withRequestType:ZERO withParameter:self.requestModel withReturnValueBlock:^(id returnValue) {
        
        weakSelf.cardCollectionView.emptyDataSetSource = weakSelf;
        weakSelf.cardCollectionView.emptyDataSetDelegate = weakSelf;
        [weakSelf endRefreshingForTableView:weakSelf.cardCollectionView];
        [XBLoadingView hideHUDViewWithDefaultWithView:weakSelf.view];
        if (RESULT(returnValue)) {
            if (isRefresh) {
                [weakSelf.datasArray removeAllObjects];
            }
            RsSimpleJingDongECardResponse *cardInformation = [[RsSimpleJingDongECardResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            for (TOJingdongEcardEntity *eCard in cardInformation.list) {
                [weakSelf.datasArray addObject:eCard];
            }
            [weakSelf.cardCollectionView reloadData];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
        
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefreshingForTableView:weakSelf.cardCollectionView];
        [XBLoadingView hideHUDViewWithDefaultWithView:weakSelf.view];
    }];
}

#pragma mark - 使用京东卡劵
- (void)useJDECard:(NSString *)JDECardNumber
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefaultWithView:self.view];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(USEJDECARD),JDECardNumber]  withRequestType:ZERO withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefaultWithView:weakSelf.view];
        if (RESULT(returnValue)) {
            [weakSelf deleteUsedJDECard:JDECardNumber];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [XBLoadingView hideHUDViewWithDefaultWithView:weakSelf.view];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

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

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datasArray.count;
}

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WS(weakSelf);
    TOJingdongEcardEntity *model = self.datasArray[indexPath.row];
    if ([[self class] isBlankString:model.orderReceiptUrl]) {
        ShowAlertView(@"提示", @"不能查看未激活卡劵,请先上传小票激活卡劵", @[@"我知道了"], UIAlertControllerStyleAlert, ^(NSInteger index) {
            CardDetailsViewController *cardDetails = [[[weakSelf class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"CardDetailsViewController"];
            [weakSelf.navigationController pushViewController:cardDetails animated:YES];
        });
        
    }else if ([model.state isEqualToString:CHECK]){
        [XBLoadingView showHUDViewWithText:@"审核中"];
    }else{
        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];
        cardVC.cardModel = self.datasArray[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 -友好界面
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无卡劵记录~" attributes:nil];
}

@end
