//
//  KWMOrderVC.m
//  iCemarose
//
//  Created by HouWeiBin on 16/8/30.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMOrderVC.h"
#import "KWMOrderCell.h"
#import "KWMProductDetailVC.h"
#import "KWMImageUtil.h"

@interface KWMOrderVC ()
@property (nonatomic) NSMutableArray<BUYOrder *> *orderList;//订单列表
@property (nonatomic) NSMutableArray *productList;//订单商品列表

@end

@implementation KWMOrderVC{
    NSMutableArray *sectionArr;//标记展开的section
}

+(NSString *)kwmTag{
    return @"KWMOrderVC";
}

-(void)awakeFromNib{
    [super awakeFromNib];
    self.title = @"我的订单";
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.orderList = [NSMutableArray array];
    self.productList = [NSMutableArray array];
    sectionArr = [NSMutableArray array];
    [self requestOrderAPI];
}

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

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return self.orderList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BUYOrder *order = [self.orderList objectAtIndex:section];
    NSArray<BUYLineItem *> *lineItems = [order.lineItems array];
    bool isShowOther = [sectionArr containsObject:[NSString stringWithFormat:@"%ld",(long)section]];
    if(!lineItems){
        return 0;
    }
    if(!isShowOther && lineItems.count >= 4){
        return 4;
    }
    return lineItems.count;
}

//每一个section有多少行
- (NSInteger)returnSectionRow:(NSInteger)section{
    BUYOrder *order = [self.orderList objectAtIndex:section];
    NSArray<BUYLineItem *> *arr = [order.lineItems array];
    return arr?arr.count:0;
}

#pragma  mark UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //总高度200,头部80,底部按钮40
    //如果是尾行
    bool isShowOther = [sectionArr containsObject:[NSString stringWithFormat:@"%ld",(long)indexPath.section]];
    if(indexPath.row == 3 && !isShowOther){
        return 200-80;
    }
    NSInteger allRow = [self returnSectionRow:indexPath.section];
    if (indexPath.row == (allRow -1) && allRow > 4) {//最后一行
        return 200-80;
    }
    //如果是首行
    if(indexPath.row == 0){
        return 200-40;
    }
    //如果是中间几行
    return 200 - 80 -40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *indentifier = @"KWMOrderCell";
    
    KWMOrderCell *orderCell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!orderCell) {
        [tableView registerNib:[UINib nibWithNibName:indentifier bundle:nil] forCellReuseIdentifier:indentifier];
        orderCell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    }
    
    //设置cell图片为默认图
    orderCell.ivImage.image = [UIImage imageNamed:@"ic_loading"];
    
    orderCell.markSection = indexPath.section;
    bool isShowOther = [sectionArr containsObject:[NSString stringWithFormat:@"%ld",(long)indexPath.section]];
    
    BUYOrder *order = [self.orderList objectAtIndex:indexPath.section];
    NSArray<BUYLineItem *> *arr = [order.lineItems array];
    if(!arr){
        return orderCell;
    }
    
    BUYLineItem *lineItem = [arr objectAtIndex:indexPath.row];
    orderCell.lineItem = lineItem;
    //当前section行数
    orderCell.lineCount = [self returnSectionRow:indexPath.section];
    orderCell.order = [self.orderList objectAtIndex:indexPath.section];
    orderCell.markSection = indexPath.section;
    orderCell.imageUrl = [self getProductImage:lineItem.productId];
    
    [orderCell updateUI:indexPath.row productCount:arr.count showAll:isShowOther];
    orderCell.delegate = self;
    return orderCell;
}

#pragma mark -- KWMOrderCellDelegate
-(void)kwm_onClickShowAllWith:(NSInteger)markSection And:(BOOL)showAll{
    if (showAll) {
        [sectionArr removeObject:[NSString stringWithFormat:@"%ld",(long)markSection]];
    }else{
        [sectionArr addObject:[NSString stringWithFormat:@"%ld",(long)markSection]];
    }
    [self.tbvOrder reloadData];
}

- (void)kwm_onClickProduct:(NSNumber *)productId{
    KWMProductDetailVC *productDetailVC = (KWMProductDetailVC *)[KWMProductDetailVC findControllerBy:[KWMProductDetailVC kwmTag] fromStoryboard:@"New"];
    productDetailVC.productId = productId;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

-(void)kwm_onClickTrandsport:(BUYOrder *)order{
    
}

-(void)kwm_onClickCancelOrder:(BUYOrder *)order{
    if(order){
//        [self requestCancelOrder:order.identifier];
        //取消订单前先获取订单状态,因为取消订单api,暂不可使用,所以隐藏取消api按钮
        [self requestOrderStatus:order.identifier];
    }
}

-(NSString *)getProductImage:(NSNumber *)productId{
    NSString *productImage = @"";
    if(productId){
        for(BUYProduct *product in self.productList){
            if([product.identifier isEqualToNumber:productId]){
                productImage = [KWMImageUtil getProductImageUrl:product ImageSize:LowImage];
                
                if([product.identifier isEqualToNumber:@9690154060]){
                    NSLog(@"11111111%@",@"lalal");
                }
            }
        }
    }
    return productImage;
}

-(BOOL)isContainId:(NSArray *)productIds productId:(NSNumber *)productId{
    for(NSNumber *mProductId in productIds){
        if([mProductId isEqualToNumber:productId]){
            return YES;
        }
    }
    return NO;
}

-(NSArray *)splitArray:(NSArray *)array withSubSize:(NSInteger)subSize{
    //拆分后的数组个数
    NSInteger count = array.count % subSize == 0?(array.count /subSize): (array.count / subSize + 1);
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < count; i ++) {
        //数组下标
        NSInteger index = i * subSize;
        //保存拆分的固定长度的数组元素的可变数组
        NSMutableArray *arr1 = [[NSMutableArray alloc] init];
        //移除子数组的所有元素
        [arr1 removeAllObjects];
        
        NSInteger j = index;
        //将数组下标乘以1、2、3,得到拆分时数组的最大下标值,但最大不能超过数组的总大小
        while (j < subSize*(i + 1) && j < array.count) {
            [arr1 addObject:[array objectAtIndex:j]];
            j += 1;
        }
        //将子数组添加到保存子数组的数组中
        [arr addObject:[arr1 copy]];  
    }
    return [arr copy];
}

//获取订单API
- (void)requestOrderAPI{
    [self showLoading];
    __weak KWMOrderVC *weakSelf = self;
    self.client.customerToken = [BUYCustomerToken customerTokenWithJSONDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]];
    [self.client getOrdersForCustomerCallback:^(NSArray<BUYOrder *> * _Nullable orders, NSError * _Nullable error) {
        [weakSelf hideLoading];
        if (error == nil && orders != nil ) {
            [weakSelf.orderList removeAllObjects];
            [weakSelf.orderList addObjectsFromArray:orders];
            [weakSelf.tbvOrder reloadData];
            [weakSelf requestProductsApi];
        }else if (error != nil){
            [weakSelf showError:error];
        }
    }];
}

//获取订单商品列表,从而拿到图片(因为订单api返回的订单数据中没有商品图片数据)
-(void)requestProductsApi{
    if(!self.orderList){
        return;
    }
    NSMutableArray *productIds = [NSMutableArray array];
    for(BUYOrder *order in self.orderList){
        NSArray *lineItems = order.lineItemsArray;
        if(lineItems){
            for(BUYLineItem *lineItem in lineItems){
                //当该商品被删除后,productId有可能为空
                if(lineItem.productId && ![self isContainId:productIds productId:lineItem.productId]){
                    [productIds addObject:lineItem.productId];
                }
            }
        }
    }
    if(productIds.count == 0){
        return;
    }
    __weak KWMOrderVC *weakSelf = self;
    NSArray *productIdsArray = [self splitArray:productIds withSubSize:50];
    for(NSArray *mProductIds in productIdsArray){
        //经过测试,该api一次最多返回50个product,所以如果有100个商品,需要分成两次请求
        [self.client getProductsByIds:mProductIds completion:^(NSArray<BUYProduct *> * _Nullable products, NSError * _Nullable error) {
            if (!error && products != nil && products.count>0) {
                [weakSelf.productList addObjectsFromArray:products];
                [weakSelf.tbvOrder reloadData];
            }else if (error != nil){
                [weakSelf showError:error];
            }
        }];
    }
}

-(void)requestCancelOrder:(NSNumber *)orderId{
    if(orderId == nil){
        return;
    }
    __weak KWMOrderVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMCemaroseResult *) = ^(NSURLSessionDataTask *task,KWMCemaroseResult *result){
        [weakSelf hideLoading];
        if(result!=nil){
            [weakSelf hideLoading];
            [weakSelf requestOrderAPI];
        }
    };
    NSDictionary *parameters = @{
                                 @"reason":@"customer"
                                 };
    [self.api cancelOrder:parameters orderId:orderId success:success failure:failure];
    [self showLoading];
}

-(void)requestOrderStatus:(NSNumber *)orderId{
    [self showToast:@"正在获取订单状态"];
    if(orderId == nil){
        return;
    }
    __weak KWMOrderVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showToast:@"获取订单状态失败"];
    };
    void(^success)(NSURLSessionDataTask *,KWMOrdersResult *) = ^(NSURLSessionDataTask *task,KWMOrdersResult *result){
        [weakSelf hideLoading];
        if(result!=nil && result.orders!=nil && result.orders.count>0){
            KWMOrder *order = result.orders.firstObject;
            if(order.fulfillmentStatus){
                if([order.fulfillmentStatus isEqualToString:@"partial"]){
                    [weakSelf showToast:@"该订单已经配送,无法取消"];
                }else if([order.fulfillmentStatus isEqualToString:@"fulfilled"]){
                    [weakSelf showToast:@"该订单已经配送,无法取消"];
                }
            }else if(order.cancelReason){
                [weakSelf showToast:[NSString stringWithFormat:@"该订单已被取消,取消原因:%@",order.cancelReason]];
            }
            else if(order.closedAt){
                [weakSelf showToast:[NSString stringWithFormat:@"该订单已于%@被关闭",order.closedAt]];
            }else{
                UIAlertController *alertOne = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否取消该订单" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alertOne addAction:cancel];
                UIAlertAction *certain = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
                    [self requestCancelOrder:orderId];
                }];
                [alertOne addAction:certain];
                [weakSelf presentViewController:alertOne animated:YES completion:nil];
            }
        }else{
            [weakSelf showToast:@"未查询到该订单"];
        }
    };
    [self.api getAdminOrder:nil orderId:orderId success:success failure:failure];
    [self showLoading];
}


@end