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

#import "CardDontUseViewController.h"
#import "CardCollectionViewCell.h"
#import "CardOrderInformationReusableView.h"
#import "DeviceDirectionManager.h"
#import "CardAmplificationViewController.h"

@interface CardDontUseViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UploadReceiptsDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


@property (nonatomic,strong) RsJingDongECardRequest *requestModel;

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

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

/**
 *  记录上传小票时的订单号
 */
@property (nonatomic,copy) NSString *orderNumber;

@end

@implementation CardDontUseViewController

#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 = DISPENSED;
        _requestModel.page = page;
    }
    return _requestModel;
}

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

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!self.isRefreshValue) {
        [self.dontUseCardCollectionView.mj_header beginRefreshing];
    }
}

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

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

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

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

- (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.delegate = self;
    headerView.model = self.datasArray[indexPath.section];
    headerView.sectionIndex = indexPath.section;
    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
{
    GroupByOrderNumber *model = self.datasArray[indexPath.section];
    if ([[self class] isBlankString:model.orderReceiptUrl]) {
        [self SHOWPrompttext:@"不能查看未激活卡劵,请先上传小票激活卡劵"];
    }
}


#pragma mark - <UploadReceiptsDelegate>
- (void)startUploadReceipts:(NSInteger)sectionIndex
{
    WS(weakSelf);
    self.orderNumber = [self.datasArray[sectionIndex] orderNumber];
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIImagePickerController *PcCamera = [[UIImagePickerController alloc]init];
    PcCamera.delegate = self;
    [DeviceDirectionManager instance].isHorizontal=YES;
    [alertView addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypeCamera];
            PcCamera.allowsEditing = YES;
            [weakSelf presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [DeviceDirectionManager instance].isHorizontal=NO;
            [weakSelf ErrorMBProgressView:@"相机无法使用"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            [PcCamera setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            PcCamera.allowsEditing = YES;
            [weakSelf presentViewController:PcCamera animated:YES completion:nil];
        }
        else
        {
            [DeviceDirectionManager instance].isHorizontal=NO;
            [weakSelf ErrorMBProgressView:@"相册无法打开"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [DeviceDirectionManager instance].isHorizontal=NO;
        [alertView dismissViewControllerAnimated:YES completion:nil];
    }]];
    self.isRefreshValue = YES;
    [self presentViewController:alertView animated:YES completion:nil];
}

#pragma mark -拍照、从相册选择
#pragma -mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [DeviceDirectionManager instance].isHorizontal=NO;
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *Headimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self uploadReceipts:Headimage];
}

#pragma mark -上传小票
- (void)uploadReceipts:(UIImage *)image
{
    WS(weakSelf);
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    [[NetworkRequestClassManager Manager] UploadImageWithURL:SERVERREQUESTURL(UPLOADHEADER) WithRequestType:1 WithImageDatas:data WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            [weakSelf activationJDECard:returnValue[@"data"]];
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
    } WithprogressBlock:^(double progress) {
        [weakSelf ShowProgressView:progress];
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}

#pragma mark - 激活京东E卡
- (void)activationJDECard:(NSString *)imagePath
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(ACTIVIATIONJDECARD),self.orderNumber,imagePath] WithCallClass:weakSelf WithRequestType:ZERO WithParameter:nil WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            weakSelf.isRefreshValue = NO;
            [weakSelf.dontUseCardCollectionView.mj_header beginRefreshing];
            [weakSelf SuccessMBProgressView:@"激活成功"];
            
        }else{
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}

#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];
}



@end
