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

#import "ClientdetailsViewController.h"
#import "ClientDetailsTableViewCell.h"
#import "OrderTableViewCell.h"
#import "OrderdetailsViewController.h"
#import "ShopcarModel.h"
#import "ProductDetailsViewController.h"

@interface ClientdetailsViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 *  客户详情
 */
@property (weak, nonatomic) IBOutlet UITableView *ClientdetailsTableview;

/**
 *  购物车数据源
 */
@property (nonatomic,strong) NSMutableArray *shopResponseArray;

/**
 *  订单记录数据
 */
@property (nonatomic,strong) NSMutableArray *orderRecordArray;

/**
 *  购物袋当前页数
 */
@property (nonatomic,assign) int shoppingBagPage;

/**
 *  购物袋总页数
 */
@property (nonatomic,assign) int shoppingBagTotalPage;

/**
 *  订单记录当前页数
 */
@property (nonatomic,assign) int orderRecordPage;

/**
 *  订单记录总页数
 */
@property (nonatomic,assign) int orderRecordTotalPage;
@end

@implementation ClientdetailsViewController


/**
 *  购物袋数据源
 */
- (NSMutableArray *)shopResponseArray
{
    if (_shopResponseArray == nil) {
        
        _shopResponseArray = [NSMutableArray array];
    }
    return _shopResponseArray;
}


/**
 *  订单记录数据源
 */
- (NSMutableArray *)orderRecordArray
{
    if (_orderRecordArray == nil) {
        
        _orderRecordArray = [NSMutableArray array];
    }
    return _orderRecordArray;
}



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


#pragma mark -UI
- (void)uiConfigAction
{
    
    self.ClientdetailsTableview.delegate = self;
    self.ClientdetailsTableview.dataSource = self;
    self.ClientdetailsTableview.tableFooterView = [UIView new];
    
    //圆角
    self.shoppingAndRecordBackview.layer.masksToBounds = YES;
    self.shoppingAndRecordBackview.layer.cornerRadius = kCornerRadius;
    self.shoppingBagButton.layer.masksToBounds = YES;
    self.shoppingBagButton.layer.cornerRadius = kCornerRadius;
    self.orderRecordButton.layer.masksToBounds = YES;
    self.orderRecordButton.layer.cornerRadius = kCornerRadius;
    self.setupButton.layer.masksToBounds = YES;
    self.setupButton.layer.cornerRadius = kCornerRadius;
    
    //默认选中购物袋
    self.shoppingBagButton.selected = YES;
    self.shoppingBagButton.backgroundColor = [UIColor whiteColor];
    
    //赋值
    [self.customerHeader sd_setImageWithURL:[NSURL URLWithString:self.model.picture] placeholderImage:ReplaceImage];
    self.customerName.text = self.model.name;
    self.customerPhoneNumber.text = self.model.mobile;
    self.companyName.text = self.model.company;
    self.customerLocation.text = self.model.address;
    self.setupButton.selected = self.model.selectedState;
    [self.setupButton setTitle:self.model.selectedState?@"退出当前客户":@"设为当前客户" forState:UIControlStateNormal];
}


#pragma mark -获取数据
- (void)GetdatasAciton
{
    //下拉刷新
    MjRefreshHeaderCustom *headerRefresh = [MjRefreshHeaderCustom headerWithRefreshingBlock:^{
        //购物袋
        if (self.shoppingBagButton.selected) {
            self.shoppingBagPage = 1;
            ShopCartFilter *shopcarNumber = [[ShopCartFilter alloc]init];
            shopcarNumber.consumerId = _model.fid;
            DataPage *Newpage = [[DataPage alloc]init];
            Newpage.page = self.shoppingBagPage;
            Newpage.rows = KROWS;
            shopcarNumber.dp = Newpage;
            [self.ClientdetailsTableview.mj_footer resetNoMoreData];
            [self getShoppingCardata:shopcarNumber isRemove:YES];
        }
        else if (self.orderRecordButton.selected)//订单记录
        {
            self.orderRecordPage = 1;
            OrderFilter *allOrder = [[OrderFilter alloc]init];
            //分页
            DataPage *page = [[DataPage alloc]init];
            page.page = self.orderRecordPage;
            page.rows = KROWS;
            allOrder.dp = page;
            allOrder.consumerIdEquals = _model.fid;
            [self getGuideAllcustomerOrder:allOrder isRemove:YES];
        }
    }];
    headerRefresh.stateLabel.hidden = YES;
    headerRefresh.lastUpdatedTimeLabel.hidden = YES;
    self.ClientdetailsTableview.mj_header =headerRefresh;
    //进入刷新状态
    [self.ClientdetailsTableview.mj_header beginRefreshing];
    //上拉加载
    self.ClientdetailsTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self.ClientdetailsTableview.mj_footer resetNoMoreData];
        //购物袋
        if (self.shoppingBagButton.selected) {
            if (++ self.shoppingBagPage > self.shoppingBagTotalPage) {
                [self.ClientdetailsTableview.mj_footer endRefreshingWithNoMoreData];
            }else
            {
                ShopCartFilter *shopcarNumber = [[ShopCartFilter alloc]init];
                shopcarNumber.consumerId = _model.fid;
                DataPage *Newpage = [[DataPage alloc]init];
                Newpage.page = self.shoppingBagPage;
                Newpage.rows = KROWS;
                shopcarNumber.dp = Newpage;
                [self getShoppingCardata:shopcarNumber isRemove:NO];
            }
        }
        else if (self.orderRecordButton.selected)//订单记录
        {
            if (++ self.orderRecordPage > self.orderRecordTotalPage) {
                [self.ClientdetailsTableview.mj_footer endRefreshingWithNoMoreData];
            }else
            {
                OrderFilter *allOrder = [[OrderFilter alloc]init];
                //分页
                DataPage *page = [[DataPage alloc]init];
                page.page = self.orderRecordPage;
                page.rows = KROWS;
                allOrder.dp = page;
                allOrder.consumerIdEquals = _model.fid;
                [self getGuideAllcustomerOrder:allOrder isRemove:NO];
            }
        }
    }];
    self.ClientdetailsTableview.mj_footer.automaticallyHidden = YES;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.shoppingBagButton.selected) {
        
        ClientDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ClientDetails" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = [self.shopResponseArray objectAtIndex_opple:indexPath.row];
        return cell;
        
    }else if (self.orderRecordButton.selected)
    {
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ordercell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = [self.orderRecordArray objectAtIndex_opple:indexPath.row];
        return  cell;
    }
    return  nil;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.shoppingBagButton.selected) {
        
        return self.shopResponseArray.count;
    }
    if (self.orderRecordButton.selected) {
        
        return self.orderRecordArray.count;
    }
    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.shoppingBagButton.selected) {
        
        return 100;
    }
    else if (self.orderRecordButton.selected)
    {
        return 200;
    }
    return 0;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.shoppingBagButton.selected) {
        
        ProductDetailsViewController *productDetails = [[self getStoryboardWithName] instantiateViewControllerWithIdentifier:@"productdetails"];
        ShopcarModel *model = [self.shopResponseArray objectAtIndex_opple:indexPath.row];
        productDetails.goodsID = model.goods.fid;
        [self.navigationController pushViewController:productDetails animated:YES];
        
    }else if (self.orderRecordButton.selected)
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardwithCYX" bundle:nil];
        OrderdetailsViewController *orderdetails = [storyboard instantiateViewControllerWithIdentifier:@"orderdetails"];
        TOOrderEntity *model = (TOOrderEntity *)[[self.orderRecordArray objectAtIndex_opple:indexPath.row] order];
        orderdetails.orderCode = model.orderNumber;
        orderdetails.sectionTitle = @[@"订单信息",@"客户信息",@"收货信息",@"商品信息",@"附件信息"];
        orderdetails.isShowattachment = YES;
        if ([model.orderState isEqualToString:@"006"] || [model.orderState isEqualToString:@"002"] || [model.orderState isEqualToString:@"003"]) {
            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.orderRecordArray objectAtIndex_opple:cellindex];
            model.order.orderState = orderSate;
            NSIndexPath *indexapath = [NSIndexPath indexPathForRow:cellindex inSection:0];
            [self.ClientdetailsTableview reloadRowsAtIndexPaths:@[indexapath] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [self.navigationController pushViewController:orderdetails animated:YES];
    }
}



#pragma mark -获取购物车商品
- (void)getShoppingCardata:(ShopCartFilter *)shopCar isRemove:(BOOL)remove
{
    [self CreateMBProgressHUDLoding];
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(SHOPPINGBAG) WithRequestType:0 WithParameter:shopCar WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf endRefreshingForTableView:weakSelf.ClientdetailsTableview];
        [weakSelf RemoveMBProgressHUDLoding];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (remove) {
                [weakSelf.shopResponseArray removeAllObjects];
            }
            ShopCartResponse *shopcar = [[ShopCartResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.shoppingBagTotalPage = [returnValue[@"data"][@"totalpages"] intValue];
            if (shopcar.shopcart.count == 0) {
                [weakSelf PromptinformationViewWithimage:TCImage(@"ablum-副本") withTitle:@"暂无购物袋信息~" withpoint:CGPointMake(ScreenHeight/2, ScreenWidth/2)];
                [weakSelf endRefreshingForTableView:weakSelf.ClientdetailsTableview];
            }
            //自定义属性
            for (TOShopcartEntity *objc in shopcar.shopcart) {
                
                ShopcarModel *model = [[ShopcarModel alloc]init];
                model.goods = objc.goods;
                model.fid = objc.fid;
                model.createName = objc.createName;
                model.createBy = objc.createBy;
                model.createDate = objc.createDate;
                model.updateName = objc.updateName;
                model.updateBy = objc.updateBy;
                model.updateDate = objc.updateDate;
                model.goodsId = objc.goodsId;
                model.goodsNum = objc.goodsNum;
                model.consumerId = objc.consumerId;
                
                [weakSelf.shopResponseArray addObject:model];
            }
            [weakSelf.ClientdetailsTableview reloadData];
            
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:@"无网络"];
    } WithFailureBlock:^(id error) {
        
        [weakSelf RemoveMBProgressHUDLoding];
    }];
}



#pragma mark -获取客户订单数据
- (void)getGuideAllcustomerOrder:(OrderFilter *)allOrder isRemove:(BOOL)remove
{
    [self CreateMBProgressHUDLoding];
    WS(weakSelf);
    [[NetworkRequestClassManager Manager] NetworkRequestWithURL:SERVERREQUESTURL(QUERYORDER) WithRequestType:0 WithParameter:allOrder WithReturnValueBlock:^(id returnValue) {
        
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf endRefreshingForTableView:weakSelf.ClientdetailsTableview];
        if ([returnValue[@"code"] isEqualToNumber:@0]) {
            if (remove) {
                [weakSelf.orderRecordArray removeAllObjects];
            }
            OrderResponse *Allorder = [[OrderResponse alloc]initWithDictionary:returnValue[@"data"] error:nil];
            weakSelf.orderRecordTotalPage = [returnValue[@"data"][@"totalpages"] intValue];
            if (Allorder.orderBillList.count == 0) {
                [weakSelf PromptinformationViewWithimage:TCImage(@"changjingtubiao") withTitle:@"暂无订单信息~" withpoint:CGPointMake(ScreenHeight/2, ScreenWidth/2)];
                [weakSelf RemoveMBProgressHUDLoding];
                [weakSelf endRefreshingForTableView:weakSelf.ClientdetailsTableview];
            }
            for (OrderBill *model in Allorder.orderBillList) {
                [weakSelf.orderRecordArray addObject:model];
            }
            [weakSelf.ClientdetailsTableview reloadData];
        }else
        {
            [weakSelf ErrorMBProgressView:returnValue[@"message"]];
        }
        
    } WithErrorCodeBlock:^(id errorCodeValue) {
        [weakSelf RemoveMBProgressHUDLoding];
        [weakSelf ErrorMBProgressView:@"无网络"];
    } WithFailureBlock:^(id error) {
        
        [weakSelf RemoveMBProgressHUDLoding];
    }];
}



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


#pragma mark -设为当前的客户
- (IBAction)SetupcurrentUserButtonClick:(UIButton *)sender {
   
    
    if (self.CurrentUserBlock) {
        self.CurrentUserBlock(_cellindex,sender.currentTitle);
    }
     [sender setTitle:sender.selected?@"设为当前客户":@"退出当前客户" forState:UIControlStateNormal];
     sender.selected = !sender.selected;

}


#pragma mark -购物袋
- (IBAction)ShoppingbagButtonClick:(UIButton *)sender {
    
    
    sender.backgroundColor = [UIColor whiteColor];
    sender.selected = YES;
    self.orderRecordButton.selected = NO;
    self.orderRecordButton.backgroundColor = kMainBlueColor;

    [self RemovePromptinformationView];
    [self.ClientdetailsTableview.mj_header beginRefreshing];
}

#pragma mark -订单记录
- (IBAction)OrderrecordButtonClick:(UIButton *)sender {
    
    
    sender.backgroundColor = [UIColor whiteColor];
    sender.selected = YES;
    self.shoppingBagButton.selected = NO;
    self.shoppingBagButton.backgroundColor = kMainBlueColor;

    [self RemovePromptinformationView];
    [self.ClientdetailsTableview.mj_header beginRefreshing];
}


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