//
//  ReadPacketViewController.m
//  Lighting
//
//  Created by 曹云霄 on 2017/3/17.
//  Copyright © 2017年 上海勾芒科技有限公司. All rights reserved.
//

#import "ReadPacketViewController.h"
#import "ReadPacketCollectionViewCell.h"
#import "CardOrderInformationReusableView.h"
#import "DeviceDirectionManager.h"

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

/**
 查询红包
 */
@property (nonatomic,strong) RsRedPackageConditions *queryReadPacket;

/**
 红包数据
 */
@property (nonatomic,strong) RedPackageResponse *readPacketResult;

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

/**
 选中订单号
 */
@property (nonatomic,strong) NSString *orderNumber;


@end

@implementation ReadPacketViewController


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

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

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

#pragma mark - 获取红包信息
- (void)getReadPacketAction:(BOOL)isRemove
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkRequestWithURL:SERVERREQUESTURL(QUERY_REDPACKAGE)  withRequestType:ZERO withParameter:self.queryReadPacket withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        weakSelf.readPacketCollectionView.emptyDataSetSource = weakSelf;
        weakSelf.readPacketCollectionView.emptyDataSetDelegate = weakSelf;
        [weakSelf endRefreshingForTableView:weakSelf.readPacketCollectionView];
        if (RESULT(returnValue)) {
            if (isRemove) {
                [weakSelf.readPacketArray removeAllObjects];
            }
            weakSelf.readPacketResult = [[RedPackageResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            [weakSelf.readPacketArray addObjectsFromArray:[NSMutableArray arrayWithArray:weakSelf.readPacketResult.list]];
            [weakSelf.readPacketCollectionView reloadData];
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefreshingForTableView:weakSelf.readPacketCollectionView];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - UICollectionView
- (void)setupCollectionView
{
    CGFloat width = (ScreenWidth-6*20)/5.0;
    self.readPacketFlowLayout.itemSize = CGSizeMake(width, width*0.6+width);
    self.readPacketFlowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    self.readPacketFlowLayout.minimumLineSpacing = 20;
    self.readPacketFlowLayout.minimumInteritemSpacing = 20;
    [self.readPacketCollectionView registerNib:[UINib nibWithNibName:@"CardOrderInformationReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CardOrderInformationReusableView"];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ReadPacketCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReadPacketCollectionViewCell" forIndexPath:indexPath];
    RedPackageGroupbyOrderNumber *order = self.readPacketArray[indexPath.section];
    cell.readPacket = order.draws[indexPath.item];
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    RedPackageGroupbyOrderNumber *order = self.readPacketArray[section];
    return order.draws.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    CardOrderInformationReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CardOrderInformationReusableView" forIndexPath:indexPath];
    headerView.stateString = self.readPacketState;
    [headerView refreshHeaderView:self withEntity:self.readPacketArray[indexPath.section] withSectionIndex:indexPath.section];
    return headerView;
}

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

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


#pragma mark - <UploadReceiptsDelegate>
- (void)startUploadReceipts:(NSInteger)sectionIndex
{
    WS(weakSelf);
    self.orderNumber = [self.readPacketArray[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;
            [XBLoadingView showHUDViewWithText:@"相机无法使用"];
        }
    }]];
    [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;
            [XBLoadingView showHUDViewWithText:@"相册无法打开"];
        }
    }]];
    [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [DeviceDirectionManager instance].isHorizontal=NO;
        [alertView dismissViewControllerAnimated:YES completion:nil];
    }]];
    [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);
    XBLoadingView *progressView = [XBLoadingView showHUDViewProgressLabel:@"上传小票中"];
    [HTTP uploadImageWithURL:SERVERREQUESTURL(UPLOADHEADER) withRequestType:ONE withImageDatas:data withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        if (RESULT(returnValue)) {
            [weakSelf activationReadPacket:RESPONSE(returnValue)];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withprogressBlock:^(double progress) {
        if (progress >= 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                progressView.labelText = @"上传小票成功";
                [progressView hide:YES];
            });
            
        }else {
            progressView.progress = progress;
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#pragma mark - 激活红包
- (void)activationReadPacket:(NSString *)imagePath
{
    WS(weakSelf);
    [XBLoadingView showHUDViewWithDefault];
    [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:SERVERREQUESTURL(READPACKETPATH),self.orderNumber,imagePath]  withRequestType:POST withParameter:nil withReturnValueBlock:^(id returnValue) {
        
        [XBLoadingView hideHUDViewWithDefault];
        if (RESULT(returnValue)) {
            [XBLoadingView showHUDViewWithSuccessText:@"激活成功" completeBlock:^{
                [weakSelf.readPacketCollectionView.mj_header beginRefreshing];
            }];
            
        }else{
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    } withFailureBlock:^(NSError *error) {
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}


#pragma mark -友好界面
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无数据" attributes:nil];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return kNoDataImage;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return 64;
}


#pragma mark -lazy
- (RsRedPackageConditions *)queryReadPacket
{
    if (!_queryReadPacket) {
        _queryReadPacket = [[RsRedPackageConditions alloc] init];
        _queryReadPacket.stateEquals = self.readPacketState;
        _queryReadPacket.guideIdEquals = [Shoppersmanager manager].shoppers.employee.fid;
        DataPage *page = [[DataPage alloc] init];
        page.page = ZERO;
        page.rows = KROWS;
        _queryReadPacket.page = page;
    }
    return _queryReadPacket;
}


- (NSMutableArray *)readPacketArray
{
    if (!_readPacketArray) {
        _readPacketArray = [NSMutableArray array];
    }
    return _readPacketArray;
}

@end
