KWMNewProductVC.m 27.1 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 26 27 28 29 30

@interface KWMNewProductVC ()

@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 43 44 45 46 47 48 49 50 51
//颜色扩展字段
@property (nonatomic) KWMMetafield *colorMeterfield;

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

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

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

houweibin committed
53 54 55
//选中的数量
@property (nonatomic) NSInteger count;

lee committed
56 57
@property (nonatomic) NSString *typeTag;

houweibin committed
58

59 60
@property (nonatomic) BOOL isLikeVariant;

houweibin committed
61 62
@property (nonatomic) KWMProduct *adminProduct;

63 64 65 66
@end

@implementation KWMNewProductVC

u  
lee committed
67 68 69 70
+ (NSString *)kwmBoard {
    return @"NewProduct";
}

71 72
- (void)viewDidLoad {
    [super viewDidLoad];
houweibin committed
73
    
houweibin committed
74 75
//    self.productId = @(7436196294);
//    self.product = nil;
houweibin committed
76
    
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    [self initView];
}

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

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

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

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

lee committed
116 117


houweibin committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
- (void)initShopCartCount{
    NSNumber *count = [[KWMShoppingCart sharedInstance] count];
    [self.btnShopCart setTitle:count.stringValue forState:UIControlStateNormal];
}

-(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);
        }
    }
}


141 142 143 144 145 146 147 148 149 150 151 152 153
//请求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
154 155 156 157 158 159
            if(self.product && [color.handle isEqualToString:self.product.handle]){
                color.product = self.product;
                [self.colorArray addObject:color];
            }else{
                [self requestProductByColor:color];
            }
160 161
        }
    }
houweibin committed
162 163 164 165 166 167 168 169 170
}

-(void)clearSelect{
    self.color = nil;
    self.variant = nil;
    self.count = 0;
    if(self.detailView1){
        [self.detailView1 setSelect:nil color:nil count:0];
    }
171 172
}

173

174 175 176 177
-(IBAction)onClickClose:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

houweibin committed
178 179 180 181 182
-(IBAction)onClickShopCart:(id)sender{
    KWMShopCartVC *shopCartVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"];
    [self.navigationController pushViewController:shopCartVC animated:YES];
}

183 184 185 186 187 188 189 190 191 192 193 194
-(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
195 196 197 198 199 200 201 202
    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;
    }
203 204 205 206 207
    if(self.isLikeVariant){
        [self requestRemoveWish];
    }else{
        [self requestAddWish];
    }
208 209
}

houweibin committed
210 211 212 213 214
-(IBAction)onClickComplete:(UIButton *)sender{
    BOOL buyNow = sender.tag == 1;
    if(!self.variant){
        [self showToast:@"请选择商品"];
        return;
215
    }
houweibin committed
216 217 218 219 220 221 222 223 224 225
    [self showLoading];
    __weak KWMNewProductVC *this = self;
    [self addShopWithVariantId:self.variant.identifier quantity:self.count variant:self.variant buyNow:buyNow callback:^(BOOL success) {
        [this hideLoading];
        if(success) {
            if(!buyNow){
                [this initShopCartCount];
                [this clearSelect];
            }
            //[this dismissViewControllerAnimated:YES completion:nil];
226 227 228 229
        }
    }];
}

houweibin committed
230 231
//添加商品
- (void)addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity variant:(BUYProductVariant *) variant buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback {
232 233 234 235 236 237 238 239 240 241
    __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
242
                model.price = variant.price;
243 244 245 246 247 248 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
                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) {
        //登录
        KWMLoginVC *loginVc = (KWMLoginVC *)[KWMBaseVC findControllerBy:[KWMLoginVC kwmTag] fromStoryboard:@"Login"];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
        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
276 277 278 279 280 281 282
#pragma mark -- KWMSecondDetailViewDelegate
-(void)kwm_clickCollectionCell:(BUYProduct *)product{
    if(!product){
        return;
    }
    self.product = product;
    self.productId = product.identifier;
houweibin committed
283 284
    self.colorMeterfield = nil;
    self.adminProduct = nil;
houweibin committed
285 286 287 288 289
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self initView];
    [self clearSelect];
}

houweibin committed
290 291 292 293 294 295 296 297
-(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
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
#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;
    [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
}

lee committed
313 314 315 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
- (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];
    }];
    [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
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 418

-(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];
}

419 420
#pragma mark - API BUYClient+Storefront
-(void)requestProductDetail{
u  
lee committed
421
    if(!(self.productId || self.product || self.handle)){
422 423 424 425
        return;
    }
    [self showLoading];
    __weak KWMNewProductVC *weakSelf = self;
u  
lee committed
426
    void(^completion)(BUYProduct*,NSError*) = ^(BUYProduct * _Nullable product, NSError * _Nullable error) {
427 428 429 430 431
        [weakSelf hideLoading];
        if(error){
            [weakSelf showError:error];
        }else if(product){
            weakSelf.product = product;
houweibin committed
432
            weakSelf.productId = product.identifier;
houweibin committed
433 434
            [weakSelf initMidViewHight];
            weakSelf.midDetailView.product = product;
435
            [weakSelf.detailView1 setData:product];
houweibin committed
436 437
            [self requestBrandProducts:1];
            [self requestCategoryProducts:1];
houweibin committed
438 439 440 441 442
            
            if(self.handle){
                [self requestAdminProduct];
                [self requestColorMetafield];
            }
443
        }
u  
lee committed
444 445 446 447 448 449
    };
    if (self.handle) {
        [self.client getProductByHandle:self.handle completion:completion];
    }else{
        [self.client getProductById:self.productId?:self.product.identifier completion:completion];
    }
450 451
}

452 453 454 455 456 457 458 459 460

-(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
461
            color.product = product;
462 463 464 465 466
            [weakSelf.colorArray addObject:color];
        }
    }];
}

467
-(void)requestBrandProducts:(NSInteger)page{
houweibin committed
468 469 470 471
    if(!self.product){
        return;
    }
    NSString *handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:self.product.vendor];
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    self.detailView2.isLoadingSameBrand = 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.isLoadingSameBrand = NO;
                [weakSelf.detailView2 setData:products isSameBrand:YES];
            }];
            
        }else{
            weakSelf.detailView2.isLoadingSameBrand = NO;
        }
    }];
}

-(void)requestCategoryProducts:(NSInteger)page{
houweibin committed
489 490 491 492
    if(!self.product){
        return;
    }
    NSString *handle = self.product.productType;
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    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
508 509 510
#pragma mark  -- API KWMApimanager
-(void)requestAdminProduct{
    NSNumber *productId = self.product?self.product.identifier:self.productId;
houweibin committed
511 512 513
    if(!productId){
        return;
    }
houweibin committed
514 515 516 517 518 519 520 521 522 523 524 525
    __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];
}

526 527

-(void)requestColorMetafield{
houweibin committed
528
    NSNumber *productId = self.product?self.product.identifier:self.productId;
houweibin committed
529 530 531
    if(!productId){
        return;
    }
532 533
    __weak KWMNewProductVC *weakSelf = self;
    void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){
houweibin committed
534
//        [weakSelf showError:error];
535 536 537 538 539 540 541 542 543 544 545 546 547 548
    };
    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
549
    [self.api getProductMetafield:nil productId:productId success:success failure:failure];
550 551 552
}


553 554 555 556
-(void)requestWishList{
    __weak KWMNewProductVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
houweibin committed
557
    BUYProductVariant *variant = self.variant;
558
    if(!(customer && customer.identifier && variant)){
559 560 561 562 563
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
houweibin committed
564
                               @"variant_id":variant.identifier.stringValue,
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
                               @"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];
}
584

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
-(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;
            }
611

612 613 614 615 616 617
        }
        
    };
    [self.api removeWish:parament success:success failure:failure];
    [self showLoading];
}
618

619 620 621 622 623 624 625
-(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;
    }
houweibin committed
626
    BUYProduct *product = (self.color && self.color.product)?self.color.product:self.product;
627 628 629 630
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"customer_name":customer.lastName,
houweibin committed
631 632
                               @"product_title":product.title,
                               @"product_id":product.identifier.stringValue,
633 634 635
                               @"variant_id":self.variant.identifier.stringValue,
                               @"variant_sku":self.variant.sku,
                               @"variant_title":self.variant.title,
houweibin committed
636
                               @"product_handle":product.handle,
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                               @"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];
}
656 657


houweibin committed
658

lee committed
659 660 661 662 663 664 665 666 667 668 669 670 671
- (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
672 673 674



675

676
@end