// // 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 "KWMContactUsVC.h" #import "KWMBrandCaramelVC.h" #import "KWMShareVC.h" #import "KWMWishListVC.h" #import "PhotoBroswerVC.h" #import "KWMUserModel.h" #import "KWMShoppingCart.h" #import "KWMImageUtil.h" #import "KWMStringUtil.h" #import "KWMShopCartVC.h" #import <TOWebViewController/TOWebViewController.h> #import <PPNetworkHelper/PPNetworkHelper.h> #import <TOWebViewController/NJKWebViewProgress.h> @interface KWMNewProductVC ()<KWMMidDetailViewDelegate> @property (weak, nonatomic) IBOutlet KWMFirstDetailView *detailView1; @property (weak, nonatomic) IBOutlet KWMSecondDetailView *detailView2; @property (weak, nonatomic) IBOutlet KWMMidDetailView *midDetailView; @property (weak, nonatomic) IBOutlet UIButton *btnShopCart; @property (weak, nonatomic) IBOutlet UIButton *btnContactUs; @property (weak, nonatomic) IBOutlet UIView *vBottomBar; @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) IBOutlet UIButton *btnLike; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightMidView; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *detailView2HeightConstraint; // 0 非自动 1 是加购 2 是立即购买 @property (assign, nonatomic) NSInteger autoAddToBag; //颜色扩展字段 @property (nonatomic) KWMMetafield *colorMeterfield; //颜色列表,由颜色扩展字段请求api拿到对应product后封装而来 @property (nonatomic) NSMutableArray<KWMColor *> *colorArray; //选中的variant @property (nonatomic) BUYProductVariant *variant; //选中的颜色 @property (nonatomic) KWMColor *color; //选中的数量 @property (nonatomic) NSInteger count; @property (nonatomic) NSString *typeTag; @property (nonatomic) BOOL isLikeVariant; @property (nonatomic) KWMProduct *adminProduct; @end @implementation KWMNewProductVC + (NSString *)kwmBoard { return @"NewProduct"; } - (void)viewDidLoad { [super viewDidLoad]; // self.productId = @(7436196294); // self.product = nil; [self initView]; } - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [self initShopCartCount]; [self.navigationController setNavigationBarHidden:YES]; } - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [self.navigationController setNavigationBarHidden:NO]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(void)initView{ self.colorArray = [NSMutableArray array]; self.detailView1.delegate = self; self.detailView2.delegate = self; self.midDetailView.delegate = self; [self initBottomViewHidden]; if(self.product){ [self.detailView1 setSizeGuideHidden:!self.typeTag]; self.midDetailView.product = self.product; [self.detailView1 setData:self.product]; [self requestBrandProducts:1]; [self requestCategoryProducts:1]; }else{ [self requestProductDetail]; } [self requestColorMetafield]; [self requestAdminProduct]; // [self initShopCartCount]; // [self initMidViewHight]; [self.btnLike setImage:[UIImage imageNamed:@"ic_like_unable"] forState:UIControlStateNormal]; } -(void)initBottomViewHidden{ if(self.product){ NSString *productVendor = self.product.vendor ?:@""; productVendor = [productVendor lowercaseString]; NSString *targetVendor = @"moncler"; BOOL isShowContactUs = [productVendor isEqualToString:targetVendor]; self.vBottomBar.hidden = isShowContactUs; self.btnContactUs.hidden = !isShowContactUs; } } - (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); // } // } //} //请求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]; if(self.product && [color.handle isEqualToString:self.product.handle]){ color.product = self.product; [self.colorArray addObject:color]; }else{ [self requestProductByColor:color]; } } } } -(void)clearSelect{ self.color = nil; self.variant = nil; self.count = 0; [self.btnLike setImage:[UIImage imageNamed:@"ic_like_unable"] forState:UIControlStateNormal]; if(self.detailView1){ [self.detailView1 setSelect:nil color:nil count:0]; } } -(IBAction)onClickClose:(id)sender{ [self.navigationController popViewControllerAnimated:YES]; } -(IBAction)onClickShopCart:(id)sender{ KWMShopCartVC *shopCartVC = (KWMShopCartVC *)[KWMBaseVC findControllerBy:[KWMShopCartVC kwmTag] fromStoryboard:@"ShopCart"]; [self.navigationController pushViewController:shopCartVC animated:YES]; } -(IBAction)onClickContactUs:(id)sender{ KWMContactUsVC *contactVC = (KWMContactUsVC *)[KWMBaseVC findControllerBy:[KWMContactUsVC kwmTag] fromStoryboard:@"Mine"]; [self.navigationController pushViewController:contactVC animated:YES]; } -(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{ 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; } if(!self.variant){ [self showToast:@"请先选择尺码/顏色"]; return; } if(self.isLikeVariant){ [self requestRemoveWish]; }else{ [self requestAddWish]; } } -(IBAction)onClickComplete:(UIButton *)sender{ BOOL buyNow = sender.tag == 1 || self.autoAddToBag == 2; if(!self.variant){ // [self showToast:@"请选择商品"]; self.autoAddToBag = buyNow ? 2 : 1; [self kwm_onClickSizeBtn]; return; } if(buyNow) { [self addShopWithVariantId:self.variant.identifier quantity:self.count variant:self.variant buyNow:YES callback:^(BOOL _){}]; return; } __weak KWMNewProductVC *this = self; // 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) { [this hideLoading]; if(success) { if(!buyNow){ [this initShopCartCount]; [this clearSelect]; } //[this dismissViewControllerAnimated:YES completion:nil]; } }]; } //添加商品 - (void)addShopWithVariantId:(NSNumber *)identifier quantity:(NSInteger)quantity variant:(BUYProductVariant *) variant buyNow:(BOOL)buyNow callback:(void (^)(BOOL))callback { __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; model.price = variant.price; 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) { //登录 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]; }); 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]; }]; } #pragma mark -- KWMSecondDetailViewDelegate -(void)kwm_updatedSecondDetailViewHeight:(CGFloat)height { self.detailView2HeightConstraint.constant = height; } -(void)kwm_clickCollectionCell:(BUYProduct *)product{ if(!product){ return; } self.product = product; self.productId = product.identifier; self.colorMeterfield = nil; self.adminProduct = nil; [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES]; [self initView]; [self clearSelect]; } -(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]]; } #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; MZFormSheetPresentationViewController * mz = [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleSlideFromBottom]; mz.didDismissContentViewControllerHandler = ^(UIViewController * _Nonnull contentViewController) { self.autoAddToBag = 0; }; } - (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]; }]; url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet whitespaceCharacterSet].invertedSet]; [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]; }); } -(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]; if (self.autoAddToBag) { [self onClickComplete:nil]; self.autoAddToBag = 0; } } #pragma mark - KWMMidViewDetailDelegate -(void) kwm_updatedHeight:(CGFloat)height { self.heightMidView.constant = height; } #pragma mark - API BUYClient+Storefront -(void)requestProductDetail{ if(!(self.productId || self.product || self.handle)){ return; } [self showLoading]; __weak KWMNewProductVC *weakSelf = self; void(^completion)(BUYProduct*,NSError*) = ^(BUYProduct * _Nullable product, NSError * _Nullable error) { [weakSelf hideLoading]; if(error){ [weakSelf showError:error]; }else if(product){ weakSelf.product = product; weakSelf.productId = product.identifier; [weakSelf initBottomViewHidden]; // [weakSelf initMidViewHight]; weakSelf.midDetailView.product = product; [weakSelf.detailView1 setData:product]; [weakSelf requestBrandProducts:1]; [weakSelf requestCategoryProducts:1]; //handle初始化的商品页面还没有请求admin api(获取库存),以及颜色 api; if(weakSelf.handle){ [weakSelf requestAdminProduct]; [weakSelf requestColorMetafield]; } } }; if (self.handle) { [self.client getProductByHandle:self.handle completion:completion]; }else{ [self.client getProductById:self.productId?:self.product.identifier completion:completion]; } } -(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){ color.product = product; [weakSelf.colorArray addObject:color]; } }]; } -(void)requestBrandProducts:(NSInteger)page{ if(!self.product){ return; } NSString *handle = [KWMStringUtil deleteOtherCharExceptLetterWithLine:self.product.vendor]; self.detailView2.isLoadingSameBrand = YES; __weak KWMNewProductVC *weakSelf = self; [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; }]; [self.client getCollectionByHandle:handle completion:^(BUYCollection * _Nullable collection, NSError * _Nullable error) { if(collection && !error){ weakSelf.detailView2.brandDescription = collection.stringDescription; [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.brand = weakSelf.product.vendor; [weakSelf.detailView2 setData:products isSameBrand:YES]; }]; }else{ weakSelf.detailView2.isLoadingSameBrand = NO; } }]; } -(void)requestCategoryProducts:(NSInteger)page{ if(!self.product){ return; } NSString *handle = self.product.productType; 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; } }]; } #pragma mark -- API KWMApimanager -(void)requestAdminProduct{ NSNumber *productId = self.product?self.product.identifier:self.productId; if(!productId){ return; } __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]; } -(void)requestColorMetafield{ NSNumber *productId = self.product?self.product.identifier:self.productId; if(!productId){ return; } __weak KWMNewProductVC *weakSelf = self; void(^failure)(NSURLSessionDataTask *,NSError *) = ^(NSURLSessionDataTask *task,NSError *error){ // [weakSelf showError:error]; }; 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; } } }; [self.api getProductMetafield:nil productId:productId success:success failure:failure]; } -(void)requestWishList{ __weak KWMNewProductVC *weakSelf = self; NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"]; BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict]; BUYProductVariant *variant = self.variant; if(!(customer && customer.identifier && 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.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]; } -(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; } } }; [self.api removeWish:parament success:success failure:failure]; [self showLoading]; } -(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; } NSNumber *customerId = customer.identifier?:@(0); NSString *customerName = customer.lastName?:@""; BUYProduct *product = (self.color && self.color.product)?self.color.product:self.product; NSDictionary *parament = @{ @"customer_id":customerId.stringValue, @"customer_email":customer.email, @"customer_name":customerName, @"product_title":product.title, @"product_id":product.identifier.stringValue, @"variant_id":self.variant.identifier.stringValue, @"variant_sku":self.variant.sku, @"variant_title":self.variant.title, @"product_handle":product.handle, @"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]; } - (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]; } @end