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

#import "LuckyDrawDetailsViewController.h"
#import "NotDrawTableViewCell.h"
#import "CustomWKWebViewController.h"
#import "UsedDrawTableViewCell.h"
#import "LuckDrawResultModel.h"


@interface LuckyDrawDetailsViewController ()<UITableViewDataSource,UITableViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>


@property (nonatomic,strong) RsLotteryRequest *drawModel;

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

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

@end

@implementation LuckyDrawDetailsViewController

#pragma mark - lazy
- (RsLotteryRequest *)drawModel
{
    if (!_drawModel) {
        _drawModel = [[RsLotteryRequest alloc]init];
        _drawModel.winnerIdEquals = [Shoppersmanager manager].Shoppers.employee.fid;
        DataPage *page = [[DataPage alloc]init];
        page.rows = KROWS;
        page.page = ONE;
        page.order = SORTDIRECTION_DESC;
        _drawModel.page = page;
        switch (self.drawValue) {
            case 0:
            {
                _drawModel.stateEquals = nil;
            }
                break;
            case 1:
            {
                _drawModel.stateEquals = INITIAL;
            }
                break;
            case 2:
            {
                _drawModel.stateEquals = ACCOMPLISHED;
            }
                break;
                
            default:
                break;
        }
    }
    return _drawModel;
}

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

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.drawValue) {
        [self.drawDetailsTableView.mj_header beginRefreshing];
    }else {
       [self getDrawDatas:YES];
    }    
}

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

#pragma mark - UI
- (void)uiConfigAction
{
    self.drawDetailsTableView.tableFooterView = [UIView new];
    self.drawDetailsTableView.delegate = self;
    self.drawDetailsTableView.dataSource = self;
}

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

#pragma mark - 抽奖数据
- (void)getDrawDatas:(BOOL)isRemove
{
    WS(weakSelf);
    [self CreateMBProgressHUDLoding];
    NSLog(@"%@",[self.drawModel toDictionary]);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(LOTTERYED) WithCallClass:weakSelf WithRequestType:ZERO WithParameter:self.drawModel WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf endRefreshingForTableView:weakSelf.drawDetailsTableView];
        weakSelf.drawDetailsTableView.emptyDataSetSource = weakSelf;
        weakSelf.drawDetailsTableView.emptyDataSetDelegate = weakSelf;
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (isRemove) {
                [weakSelf.datasArray removeAllObjects];
            }
            RsLotteryResponse *drawRecord = [[RsLotteryResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            [weakSelf.datasArray addObjectsFromArray:drawRecord.list];
            weakSelf.totalPage = [returnValue[@"data"][@"totalpages"] integerValue];
            NSLog(@"%ld",weakSelf.datasArray.count);
            [weakSelf.drawDetailsTableView reloadData];
        }else {
            [weakSelf SHOWPrompttext:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:NETWORK];
    } WithFailureBlock:^(NSError *error) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:error.localizedDescription];
    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RsAwardDraw *drawEntity = self.datasArray[indexPath.row];
    if ([drawEntity.draw.state isEqualToString:@"initial"]) {
        NotDrawTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NotDrawTableViewCell" forIndexPath:indexPath];
        cell.orderNumberLabel.text = drawEntity.draw.orderNumber;
        cell.drawButton.tag = indexPath.row;
        [cell.drawButton addTarget:self action:@selector(drawButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
        if (self.drawValue == 0) {
            cell.orderNumberTitle.font = [UIFont systemFontOfSize:12];
            cell.drawButton.titleLabel.font = [UIFont systemFontOfSize:12];
            cell.orderNumberLabel.font = [UIFont systemFontOfSize:12];
            [cell.drawButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(cell).offset(-20);
                make.size.mas_equalTo(CGSizeMake(50, 20));
                make.centerY.equalTo(cell);
            }];
            [cell.orderNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(cell.orderNumberTitle.mas_right).offset(-10);
                make.centerY.equalTo(cell.orderNumberTitle);
                make.right.equalTo(cell).offset(-100);
            }];
        }
        return cell;
    }
    UsedDrawTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UsedDrawTableViewCell" forIndexPath:indexPath];
    cell.orderNumber.text = drawEntity.draw.orderNumber;
    cell.drawTimeLabel.text = drawEntity.draw.createDate;
    cell.trophyLabel.text = drawEntity.draw.awardDescription;
    if (self.drawValue == 0) {
        cell.drawTimeLabel.hidden = YES;
        cell.drawTimeTitle.hidden = YES;
        cell.orderNumberTitle.font = [UIFont systemFontOfSize:12];
        cell.trophyLabel.font = [UIFont systemFontOfSize:12];
        cell.orderNumber.font = [UIFont systemFontOfSize:12];
        [cell.orderNumber mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(cell.orderNumberTitle.mas_right).offset(-10);
            make.centerY.equalTo(cell.orderNumberTitle);
            make.right.equalTo(cell).offset(-100);
        }];
    }
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasArray.count;
}

#pragma mark - 去抽奖
- (void)drawButtonClickAction:(UIButton *)sender
{
    WS(weakSelf);
    RsAwardDraw *drawEntity = self.datasArray[sender.tag];
    [self showLuckyDrawControl:drawEntity.draw.lotteryId andOrderNumber:drawEntity.draw.orderNumber andDrawid:drawEntity.draw.fid luckyDrawFinish:^(NSDictionary *dict) {
        
        id json = [NSJSONSerialization JSONObjectWithData:[dict[@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        if (json) {
            if ([json isKindOfClass:[NSDictionary class]]) {
                if ([BaseViewController isBlankString:json[@"awardId"]]) {
                    [weakSelf SHOWPrompttext:@"未中奖"];
                }else {
                    [weakSelf SHOWPrompttext:[NSString stringWithFormat:@"恭喜你获得了 %@",json[@"description"]]];
                }
            }
        }
    }];
}

#pragma mark - 抽奖界面
- (void)showLuckyDrawControl:(NSString *)lotteryId andOrderNumber:(NSString *)orderNumber andDrawid:(NSString *)drawid luckyDrawFinish:(void(^)(NSDictionary *dict))complete
{
    CustomWKWebViewController *wkWebView = [[CustomWKWebViewController alloc]init];
    NSString *server = [NSString stringWithFormat:SERVERREQUESTURL(DRAW),lotteryId,drawid,orderNumber];
    NSString *newServer = [server stringByReplacingOccurrencesOfString:@"/app" withString:@""];
    wkWebView.pdfURLString = newServer;
    [wkWebView setLuckyDrawFinishBlock:^(NSDictionary *result) {
        complete(result);
    }];
    [wkWebView setDismissLuckyDrawController:^{
        
    }];
    [self presentViewController:wkWebView animated:YES completion:nil];
}


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

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

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc]initWithString:@"暂无抽奖记录~" attributes:nil];
}

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



@end
