//
//  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"
#import "KWMWishListVC.h"
#import "PhotoBroswerVC.h"
#import "KWMUserModel.h"
#import "KWMShoppingCart.h"
#import "KWMImageUtil.h"
#import "KWMStringUtil.h"

@interface KWMNewProductVC ()

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

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

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

@property (weak, nonatomic) IBOutlet UIImageView *ivShare;

//颜色扩展字段
@property (nonatomic) KWMMetafield *colorMeterfield;

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

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

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

@property (nonatomic) BOOL isLikeVariant;

@end

@implementation KWMNewProductVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [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{
    [self.btnLike setImage:[UIImage imageNamed:@"ic_like_unable"] forState:UIControlStateNormal];
    self.productId = @(7436196294);
    self.detailView1.delegate = self;
    self.colorArray = [NSMutableArray array];
    [self requestProductDetail];
    [self requestBrandProducts:1];
    [self requestCategoryProducts:1];
    [self requestColorMetafield];
}

//请求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];
            [self requestProductByColor:color];
        }
    }
    
}


-(IBAction)onClickClose:(id)sender{
    [self.navigationController popViewControllerAnimated: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{
    if(self.isLikeVariant){
        [self requestRemoveWish];
    }else{
        [self requestAddWish];
    }
}

#pragma mark -- KWMFirstDetailViewDelegate
-(void)kwm_onClickSizeBtn{
    KWMVariantsVC *variantsVC = (KWMVariantsVC *)[KWMVariantsVC findControllerBy:[KWMVariantsVC kwmTag] fromStoryboard:@"NewProduct"];
    variantsVC.product = self.product;
    variantsVC.colorArray = self.colorArray;
    variantsVC.delegate = self;
    CGSize size = [UIScreen mainScreen].bounds.size;
    [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
}

-(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{
    [self.btnLike setImage:[UIImage imageNamed:@"ic_like"] forState:UIControlStateNormal];
    self.detailView1.variant = variant;
    self.variant = variant;
    self.color = color;
    self.isLikeVariant = NO;
    [self requestWishList];
}

- (void)kwm_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 getProductImageUrl:this.product.identifier ImageSize:NormalImage];
                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.floatValue;
                                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) {
        //登录
        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 - API BUYClient+Storefront
-(void)requestProductDetail{
    if(!self.productId && !self.product){
        return;
    }
    [self showLoading];
    __weak KWMNewProductVC *weakSelf = self;
    [self.client getProductById:self.productId?:self.product.identifier completion:^(BUYProduct * _Nullable product, NSError * _Nullable error) {
        [weakSelf hideLoading];
        if(error){
            [weakSelf showError:error];
        }else if(product){
            weakSelf.product = product;
            [weakSelf.detailView1 setData:product];
        }
    }];
}


-(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.prodcut = product;
            [weakSelf.colorArray addObject:color];
        }
    }];
}

-(void)requestBrandProducts:(NSInteger)page{
//    if(!self.product){
//        return;
//    }
    NSString *handle = @"girls";
    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{
    //    if(!self.product){
    //        return;
    //    }
    NSString *handle = @"girls";
    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  apimanager
-(void)requestColorMetafield{
    __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:@(7436196294) 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.detailView1.variant;
    if(!customer || !variant){
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"varaint_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;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"customer_name":customer.lastName,
                               @"product_title":self.product.title,
                               @"product_id":self.product.identifier.stringValue,
                               @"variant_id":self.variant.identifier.stringValue,
                               @"variant_sku":self.variant.sku,
                               @"variant_title":self.variant.title,
                               @"product_handle":self.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];
}







@end