//
//  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>

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

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


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

#pragma mark -UI
- (void)uiConfigAction
{
    self.searchCustomerOrder.delegate = self;
    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 addCorner:10];
    [self.orderStateBackView addSubview:self.styleButton];
}

#pragma mark -加载数据
- (void)loadWebDataSource
{
    WS(weakSelf);
    if (self.pullPageIndex == ONE) {
        [self.datasArray removeAllObjects];
    }
    self.model.dp.page = self.pullPageIndex;
    [self getGuideAllcustomerOrder:self.model completed:^(OrderResponse *result) {
        if (weakSelf.pullPageIndex >= result.totalpages) {
            [weakSelf endRefresh:EndRefreshNotData];
        }else {
            [weakSelf endRefresh:EndRefreshDefault];
        }
    }];
}


#pragma mark -获取导购下客户订单
- (void)getGuideAllcustomerOrder:(OrderFilter *)allOrder completed:(void(^)(OrderResponse *result))completed
{
    WS(weakSelf);
    [HTTP networkRequestWithURL:SERVERREQUESTURL(QUERYORDER)  withRequestType:ZERO withParameter:allOrder withReturnValueBlock:^(id returnValue) {
        if (RESULT(returnValue)) {
            OrderResponse *allorder = [[OrderResponse alloc]initWithDictionary:RESPONSE(returnValue) error:nil];
            completed(allorder);
            for (OrderBill *model in allorder.orderBillList) {
                [weakSelf.datasArray addObject:model];
            }
            [weakSelf.tableView reloadData];
        }else
        {
            [XBLoadingView showHUDViewWithText:MESSAGE(returnValue)];
        }
    }withFailureBlock:^(NSError *error) {
        [weakSelf endRefresh:EndRefreshDefault];
        [XBLoadingView showHUDViewWithText:error.localizedDescription];
    }];
}

#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 = [OrderdetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    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;
    }
    //撤销、支付回调
    WS(weakSelf);
    [orderdetails setDelecteAndPayButtonBlock:^(NSInteger cellindex, NSString *orderSate) {
        OrderBill *model = [self.datasArray objectAtIndex_opple:cellindex];
        model.order.orderState = orderSate;
        NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self 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 = @"001";
    }
    //已支付
   else if ([title isEqualToString:@"已支付"]) {
        orderState = @"002";
    }
    //已发货
   else  if ([title isEqualToString:@"已发货"]) {
        orderState = @"003";
    }
    //已完成
   else if ([title isEqualToString:@"已完成"]) {
        orderState = @"006";
    }
    //已撤销
   else if ([title isEqualToString:@"已撤销"]) {
        orderState = @"005";
    }
    //已退货
   else if ([title isEqualToString:@"已退货"]) {
        orderState = @"004";
    }
    self.model.consumerNameOrMobileEquals = nil;
    self.model.orderStateEquals = orderState;
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark -Search点击
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.model.consumerNameOrMobileEquals = textField.text;
    self.model.orderStateEquals = nil;
    [self.tableView.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,@"005"]  withRequestType:ONE withParameter:nil withReturnValueBlock:^(id returnValue) {
            
            [XBLoadingView hideHUDViewWithDefault];
            if (RESULT(returnValue)) {
                [XBLoadingView showHUDViewWithSuccessText:@"撤销成功" completeBlock:nil];
                model.order.orderState = @"005";
                NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
                [weakSelf.tableView 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 = [OrderdetailsViewController viewControllerWithStoryBoardType:STORYBOARD_TYPE_MAIN];
    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.tableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationNone];
        
    }];
    [self pushViewController:orderdetails animated:YES];
}



@end
