KWMOrderVC.m 13.2 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10
//
//  KWMOrderVC.m
//  iCemarose
//
//  Created by HouWeiBin on 16/8/30.
//  Copyright © 2016年 kollway. All rights reserved.
//

#import "KWMOrderVC.h"
#import "KWMOrderCell.h"
u  
lee committed
11
#import "KWMNewProductVC.h"
houweibin committed
12
#import "KWMImageUtil.h"
13
#import "KWMStringUtil.h"
houweibin committed
14
#import "MJRefresh.h"
houweibin committed
15 16

@interface KWMOrderVC ()
houweibin committed
17
@property (nonatomic) NSMutableArray *productList;//订单商品列表
houweibin committed
18
@property (nonatomic) NSMutableArray *expandOrderId;//标记展开的section
houweibin committed
19 20 21 22 23 24 25 26 27 28 29 30 31
@end

@implementation KWMOrderVC{
}

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

-(void)awakeFromNib{
    [super awakeFromNib];
    self.title = @"我的订单";
}
32 33

-(void)viewWillAppear:(BOOL)animated{
houweibin committed
34 35 36
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}
37 38

-(void)viewDidLoad{
houweibin committed
39
    [super viewDidLoad];
40 41 42 43
    [self setUpData];
}

-(void)setUpData{
houweibin committed
44
    self.productList = [NSMutableArray array];
houweibin committed
45
    self.expandOrderId = [NSMutableArray array];
46 47 48
}

-(void)loadData{
houweibin committed
49
    [self requestNewOrderAPI];
houweibin committed
50 51
}

52 53 54 55 56 57 58 59 60 61 62 63 64 65
-(UITableView *)targetTableView{
    return self.tbvOrder;
}

-(BUYOrder *)getPaidOrder{
    if(self.paidCheckout){
        BUYOrder *order = [[BUYOrder alloc]init];
        order.checkout = self.paidCheckout;
        order.lineItems = self.paidCheckout.lineItems;
        order.totalPrice = self.paidCheckout.totalPrice;
        return order;
    }else{
        return nil;
    }
houweibin committed
66 67
}

68 69 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
-(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];
            }
        }
    }
    return productImage;
}

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

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

//将商品数量小于4的订单(完全展开的订单)添加到openSection中
-(void)refreshOpenSection:(NSArray<BUYOrder *> *)array{
    if(!array){
        return;
    }
    for(BUYOrder *order in array){
        NSArray<BUYLineItem *> *arr = [order.lineItems array];
        if(arr && arr.count > 4){
            return;
houweibin committed
105 106
        }else if(order.identifier && ![self.expandOrderId containsObject:order.identifier]){
            [self.expandOrderId addObject:order.identifier];
107 108 109 110 111 112 113
        }
    }
}

#pragma mark -- UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataList.count;
houweibin committed
114 115 116
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
117 118
    bool isExpend = YES;
    BUYOrder *order = [self.dataList objectAtIndex:section];
houweibin committed
119
    NSArray<BUYLineItem *> *lineItems = [order.lineItems array];
120
    if(order.identifier){
houweibin committed
121
        isExpend = [self.expandOrderId containsObject:order.identifier];
122
    }
houweibin committed
123 124 125
    if(!lineItems){
        return 0;
    }
126
    if(!isExpend && lineItems.count >= 4){
houweibin committed
127
        return 4;
houweibin committed
128 129 130 131 132
    }
    return lineItems.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
133 134 135
    bool isExpend = YES;
    BUYOrder *order = [self.dataList objectAtIndex:indexPath.section];
    if(order.identifier){
houweibin committed
136
        isExpend = [self.expandOrderId containsObject:order.identifier];
houweibin committed
137
    }
138 139 140 141 142 143 144 145
    NSInteger rowCount = [self getRowCountBySection:indexPath.section];
    NSInteger lastRow = rowCount -1;
    NSInteger firstRow = 0;
    CGFloat h = 165;
    CGFloat head = 45;
    CGFloat bot = 40;
    if(indexPath.row == 3 && !isExpend){
        return h - head;
houweibin committed
146
    }
147 148
    if(indexPath.row == lastRow && rowCount >4){
        return h - head;
houweibin committed
149
    }
150 151 152 153
    if(indexPath.row == firstRow){
        return h - bot;
    }
    return h - head -bot;
houweibin committed
154 155 156 157
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *indentifier = @"KWMOrderCell";
158
    bool isExpend = YES;
houweibin committed
159 160 161 162 163 164 165 166 167
    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;
    
168 169
    BUYOrder *order = [self.dataList objectAtIndex:indexPath.section];
    if(order.identifier){
houweibin committed
170
        isExpend = [self.expandOrderId containsObject:order.identifier];
171
    }
houweibin committed
172 173 174 175 176
    NSArray<BUYLineItem *> *arr = [order.lineItems array];
    if(!arr){
        return orderCell;
    }
    //当前section行数
177 178
    orderCell.lineCount = [self getRowCountBySection:indexPath.section];
    orderCell.order = [self.dataList objectAtIndex:indexPath.section];
lee committed
179 180
    BUYLineItem *lineItem = [arr objectAtIndex:indexPath.row];
    orderCell.lineItem = lineItem;
houweibin committed
181
    orderCell.markSection = indexPath.section;
houweibin committed
182
    orderCell.imageUrl = [self getProductImage:lineItem.productId];
183
    [orderCell updateUI:indexPath.row productCount:arr.count showAll:isExpend];
houweibin committed
184 185 186 187 188 189
    orderCell.delegate = self;
    return orderCell;
}

#pragma mark -- KWMOrderCellDelegate
-(void)kwm_onClickShowAllWith:(NSInteger)markSection And:(BOOL)showAll{
190 191 192
    BUYOrder *order = [self.dataList objectAtIndex:markSection];
    if(order.identifier){
        if (showAll) {
houweibin committed
193
            [self.expandOrderId removeObject:order.identifier];
194
        }else{
houweibin committed
195
            [self.expandOrderId addObject:order.identifier];
196
        }
houweibin committed
197 198 199 200 201
    }
    [self.tbvOrder reloadData];
}

- (void)kwm_onClickProduct:(NSNumber *)productId{
u  
lee committed
202
    KWMNewProductVC *productDetailVC = [KWMNewProductVC getNewInstance];
houweibin committed
203 204 205 206 207 208 209 210 211
    productDetailVC.productId = productId;
    [self.navigationController pushViewController:productDetailVC animated:YES];
}

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

-(void)kwm_onClickCancelOrder:(BUYOrder *)order{
houweibin committed
212 213
}

houweibin committed
214 215


216
#pragma mark -- API
houweibin committed
217 218
//获取全部订单API
- (void)requestNewOrderAPI{
houweibin committed
219 220
    [self showLoading];
    __weak KWMOrderVC *weakSelf = self;
houweibin committed
221 222 223 224 225 226
    NSInteger targetPage = self.currentPage.integerValue + 1;
    self.tbvOrder.mj_footer.hidden = YES;
    NSDictionary *parameters = @{
                               @"page":@(targetPage).stringValue
                               };
    [self.api getOrderList:parameters success:^(NSURLSessionDataTask *task, KWMOrderListResult *result) {
houweibin committed
227
        [weakSelf hideLoading];
228 229
        if(!result || !result.code || result.code.integerValue != 1000){
            if(result && result.message){
houweibin committed
230 231 232 233
                [weakSelf showToast:result.message];
            }
            return;
        }
234
        weakSelf.hasNextPage = result.data && result.data.count > 0;
houweibin committed
235 236
        if (result.data) {
            NSMutableArray *showOrders = [NSMutableArray arrayWithArray:result.data];
237
            BUYOrder *paidOrder = [self getPaidOrder];
houweibin committed
238
            if(paidOrder && targetPage ==1){
239 240
                [showOrders insertObject:paidOrder atIndex:0];
            }
houweibin committed
241
            if(targetPage == 1){
houweibin committed
242 243 244
                [weakSelf.dataList removeAllObjects];
                [self.expandOrderId removeAllObjects];
            }
245
            [weakSelf refreshOpenSection:showOrders];
houweibin committed
246
            [weakSelf appendDataList:showOrders setPage:targetPage];
houweibin committed
247 248
            [weakSelf requestProductsApi];
        }
houweibin committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showError:error];
    }];
}


//获取订单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];
//        NSMutableArray *showOrders = [NSMutableArray arrayWithArray:orders];
//        if (error == nil && orders != nil ) {
//            BUYOrder *paidOrder = [self getPaidOrder];
//            if(paidOrder){
//                [showOrders insertObject:paidOrder atIndex:0];
//            }
//            [weakSelf.dataList removeAllObjects];
//            [weakSelf refreshOpenSection:showOrders];
//            [weakSelf appendDataList:showOrders setPage:1];
//            weakSelf.hasNextPage = false;
//            [weakSelf requestProductsApi];
//        }else if (error != nil){
//            [weakSelf showError:error];
//        }
houweibin committed
278 279 280 281 282
    }];
}

//获取订单商品列表,从而拿到图片(因为订单api返回的订单数据中没有商品图片数据)
-(void)requestProductsApi{
283
    if(!self.dataList){
houweibin committed
284 285 286
        return;
    }
    NSMutableArray *productIds = [NSMutableArray array];
287
    for(BUYOrder *order in self.dataList){
houweibin committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301
        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;
302
    NSArray *productIdsArray = [KWMStringUtil splitArray:productIds withSubSize:50];
houweibin committed
303 304 305 306 307 308 309 310 311 312 313 314 315
    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
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
-(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