KWMOrderVC.m 11.9 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//
//  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;//订单列表
houweibin committed
16
@property (nonatomic) NSMutableArray *productList;//订单商品列表
houweibin committed
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

@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.
houweibin committed
39 40
    self.orderList = [NSMutableArray array];
    self.productList = [NSMutableArray array];
houweibin committed
41 42 43 44 45 46 47 48 49 50
    sectionArr = [NSMutableArray array];
    [self requestOrderAPI];
}

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

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
houweibin committed
51
    return self.orderList.count;
houweibin committed
52 53 54
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
houweibin committed
55
    BUYOrder *order = [self.orderList objectAtIndex:section];
houweibin committed
56 57 58 59 60 61
    NSArray<BUYLineItem *> *lineItems = [order.lineItems array];
    bool isShowOther = [sectionArr containsObject:[NSString stringWithFormat:@"%ld",(long)section]];
    if(!lineItems){
        return 0;
    }
    if(!isShowOther && lineItems.count >= 4){
houweibin committed
62
        return 4;
houweibin committed
63 64 65 66 67 68
    }
    return lineItems.count;
}

//每一个section有多少行
- (NSInteger)returnSectionRow:(NSInteger)section{
houweibin committed
69
    BUYOrder *order = [self.orderList objectAtIndex:section];
houweibin committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    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]];
    
houweibin committed
110
    BUYOrder *order = [self.orderList objectAtIndex:indexPath.section];
houweibin committed
111 112 113 114 115 116 117 118
    NSArray<BUYLineItem *> *arr = [order.lineItems array];
    if(!arr){
        return orderCell;
    }
    
    BUYLineItem *lineItem = [arr objectAtIndex:indexPath.row];
    orderCell.lineItem = lineItem;
    //当前section行数
houweibin committed
119 120
    orderCell.lineCount = [self returnSectionRow:indexPath.section];
    orderCell.order = [self.orderList objectAtIndex:indexPath.section];
houweibin committed
121
    orderCell.markSection = indexPath.section;
houweibin committed
122
    orderCell.imageUrl = [self getProductImage:lineItem.productId];
houweibin committed
123
    
houweibin committed
124
    [orderCell updateUI:indexPath.row productCount:arr.count showAll:isShowOther];
houweibin committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    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];
    }
}

houweibin committed
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
-(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];
            }
        }];
    }
}

houweibin committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
-(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