KWMNewProductVC.m 30.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
//
//  KWMNewProductVC.m
//  iCemarose
//
//  Created by HouWeiBin on 2017/6/23.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMNewProductVC.h"
#import "KWMLoginVC.h"
#import "KWMBeforePayVC.h"
#import "KWMBrandCaramelVC.h"
#import "KWMShareVC.h"
14
#import "KWMWishListVC.h"
15 16 17 18 19
#import "PhotoBroswerVC.h"
#import "KWMUserModel.h"
#import "KWMShoppingCart.h"
#import "KWMImageUtil.h"
#import "KWMStringUtil.h"
houweibin committed
20
#import "KWMShopCartVC.h"
lee committed
21 22 23
#import <TOWebViewController/TOWebViewController.h>
#import <PPNetworkHelper/PPNetworkHelper.h>
#import <TOWebViewController/NJKWebViewProgress.h>
24

25
@interface KWMNewProductVC ()<KWMMidDetailViewDelegate>
26 27 28 29 30

@property (weak, nonatomic) IBOutlet KWMFirstDetailView *detailView1;

@property (weak, nonatomic) IBOutlet KWMSecondDetailView *detailView2;

houweibin committed
31 32 33 34 35 36
@property (weak, nonatomic) IBOutlet KWMMidDetailView *midDetailView;

@property (weak, nonatomic) IBOutlet UIButton *btnShopCart;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

37 38
@property (weak, nonatomic) IBOutlet UIButton *btnLike;

houweibin committed
39
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightMidView;
40

41 42
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *detailView2HeightConstraint;

43 44 45
// 0 非自动  1 是加购  2 是立即购买
@property (assign, nonatomic) NSInteger autoAddToBag;

46 47 48 49 50 51 52 53 54 55 56
//颜色扩展字段
@property (nonatomic) KWMMetafield *colorMeterfield;

//颜色列表,由颜色扩展字段请求api拿到对应product后封装而来
@property (nonatomic) NSMutableArray<KWMColor *> *colorArray;

//选中的variant
@property (nonatomic) BUYProductVariant *variant;

//选中的颜色
@property (nonatomic) KWMColor *color;
57

houweibin committed
58 59 60
//选中的数量
@property (nonatomic) NSInteger count;

lee committed
61 62
@property (nonatomic) NSString *typeTag;

houweibin committed
63

64 65
@property (nonatomic) BOOL isLikeVariant;

houweibin committed
66 67
@property (nonatomic) KWMProduct *adminProduct;

68 69 70 71
@end

@implementation KWMNewProductVC

u  
lee committed
72 73 74 75
+ (NSString *)kwmBoard {
    return @"NewProduct";
}

76 77
- (void)viewDidLoad {
    [super viewDidLoad];
houweibin committed
78
    
houweibin committed
79 80
//    self.productId = @(7436196294);
//    self.product = nil;
houweibin committed
81
    
82 83 84 85 86
    [self initView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
87
    [self initShopCartCount];
88 89 90 91 92 93 94 95 96 97 98 99 100
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)initView{
101
    self.colorArray = [NSMutableArray array];
houweibin committed
102 103
    self.detailView1.delegate = self;
    self.detailView2.delegate = self;
104
    self.midDetailView.delegate = self;
houweibin committed
105 106 107 108 109 110 111 112
    if(self.product){
        self.midDetailView.product = self.product;
        [self.detailView1 setData:self.product];
        [self requestBrandProducts:1];
        [self requestCategoryProducts:1];
    }else{
        [self requestProductDetail];
    }
113
    [self requestColorMetafield];
houweibin committed
114
    [self requestAdminProduct];
115 116
//    [self initShopCartCount];
//    [self initMidViewHight];
houweibin committed
117
    [self.btnLike setImage:[UIImage imageNamed:@"ic_like_unable"] forState:UIControlStateNormal];
lee committed
118 119
    
    
120 121
}

lee committed
122 123


houweibin committed
124 125 126 127 128
- (void)initShopCartCount{
    NSNumber *count = [[KWMShoppingCart sharedInstance] count];
    [self.btnShopCart setTitle:count.stringValue forState:UIControlStateNormal];
}

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
//-(void)initMidViewHight{
//    if(self.product){
//        if([KWMStringUtil isEmpty:self.product.stringDescription]){
//            self.heightMidView.constant = 86.5;
//        }else{
//            NSString *detail = self.product.stringDescription;
//            //获得字体,计算文字显示所需高度
//            UIFont *font = [UIFont systemFontOfSize:11];
//            if(SYSTEM_VERSION_LESS_THAN(@"9.0")){
//                [UIFont fontWithName:@"PingFang SC" size:11];
//            }
//            NSInteger heightLbDetail = [KWMStringUtil getLabelHeight:detail labelFont:font textWidth:UI_SCREEN_WIDTH - 20].height;
//            self.heightMidView.constant =  (86.5 - 15 + heightLbDetail);
//        }
//    }
//}
houweibin committed
145 146


147 148 149 150 151 152 153 154 155 156 157 158 159
//请求API得到颜色Meterfield后才会调用这个.
-(void)initColorData{
    if(!self.colorMeterfield || [KWMStringUtil isEmpty:self.colorMeterfield.value]){
        return;
    }
    //kenzo-13201,blue,7436196294-1.jpg;kenzo-13203,red,7436196614-1.jpg;kenzo-13202,pink,7436196358-1.jpg
    NSArray *colorStringArray = [self.colorMeterfield.value componentsSeparatedByString:@";"];
    for(NSString *colorString in colorStringArray){
        NSArray *colorInfo = [colorString componentsSeparatedByString:@","];
        if(colorInfo.count == 3){//加上判断,以后要是修改了,至少不会程序崩溃。。
            KWMColor *color = [KWMColor new];
            color.handle = colorInfo[0];
            color.title = colorInfo[1];
houweibin committed
160 161 162 163 164 165
            if(self.product && [color.handle isEqualToString:self.product.handle]){
                color.product = self.product;
                [self.colorArray addObject:color];
            }else{
                [self requestProductByColor:color];
            }
166 167
        }
    }
houweibin committed
168 169 170 171 172 173
}

-(void)clearSelect{
    self.color = nil;
    self.variant = nil;
    self.count = 0;
houweibin committed
174
    [self.btnLike setImage:[UIImage imageNamed:@"ic_like_unable"] forState:UIControlStateNormal];
houweibin committed
175 176 177
    if(self.detailView1){
        [self.detailView1 setSelect:nil color:nil count:0];
    }
178 179
}

180

181 182 183 184
-(IBAction)onClickClose:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

houweibin committed
185 186 187 188 189
-(IBAction)onClickShopCart:(id)sender{
    KWMShopCartVC *shopCartVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:shopCartVC animated:YES];
}

190 191 192 193 194 195 196 197 198 199 200 201
-(IBAction)onClickShare:(id)sender{
    if(self.product){
    KWMShareVC *shareVC = (KWMShareVC *)[KWMBaseVC findControllerBy:[KWMShareVC kwmTag] fromStoryboard:@"New"];
    shareVC.shareUrl = [NSString stringWithFormat:@"https://www.cemarose.com/products/%@",self.product.handle];
    shareVC.imageUrl = [KWMImageUtil getProductImageUrl:self.product ImageSize:SmallImage];
    shareVC.productName = self.product.title;
    CGSize size = [UIScreen mainScreen].bounds.size;
    [self showPresentation:shareVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
    }
}

-(IBAction)onClickLike:(id)sender{
houweibin committed
202 203 204 205 206 207 208 209
    KWMUserModel *useModel = [KWMUserModel shareUser];
    if (!useModel.status) {
        //登录
        KWMLoginVC *loginVc = (KWMLoginVC *)[KWMBaseVC findControllerBy:[KWMLoginVC kwmTag] fromStoryboard:@"Login"];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
houweibin committed
210 211 212 213
    if(!self.variant){
        [self showToast:@"请先选择尺码/顏色"];
        return;
    }
214 215 216 217 218
    if(self.isLikeVariant){
        [self requestRemoveWish];
    }else{
        [self requestAddWish];
    }
219 220
}

houweibin committed
221
-(IBAction)onClickComplete:(UIButton *)sender{
222
    BOOL buyNow = sender.tag == 1 || self.autoAddToBag == 2;
houweibin committed
223
    if(!self.variant){
224 225 226
//        [self showToast:@"请选择商品"];
        self.autoAddToBag = buyNow ? 2 : 1;
        [self kwm_onClickSizeBtn];
houweibin committed
227
        return;
228
    }
lee committed
229 230 231 232
    if(buyNow) {
        [self addShopWithVariantId:self.variant.identifier quantity:self.count variant:self.variant buyNow:YES callback:^(BOOL _){}];
        return;
    }
houweibin committed
233
    __weak KWMNewProductVC *this = self;
lee committed
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 259 260 261
    // TODO: this
    NSArray<KWMShopCartModel *> *items = [[KWMShoppingCart sharedInstance] items];
    KWMShopCartModel *item = nil;
    for (KWMShopCartModel *it in items) {
        if (it.identifier.integerValue == self.variant.identifier.integerValue) {
            item = it;
            break;
        }
    }
    NSInteger quantity = self.count;
    KWMVariants *variant = nil;
    for (KWMVariants *it in self.adminProduct.variants) {
        if (it.id.integerValue == self.variant.identifier.integerValue) {
            variant = it;
            break;
        }
    }
    if (item.quantity + quantity > variant.inventoryQuantity.integerValue) {
        quantity = variant.inventoryQuantity.integerValue - item.quantity;
        if (quantity <= 0 && !buyNow) {
            [self showToast:@"无库存"];
            return;
        }else{
            [self showToast:@"库存不足"];
        }
    }
    [self showLoading];
    [self addShopWithVariantId:self.variant.identifier quantity:quantity variant:self.variant buyNow:buyNow callback:^(BOOL success) {
houweibin committed
262 263 264 265 266 267 268
        [this hideLoading];
        if(success) {
            if(!buyNow){
                [this initShopCartCount];
                [this clearSelect];
            }
            //[this dismissViewControllerAnimated:YES completion:nil];
269 270 271 272
        }
    }];
}

houweibin committed
273 274
//添加商品
- (void)addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity variant:(BUYProductVariant *) variant buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback {
275 276 277 278 279 280 281 282 283 284
    __weak KWMNewProductVC *this = self;
    if (!buyNow) {
        [[KWMShoppingCart sharedInstance] increaseProductWithVariantId:identifier quantity:quantity callback:^(NSError *error, KWMCartResult *cart) {
            if (cart.items.firstObject && !cart.items.firstObject.product_id) {
                KWMShopCartModel *model = cart.items.firstObject;
                BUYImageLink *il = this.product.images.firstObject;
                model.imageStr = [KWMImageUtil getProductImageUrlByOriginalUrl:il.sourceURL.absoluteString ImageSize:NormalImage];
                model.name = this.product.title;
                model.brand = this.product.vendor;
                model.size = variant.title;
houweibin committed
285
                model.price = variant.price;
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
                model.product_id = this.product.identifier;
            }
            if (!error) {
                [this showToast:@"添加成功"];
                callback(YES);
            }else{
                [this showError:error];
                callback(NO);
            }
        }];
        return;
    }
    callback(YES);
    KWMUserModel *useModel = [KWMUserModel shareUser];
    if (!useModel.status) {
        //登录
302 303 304 305 306
        dispatch_after(0, dispatch_get_main_queue(), ^{
            KWMLoginVC *loginVc = (KWMLoginVC *)[KWMBaseVC findControllerBy:[KWMLoginVC kwmTag] fromStoryboard:@"Login"];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
            [self presentViewController:nav animated:YES completion:nil];
        });
307 308 309 310 311 312 313 314 315 316 317 318 319 320
        return;
    }
    [self showLoading];
    [self.api tmpCartWithVariantId:identifier quantity:quantity success:^(NSURLSessionDataTask *task, NSString *cartCookie) {
        [this hideLoading];
        KWMBeforePayVC *beforePayVC = (KWMBeforePayVC *)[KWMBaseVC findControllerBy:[KWMBeforePayVC kwmTag] fromStoryboard:@"ShopCart"];
        beforePayVC.cartCookie = cartCookie;
        [this.navigationController pushViewController:beforePayVC animated:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [this showError:error];
    }];
    
}

houweibin committed
321
#pragma mark -- KWMSecondDetailViewDelegate
322 323 324 325
-(void)kwm_updatedSecondDetailViewHeight:(CGFloat)height {
    self.detailView2HeightConstraint.constant = height;
}

houweibin committed
326 327 328 329 330 331
-(void)kwm_clickCollectionCell:(BUYProduct *)product{
    if(!product){
        return;
    }
    self.product = product;
    self.productId = product.identifier;
houweibin committed
332 333
    self.colorMeterfield = nil;
    self.adminProduct = nil;
houweibin committed
334 335 336 337 338
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self initView];
    [self clearSelect];
}

houweibin committed
339 340 341 342 343 344 345 346
-(void)kwm_clickMore:(BOOL)isSameBrand{
    if(!self.product){
        return;
    }
    NSString *handle = isSameBrand?[KWMStringUtil deleteOtherCharExceptLetterWithLine:self.product.vendor]:self.product.productType;
    [self openURLWithString:[NSString stringWithFormat:@"https://cemarose.myshopify.com/collections/%@",handle]];
}

houweibin committed
347 348 349 350 351 352 353 354 355 356 357 358
#pragma mark -- KWMFirstDetailViewDelegate
-(void)kwm_onClickSizeBtn{
    
    KWMVariantsVC *variantsVC = (KWMVariantsVC *)[KWMVariantsVC findControllerBy:[KWMVariantsVC kwmTag] fromStoryboard:@"NewProduct"];
    variantsVC.product = self.product;
    variantsVC.adminProduct = self.adminProduct;
    variantsVC.colorArray = self.colorArray;
    variantsVC.delegate = self;
    if(self.variant){
        [variantsVC setDefaultSelect:self.variant color:self.color count:self.count];
    }
    CGSize size = [UIScreen mainScreen].bounds.size;
359 360 361 362
    MZFormSheetPresentationViewController * mz  = [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleSlideFromBottom];
    mz.didDismissContentViewControllerHandler = ^(UIViewController * _Nonnull contentViewController) {
        self.autoAddToBag = 0;
    };
houweibin committed
363 364
}

lee committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
- (void)kwm_sizeGuide {
    NSString *brand = [self.product.vendor stringByReplacingOccurrencesOfRegex:@"\\s*\\W\\s*" withString:@"-"].lowercaseString;
    NSString *baseUrl = @"http://www.cemarose.cn/pages/";
    NSString *url= [NSString stringWithFormat:@"%@%@-size-guide-%@",baseUrl,brand,self.typeTag];
    NSLog(@"size guide url: %@",url);
    //    TOWebViewController *wv = [[TOWebViewController alloc] initWithURLString:url];
    TOWebViewController *wv = [[TOWebViewController alloc] init];
    __unused id _ = wv.view;
    wv.showPageTitles = NO;
    wv.title = @"Size Guide";
    wv.navigationButtonsHidden = YES;
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    ////    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    ////        NJKWebViewProgress *wvp = [vc valueForKeyPath:@"progressManager"];
    ////        [wvp.progressDelegate webViewProgress:wvp updateProgress:downloadProgress.fractionCompleted];
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        NSString *body = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    //        body = [body stringByReplacingOccurrencesOfRegex:@"<meta[\\w\\W]*?/?>" withString:@""];
    //        body = [body stringByReplacingOccurrencesOfRegex:@"<script[\\w\\W]*?</script>" withString:@""];
    //        body = [body stringByReplacingOccurrencesOfRegex:@"<header[\\w\\W]*?</header>" withString:@""];
    //        body = [body stringByReplacingOccurrencesOfRegex:@"<footer[\\w\\W]*?</footer>" withString:@""];
    //        body = [body stringByReplacingOccurrencesOfRegex:@"<head>" withString:@"<head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" /><style type='text/css'>"
    //                @".page-title h1.label{font-size:17px;}"
    //                @".rte.text-content td{padding-left:10px;}"
    //                @"</style>"];
    //        [wv.webView loadHTMLString:body baseURL:[NSURL URLWithString:baseUrl]];
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //    }];
    void(^success)(id) = ^(id body){
        if (!body) {
            return;
        }
        body = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
        body = [body stringByReplacingOccurrencesOfRegex:@"<meta[\\w\\W]*?/?>" withString:@""];
        body = [body stringByReplacingOccurrencesOfRegex:@"<script[\\w\\W]*?</script>" withString:@""];
        body = [body stringByReplacingOccurrencesOfRegex:@"<header[\\w\\W]*?</header>" withString:@""];
        body = [body stringByReplacingOccurrencesOfRegex:@"<footer[\\w\\W]*?</footer>" withString:@""];
        body = [body stringByReplacingOccurrencesOfRegex:@"<head>" withString:@"<head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" /><style type='text/css'>"
                @".page-title h1.label{font-size:17px;}"
                @".rte.text-content td{padding-left:10px;}"
                @"</style>"];
        [wv.webView loadHTMLString:body baseURL:[NSURL URLWithString:baseUrl]];
        
    };
    
    __weak typeof(self) this = self;
    [PPNetworkHelper setAFHTTPSessionManagerProperty:^(AFHTTPSessionManager *sessionManager) {
        sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    }];
418
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet whitespaceCharacterSet].invertedSet];
lee committed
419 420 421 422 423 424 425 426 427
    [PPNetworkHelper GET:url parameters:nil responseCache:success success:success failure:^(NSError *error) {
        [this showError:error];
    }];
    [self.navigationController pushViewController:wv animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(200 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        NJKWebViewProgress *wvp = [wv valueForKeyPath:@"progressManager"];
        [wvp.progressDelegate webViewProgress:wvp updateProgress:0.1];
    });
}
houweibin committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

-(void)kwm_goToBrandVC{
    if(self.product && self.product.vendor){
        KWMBrandCaramelVC *brandCaramelVC = (KWMBrandCaramelVC *)[KWMBrandCaramelVC findControllerBy:[KWMBrandCaramelVC kwmTag] fromStoryboard:@"Brand"];
        NSString *brand = self.product.vendor;
        brandCaramelVC.brand = brand;
        brandCaramelVC.handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:brand];
        brandCaramelVC.isSale = NO;
        [self.navigationController pushViewController:brandCaramelVC animated:YES];
    }
}

-(void)kwm_onClickImage:(NSMutableArray *)imageArr currentIndex:(NSInteger)currentIndex{
    __weak KWMNewProductVC *weakSelf=self;
    NSArray<NSString *> *imags = imageArr;
    [PhotoBroswerVC show:self type:PhotoBroswerVCTypePush index:currentIndex isShowSaveBtn:YES photoModelBlock:^NSArray *{
        NSArray *localImages = imags;
        NSMutableArray *modelsM = [NSMutableArray arrayWithCapacity:localImages.count];
        for (NSUInteger i = 0; i< localImages.count; i++) {
            PhotoModel *pbModel=[[PhotoModel alloc] init];
            pbModel.mid = i + 1;
            //源frame
            UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, weakSelf.view.frame.size.width, weakSelf.view.frame.size.height)];
            pbModel.sourceImageView = imageV;
            pbModel.image_HD_U = [[KWMAPIManager sharedManager] toAbsoluteUrl:localImages[i]];
            [modelsM addObject:pbModel];
        }
        return modelsM;
    }];
}


#pragma mark - KWMVariantsVCDelegate
-(void)kwm_setVariant:(KWMVariantsVC *)variantsVC variant:(BUYProductVariant *)variant color:(KWMColor *)color count:(NSInteger)count{
    [self.btnLike setImage:[UIImage imageNamed:@"ic_like"] forState:UIControlStateNormal];
    [self.detailView1 setSelect:variant color:color count:count];
    self.variant = variant;
    self.color = color;
    self.count = count;
    
    self.isLikeVariant = NO;
    [self requestWishList];
470 471 472 473
    if (self.autoAddToBag) {
        [self onClickComplete:nil];
        self.autoAddToBag = 0;
    }
houweibin committed
474 475
}

476 477 478 479 480 481
#pragma mark - KWMMidViewDetailDelegate

-(void) kwm_updatedHeight:(CGFloat)height {
    self.heightMidView.constant = height;
}

482 483
#pragma mark - API BUYClient+Storefront
-(void)requestProductDetail{
u  
lee committed
484
    if(!(self.productId || self.product || self.handle)){
485 486 487 488
        return;
    }
    [self showLoading];
    __weak KWMNewProductVC *weakSelf = self;
u  
lee committed
489
    void(^completion)(BUYProduct*,NSError*) = ^(BUYProduct * _Nullable product, NSError * _Nullable error) {
490 491 492 493 494
        [weakSelf hideLoading];
        if(error){
            [weakSelf showError:error];
        }else if(product){
            weakSelf.product = product;
houweibin committed
495
            weakSelf.productId = product.identifier;
496
//            [weakSelf initMidViewHight];
houweibin committed
497
            weakSelf.midDetailView.product = product;
498
            [weakSelf.detailView1 setData:product];
houweibin committed
499 500
            [self requestBrandProducts:1];
            [self requestCategoryProducts:1];
houweibin committed
501 502 503 504 505
            
            if(self.handle){
                [self requestAdminProduct];
                [self requestColorMetafield];
            }
506
        }
u  
lee committed
507 508 509 510 511 512
    };
    if (self.handle) {
        [self.client getProductByHandle:self.handle completion:completion];
    }else{
        [self.client getProductById:self.productId?:self.product.identifier completion:completion];
    }
513 514
}

515 516 517 518 519 520 521 522 523

-(void)requestProductByColor:(KWMColor *)color{
    __weak KWMNewProductVC *weakSelf = self;
    [weakSelf showLoading];
    [self.client getProductByHandle:color.handle completion:^(BUYProduct * _Nullable product, NSError * _Nullable error) {
        [weakSelf hideLoading];
        if(error){

        }else if(product){
houweibin committed
524
            color.product = product;
525 526 527 528 529
            [weakSelf.colorArray addObject:color];
        }
    }];
}

530
-(void)requestBrandProducts:(NSInteger)page{
houweibin committed
531 532 533 534
    if(!self.product){
        return;
    }
    NSString *handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:self.product.vendor];
535 536
    self.detailView2.isLoadingSameBrand = YES;
    __weak KWMNewProductVC *weakSelf = self;
537 538 539 540 541 542 543 544 545
    [self.api searchProduct:@{@"keyword":self.product.vendor} success:^(NSURLSessionDataTask *task, KWMSearchResult *result) {
//        weakSelf.detailView2.isLoadingSameBrand = NO;
        weakSelf.detailView2.brand = weakSelf.product.vendor;
        weakSelf.detailView2.productCount = result.products.total;
//        [weakSelf.detailView2 setData:result.productList isSameBrand:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
//        weakSelf.detailView2.isLoadingSameBrand = NO;
    }];
546 547
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if(collection && !error){
548
            weakSelf.detailView2.brandDescription = collection.stringDescription;
549 550
            [weakSelf.client getProductsPage:page inCollection:collection.identifier completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
                weakSelf.detailView2.isLoadingSameBrand = NO;
551 552
                weakSelf.detailView2.brand = weakSelf.product.vendor;
                
553 554 555 556 557 558 559 560 561 562
                [weakSelf.detailView2 setData:products isSameBrand:YES];
            }];
            
        }else{
            weakSelf.detailView2.isLoadingSameBrand = NO;
        }
    }];
}

-(void)requestCategoryProducts:(NSInteger)page{
houweibin committed
563 564 565 566
    if(!self.product){
        return;
    }
    NSString *handle = self.product.productType;
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    self.detailView2.isLoadingSameType = YES;
    __weak KWMNewProductVC *weakSelf = self;
    [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) {
        if(collection && !error){
            
            [weakSelf.client getProductsPage:page inCollection:collection.identifier completion:^(NSArray<BUYProduct *> * _Nullable products, NSUInteger page, BOOL reachedEnd, NSError * _Nullable error) {
                weakSelf.detailView2.isLoadingSameType = NO;
                [weakSelf.detailView2 setData:products isSameBrand:NO];
            }];
        }else{
            weakSelf.detailView2.isLoadingSameType = NO;
        }
    }];
}

houweibin committed
582 583 584
#pragma mark  -- API KWMApimanager
-(void)requestAdminProduct{
    NSNumber *productId = self.product?self.product.identifier:self.productId;
houweibin committed
585 586 587
    if(!productId){
        return;
    }
houweibin committed
588 589 590 591 592 593 594 595 596 597 598 599
    __weak KWMNewProductVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
    };
    void(^success)(NSURLSessionDataTask *,KWMProductResult *) = ^(NSURLSessionDataTask *task,KWMProductResult *result){
        if(result!=nil && result.product!=nil){
            KWMProduct* adminProduct = (KWMProduct *)result.product;
            weakSelf.adminProduct = adminProduct;
        }
    };
    [self.api getAdminProduct:nil productId:productId success:success failure:failure];
}

600 601

-(void)requestColorMetafield{
houweibin committed
602
    NSNumber *productId = self.product?self.product.identifier:self.productId;
houweibin committed
603 604 605
    if(!productId){
        return;
    }
606 607
    __weak KWMNewProductVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
houweibin committed
608
//        [weakSelf showError:error];
609 610 611 612 613 614 615 616 617 618 619 620 621 622
    };
    void(^success)(NSURLSessionDataTask *,KWMMetafieldResult *) = ^(NSURLSessionDataTask *task,KWMMetafieldResult *result){
        if(!result.metafields){
            return;
        }
        NSArray *array = (NSArray *)result.metafields;
        for(KWMMetafield *metafield in array){
            if([metafield.key isEqualToString:@"pe_related_1"]){
                weakSelf.colorMeterfield = metafield;
                [weakSelf initColorData];
                return;
            }
        }
    };
houweibin committed
623
    [self.api getProductMetafield:nil productId:productId success:success failure:failure];
624 625 626
}


627 628 629 630
-(void)requestWishList{
    __weak KWMNewProductVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
houweibin committed
631
    BUYProductVariant *variant = self.variant;
632
    if(!(customer && customer.identifier && variant)){
633 634 635 636 637
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
houweibin committed
638
                               @"variant_id":variant.identifier.stringValue,
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
                               @"shop":Shopify_SHOP_DOMAIN
                               };
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMAdditionalListResult *) = ^(NSURLSessionDataTask *task,KWMAdditionalListResult *result){
        [weakSelf hideLoading];
        if(result && result.data){
            NSArray *wishArray = (NSArray *)result.data;
            if(wishArray.count >0){
                UIImage *image = [UIImage imageNamed:@"ic_like_1"];
                [weakSelf.btnLike setImage:image forState:UIControlStateNormal];
                weakSelf.isLikeVariant = YES;
            }
        }
    };
    [self.api getWishList:parament success:success failure:failure];
}
658

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
-(void)requestRemoveWish{
    __weak KWMNewProductVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
    BUYProductVariant *variant = self.detailView1.variant;
    if(!customer || !variant){
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"variant_id":variant.identifier.stringValue,
                               @"shop":Shopify_SHOP_DOMAIN
                               };
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMAdditionalListResult *) = ^(NSURLSessionDataTask *task,KWMAdditionalListResult *result){
        [weakSelf hideLoading];
        if(result && result.message){
            if([result.message isEqualToString:@"success"] || [result.message isEqualToString:@"wishlist does not exist"]){
                UIImage *image = [UIImage imageNamed:@"ic_like"];
                [weakSelf.btnLike setImage:image forState:UIControlStateNormal];
                weakSelf.isLikeVariant = NO;
            }
685

686 687 688 689 690 691
        }
        
    };
    [self.api removeWish:parament success:success failure:failure];
    [self showLoading];
}
692

693 694 695 696 697 698 699
-(void)requestAddWish{
    __weak KWMNewProductVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
    if(!customer || !self.variant){
        return;
    }
700 701
    NSNumber *customerId = customer.identifier?:@(0);
    NSString *customerName = customer.lastName?:@"";
houweibin committed
702
    BUYProduct *product = (self.color && self.color.product)?self.color.product:self.product;
703
    NSDictionary *parament = @{
704
                               @"customer_id":customerId.stringValue,
705
                               @"customer_email":customer.email,
706
                               @"customer_name":customerName,
houweibin committed
707 708
                               @"product_title":product.title,
                               @"product_id":product.identifier.stringValue,
709 710 711
                               @"variant_id":self.variant.identifier.stringValue,
                               @"variant_sku":self.variant.sku,
                               @"variant_title":self.variant.title,
houweibin committed
712
                               @"product_handle":product.handle,
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
                               @"shop":Shopify_SHOP_DOMAIN
                               };
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
    void(^success)(NSURLSessionDataTask *,KWMAdditionalListResult *) = ^(NSURLSessionDataTask *task,KWMAdditionalListResult *result){
        [weakSelf hideLoading];
        if(result && result.message && [result.message isEqualToString:@"success"]){
            if([result.message isEqualToString:@"success"] || [result.message isEqualToString:@"wishlist already exist"]){
                UIImage *image = [UIImage imageNamed:@"ic_like_1"];
                [weakSelf.btnLike setImage:image forState:UIControlStateNormal];
                weakSelf.isLikeVariant = YES;
            }
        }
    };
    [self.api saveWish:parament success:success failure:failure];
    [self showLoading];
}
732 733


houweibin committed
734

lee committed
735 736 737 738 739 740 741 742 743 744 745 746 747
- (void)setProduct:(BUYProduct *)product {
    _product = product;
    NSArray *types = @[@"baby",@"girls",@"boys",@"shoes",@"newborn"];
    for (NSString *tag in self.product.tags) {
        if ([types containsObject:tag.lowercaseString]) {
            self.typeTag = tag.lowercaseString;
            break;
        }
    }
    
    [self.detailView1 setSizeGuideHidden:!self.typeTag];
}

houweibin committed
748 749 750



751

752
@end