//
//  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,assign) int indexPage;

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

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

/**
 *  当前选中的状态值
 */
@property (nonatomic,copy) NSString *currentState;

@end

@implementation CustomerOrderViewController


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

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

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self uiConfigAction];
   
}


#pragma mark -UI
- (void)uiConfigAction
{
    self.searchCustomerOrder.delegate = self;
    self.view.backgroundColor = kTCColor(238, 238, 238);
    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 = kTCColor(131, 131, 131);
    [self.StyleButton setTitle:@"订单状态" forState:UIControlStateNormal];
    [self.StyleButton addTarget:self action:@selector(OrderStateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.StyleButton setImage:TCImage(@"down_arr") forState:UIControlStateNormal];
    self.StyleButton.layer.masksToBounds = YES;
    self.StyleButton.layer.cornerRadius = 10;
    [self.orderStateBackView addSubview:self.StyleButton];
    
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        
        self.indexPage = 1;
        OrderBill *allOrder = [[OrderBill alloc]init];
        //分页
        DataPage *page = [[DataPage alloc]init];
        page.page = self.indexPage;
        page.rows = 10;
        //订单
        TOOrderEntity *Neworder = [[TOOrderEntity alloc]init];
        Neworder.guideId = [Shoppersmanager manager].Shoppers.employee.fid;
        allOrder.datapage = page;
        allOrder.order = Neworder;
        Neworder.orderState = self.currentState;
        [self.customerOrderTableView.mj_footer resetNoMoreData];
        
        [self getGuideAllcustomerOrder:YES WithorderBill:allOrder];
    }];
    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 (self.indexPage ++ > self.totalPages) {
            [self.customerOrderTableView.mj_footer endRefreshingWithNoMoreData];
        }else
        {
            OrderBill *allOrder = [[OrderBill alloc]init];
            //分页
            DataPage *page = [[DataPage alloc]init];
            page.page = self.indexPage ++;
            page.rows = 10;
            //订单
            TOOrderEntity *Neworder = [[TOOrderEntity alloc]init];
            Neworder.guideId = [Shoppersmanager manager].Shoppers.employee.fid;
            allOrder.datapage = page;
            allOrder.order = Neworder;
            Neworder.orderState = self.currentState;
            [self getGuideAllcustomerOrder:NO WithorderBill:allOrder];
        }
    }];
}


#pragma mark -获取导购下客户订单  ----isdelecte 表示是否清空数组
- (void)getGuideAllcustomerOrder:(BOOL)isdelecte WithorderBill:(OrderBill *)allOrder
{

    [self CreateMBProgressHUDLoding];
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:[NSString stringWithFormat:@"%@%@",ServerAddress,@"/order/query"] WithRequestType:0 WithParameter:allOrder WithReturnValueBlock:^(id returnValue) {
        
        [self RemoveMBProgressHUDLoding];
        [self endRefreshingForTableView:self.customerOrderTableView];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            
            if (isdelecte) {
                [self.datasArray removeAllObjects];
            }
            OrderResponse *Allorder = [[OrderResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            self.totalPages = (int)returnValue[@"data"][@"totalPages"];
            for (OrderBill *model in Allorder.orderBillList) {
                [self.datasArray addObject:model];
            }
            [self.customerOrderTableView reloadData];
        }else
        {
            [self ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        
    } WithFailureBlock:^(id error) {
        
        [self endRefreshingForTableView:self.customerOrderTableView];
        [self RemoveMBProgressHUDLoding];
    }];
}




#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
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
    OrderdetailsViewController *orderdetails = [storyboard instantiateViewControllerWithIdentifier:@"orderdetails"];
    TOOrderEntity *model = [[self.datasArray objectAtIndex_opple:indexPath.row] order];
    orderdetails.orderCode = model.orderNumber;
    orderdetails.sectionTitle = @[@"订单信息",@"客户信息",@"收货信息",@"商品信息",@"附件信息"];
    orderdetails.isShowattachment = YES;
    if ([model.orderState isEqualToString:@"006"]) {
        orderdetails.isShowPrintButton = YES;
        orderdetails.isDelectedButton = NO;
    }
    if ([model.orderState isEqualToString:@"001"]) {
        orderdetails.isShowPayButton = YES;
        orderdetails.isDelectedButton = YES;
        orderdetails.isShowPrintButton = YES;
    }
    [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];
    
    self.indexPage = 1;
    OrderBill *allOrder = [[OrderBill alloc]init];
    //分页
    DataPage *page = [[DataPage alloc]init];
    page.page = self.indexPage;
    page.rows = KROWS;
    //订单
    TOOrderEntity *Neworder = [[TOOrderEntity alloc]init];
    Neworder.guideId = [Shoppersmanager manager].Shoppers.employee.fid;
    allOrder.datapage = page;
    allOrder.order = Neworder;
    
    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";
    }
    Neworder.orderState = orderState;
    self.currentState = orderState;
    [self getGuideAllcustomerOrder:YES WithorderBill:allOrder];
}



#pragma mark -Search点击
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    self.indexPage = 1;
    OrderBill *allOrder = [[OrderBill alloc]init];
    //分页
    DataPage *page = [[DataPage alloc]init];
    page.page = self.indexPage;
    page.rows = KROWS;
    //订单
    TOOrderEntity *Neworder = [[TOOrderEntity alloc]init];
    Neworder.guideId = [Shoppersmanager manager].Shoppers.employee.fid;
    allOrder.datapage = page;
    allOrder.order = Neworder;
    //客户搜索
    TOConsumerEntity *customer = [[TOConsumerEntity alloc]init];
    customer.name = textField.text;
    customer.mobile = textField.text;
    allOrder.consumer = customer;
    [self getGuideAllcustomerOrder:YES WithorderBill:allOrder];
    return YES;
}



#pragma mark -撤销订单
- (void)undoOrderButtonClick:(NSInteger)cellindex
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请确认是否撤销订单" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf CreateMBProgressHUDLoding];
        OrderBill *model = [weakSelf.datasArray objectAtIndex_opple:cellindex];
        [[NetworkRequestClassManager Manager] NetworkWithDictionaryRequestWithURL:[NSString stringWithFormat:@"%@%@%@/%@/%@",ServerAddress,@"/order/updateOrderState/",model.order.orderNumber,model.order.orderState,@"005"] WithRequestType:1 WithParameter:nil WithReturnValueBlock:^(id returnValue) {
            
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            [weakSelf RemoveMBProgressHUDLoding];
            if ([returnValue[@"code"] isEqualToNumber:@0]) {
                
                [weakSelf SuccessMBProgressView:@"撤销成功"];
                model.order.orderState = @"005";
                NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
                [weakSelf.customerOrderTableView reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationLeft];
            }
            else
            {
                [weakSelf ErrorMBProgressView:returnValue[@"message"]];
            }
            
        } WithErrorCodeBlock:^(id errorCodeValue) {
            
        } WithFailureBlock:^(id error) {
            
            [weakSelf RemoveMBProgressHUDLoding];
        }];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}



#pragma mark -去支付
- (void)TopayButtonClick:(NSInteger)cellindex
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
    OrderdetailsViewController *orderdetails = [storyboard instantiateViewControllerWithIdentifier:@"orderdetails"];
    TOOrderEntity *model = [[self.datasArray objectAtIndex_opple:cellindex] order];
    orderdetails.orderCode = model.orderNumber;
    orderdetails.sectionTitle = @[@"订单信息",@"客户信息",@"收货信息",@"商品信息",@"附件信息"];
    orderdetails.isShowattachment = YES;
    if ([model.orderState isEqualToString:@"006"]) {
        orderdetails.isShowPrintButton = YES;
        orderdetails.isDelectedButton = NO;
    }
    if ([model.orderState isEqualToString:@"001"]) {
        orderdetails.isShowPayButton = YES;
        orderdetails.isDelectedButton = YES;
        orderdetails.isShowPrintButton = YES;
    }
    
    //撤销、支付回调
    [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];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
