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

#import "CustomerOrderViewController.h"
#import "CustomerOrderTableViewCell.h"
#import "OrderdetailsViewController.h"
@interface CustomerOrderViewController ()<UITableViewDataSource,UITableViewDelegate,ReturnTableviewcellIndexpathdelegate,UITextFieldDelegate,undoOrderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

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

/**
 *  订单状态数组
 */
@property (nonatomic,strong) NSArray *orderStateArray;

/**
 *  总页数
 */
@property (nonatomic,assign) int totalPages;



@end

@implementation CustomerOrderViewController


/**
 *  初始化数据源数组
 */
- (NSMutableArray *)datasArray
{
    if (_datasArray == nil) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}

/**
 *  订单状态数组
 */
- (NSArray *)orderStateArray
{
    if (_orderStateArray == nil) {
        _orderStateArray = [NSArray arrayWithObjects:@"全部订单",@"待支付",@"已支付",@"已发货",@"已完成",@"已撤销",@"已退货", nil];
    }
    return _orderStateArray;
}

- (OrderFilter *)model
{
    if (!_model) {
        _model = [[OrderFilter alloc]init];
        DataPage *page = [[DataPage alloc]init];
        page.page = ONE;
        page.rows = KROWS;
        _model.dp = page;
        //经销商代码
        _model.resellerCodeEquals = [[Shoppersmanager manager].shoppers.employee.currentDepart  orgCode];
    }
    return _model;
}

#pragma mark -渲染完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

#pragma mark -视图即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

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

#pragma mark -UI
- (void)uiConfigAction
{
    self.searchCustomerOrder.delegate = self;
    self.view.backgroundColor = RGB(238, 238, 238,1);
    self.customerOrderTableView.dataSource = self;
    self.customerOrderTableView.delegate = self;
    self.customerOrderTableView.backgroundColor = [UIColor clearColor];
    self.styleButton = [ScreeningButton buttonWithType:UIButtonTypeCustom];
    self.styleButton.frame = CGRectMake(ScreenWidth-250, 20, 150, 30);
    self.styleButton.backgroundColor = RGB(131, 131, 131,1);
    [self.styleButton setTitle:@"订单状态" forState:UIControlStateNormal];
    [self.styleButton addTarget:self action:@selector(OrderStateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.styleButton setImage:TCImage(@"down_arr") forState:UIControlStateNormal];
    [self.styleButton setMyCorner:10];
    [self.orderStateBackView addSubview:self.styleButton];
}

#pragma mark -设置刷新
- (void)setUpRefresh
{
    //下拉刷新
    WS(weakSelf);
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        
        [weakSelf.customerOrderTableView.mj_footer resetNoMoreData];
        weakSelf.model.dp.page = ONE;
        [weakSelf getGuideAllcustomerOrder:YES withOrderBill:weakSelf.model];
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.customerOrderTableView.mj_header = headerRefresh;
    [self.customerOrderTableView.mj_header beginRefreshing];
    //上拉加载
    self.customerOrderTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if ( ++ weakSelf.model.dp.page > weakSelf.totalPages) {
            [weakSelf.customerOrderTableView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            [weakSelf getGuideAllcustomerOrder:NO withOrderBill:weakSelf.model];
        }
    }];
    self.customerOrderTableView.mj_footer.automaticallyHidden = YES;
}


#pragma mark -获取导购下客户订单  ----isdelecte 表示是否清空数组
- (void)getGuideAllcustomerOrder:(BOOL)isdelecte withOrderBill:(OrderFilter *)allOrder
{
    [XBLoadingView showHUDViewWithDefault];
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(QUERYORDER)  withRequestType:ZERO withParameter:allOrder withReturnValueBlock:^(id returnValue) {
        
        weakSelf.customerOrderTableView.emptyDataSetSource = weakSelf;
        weakSelf.customerOrderTableView.emptyDataSetDelegate = weakSelf;
        [XBLoadingView hideHUDViewWithDefault];
        [weakSelf endRefreshingForTableView:weakSelf.customerOrderTableView];
        if (RESULT(returnValue)) {
            if (isdelecte) {
                [weakSelf.datasArray removeAllObjects];
            }
            OrderResponse *Allorder = [[OrderResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            weakSelf.totalPages = [RESPONSE(returnValue)[@"totalpages"] intValue];
            for (OrderBill *model in Allorder.orderBillList) {
                [weakSelf.datasArray addObject:model];
            }
            [weakSelf.customerOrderTableView reloadData];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(id error) {
        [weakSelf endRefreshingForTableView:weakSelf.customerOrderTableView];
        [XBLoadingView hideHUDViewWithDefault];
    }];
}

#pragma mark -订单状态筛选
- (void)OrderStateButtonClick:(UIButton *)button
{
    [self showPopoverViewController:CGSizeMake(200, 400) withDatas:self.orderStateArray showButton:button selectedIndex:0];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomerOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"customerordercell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.cellBackView.layer.masksToBounds = YES;
    cell.model = [self.datasArray objectAtIndex_opple:indexPath.row];
    cell.cellBackView.layer.cornerRadius = kCornerRadius;
    cell.backgroundColor = [UIColor clearColor];
    cell.cellIndex = indexPath.row;
    cell.delegate = self;
    return cell;
}

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 260;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderdetailsViewController *orderdetails = [[[self class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"orderdetails"];
    TOOrderEntity *model = (TOOrderEntity *)[[self.datasArray objectAtIndex_opple:indexPath.row] order];
    orderdetails.orderCode = model.orderNumber;
    orderdetails.consumerID = model.consumerId;
    if ([model.orderState isEqualToString:COMPLETED] || [model.orderState isEqualToString:PAID] || [model.orderState isEqualToString:SHIPPED]) {
        orderdetails.isShowShareButton = YES;
        orderdetails.isShowPayButton = NO;
        orderdetails.isShowHeaderView = YES;
        orderdetails.isUserInteractionEnabled = NO;
        
    } else if ([model.orderState isEqualToString:UNPAID]) {//未付款
        orderdetails.isShowPayButton = YES;
        orderdetails.isShowShareButton = YES;
        orderdetails.isShowHeaderView = YES;
        orderdetails.isUserInteractionEnabled = YES;
        
    }else{
        orderdetails.isShowHeaderView = NO;
    }
    //撤销、支付回调
    [orderdetails setDelecteAndPayButtonBlock:^(NSInteger cellindex, NSString *orderSate) {
        OrderBill *model = [self.datasArray objectAtIndex_opple:cellindex];
        model.order.orderState = orderSate;
        NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
        [self.customerOrderTableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self.navigationController pushViewController:orderdetails animated:YES];
}

#pragma mark -弹出popover视图控制器
- (void)showPopoverViewController:(CGSize)size withDatas:(NSArray *)datasArray showButton:(UIButton *)button selectedIndex:(NSInteger)index
{
    PopoverViewController *popover = [[PopoverViewController alloc]init];
    popover.datasArray = datasArray;
    popover.delegate = self;
    popover.isString = YES;
    popover.selectedindex = index;
    popover.contentSize = size;
    popover.preferredContentSize = size;
    popover.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController *pop = popover.popoverPresentationController;
    pop.permittedArrowDirections = UIPopoverArrowDirectionAny;
    pop.sourceView = popover.view;
    pop.barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [self presentViewController:popover animated:YES completion:nil];
}

#pragma mark -选中代理
/**
 *  选中筛选条件对象typecode
 *
 *  @param index NSString
 */
- (void)returnCellindexpathwithrow:(NSString *)type withCellTitle:(NSString *)title withSelected:(NSInteger)selected
{
    [self.styleButton setTitle:title forState:UIControlStateNormal];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSString *orderState = nil;
    //全部订单
    if ([title isEqualToString:@"全部订单"]) {
        orderState = nil;
    }
    //待支付
    else if ([title isEqualToString:@"待支付"]) {
        orderState = UNPAID;
    }
    //已支付
   else if ([title isEqualToString:@"已支付"]) {
        orderState = PAID;
    }
    //已发货
   else  if ([title isEqualToString:@"已发货"]) {
        orderState = SHIPPED;
    }
    //已完成
   else if ([title isEqualToString:@"已完成"]) {
        orderState = COMPLETED;
    }
    //已撤销
   else if ([title isEqualToString:@"已撤销"]) {
        orderState = CANCELED;
    }
    //已退货
   else if ([title isEqualToString:@"已退货"]) {
        orderState = RETURN;
    }
    self.model.consumerNameOrMobileEquals = nil;
    self.model.orderStateEquals = orderState;
    [self.customerOrderTableView.mj_header beginRefreshing];
}


#pragma mark -Search点击
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.model.consumerNameOrMobileEquals = textField.text;
    self.model.orderStateEquals = nil;
    [self.customerOrderTableView.mj_header beginRefreshing];
    return YES;
}


#pragma mark -撤销订单
- (void)undoOrderButtonClick:(NSInteger)cellindex
{
    WS(weakSelf);
    ShowAlertView(@"提示", @"请确认是否撤销订单", @[@"确认",@"取消"], UIAlertControllerStyleAlert, ^(NSInteger index) {
        if (index == ONE) {
            return;
        }
        [XBLoadingView showHUDViewWithDefault];
        OrderBill *model = [weakSelf.datasArray objectAtIndex_opple:cellindex];
        [HTTP networkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@/%@/%@",SERVERREQUESTURL(RESETORDER),model.order.orderNumber,model.order.orderState,CANCELED]  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
            
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                [XBLoadingView showHUDViewWithSuccessText:@"撤销成功" completeBlock:nil];
                model.order.orderState = CANCELED;
                NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
                [weakSelf.customerOrderTableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationLeft];
            }else{
                [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
            }
        }withFailureBlock:^(NSError *error) {
            [XBLoadingView hideHUDViewWithDefault];
            [XBLoadingView showHUDViewWithText:error.localizedDescription];
        }];
    });
}



#pragma mark -去支付
- (void)TopayButtonClick:(NSInteger)cellindex
{
    OrderdetailsViewController *orderdetails = [[[self class] getMainStoryboardClass] instantiateViewControllerWithIdentifier:@"orderdetails"];
    TOOrderEntity *model = (TOOrderEntity *)[[self.datasArray objectAtIndex_opple:cellindex] order];
    orderdetails.orderCode = model.orderNumber;
    if ([model.orderState isEqualToString:COMPLETED] || [model.orderState isEqualToString:PAID] || [model.orderState isEqualToString:SHIPPED]) {
        orderdetails.isShowShareButton = YES;
        orderdetails.isShowPayButton = NO;
        orderdetails.isShowHeaderView = YES;
        orderdetails.isUserInteractionEnabled = NO;
        
    } else if ([model.orderState isEqualToString:UNPAID]) {//未付款
        orderdetails.isShowPayButton = YES;
        orderdetails.isShowShareButton = YES;
        orderdetails.isShowHeaderView = YES;
        orderdetails.isUserInteractionEnabled = YES;
        
    }else{
        orderdetails.isShowHeaderView = NO;
    }
    //撤销、支付回调
    [orderdetails setDelecteAndPayButtonBlock:^(NSInteger cellindex, NSString *orderSate) {
        
        OrderBill *model = [self.datasArray objectAtIndex_opple:cellindex];
        model.order.orderState = orderSate;
        NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
        [self.customerOrderTableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationNone];
        
    }];
    [self.navigationController pushViewController:orderdetails animated:YES];
}


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

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

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


@end
