//
//  KWMWishListVC.m
//  iCemarose
//
//  Created by HouWeiBin on 2017/7/7.
//  Copyright © 2017年 kollway. All rights reserved.
//

#import "KWMWishListVC.h"
#import "KWMShoppingCart.h"
#import "KWMImageUtil.h"
#import "KWMStringUtil.h"
#import "KWMShopCartModel.h"

@interface KWMWishListVC ()

@property (weak,nonatomic) IBOutlet UILabel *lbTotalPrice;

@property (weak,nonatomic) IBOutlet UITableView *tbvWish;

@property(nonatomic) NSMutableArray *wishArray;

@property(nonatomic) NSMutableArray *productArray;

@end

@implementation KWMWishListVC

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

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self requestWishList];
}

- (void)initView{
    self.title = @"我喜欢的";
    [self.tbvWish registerNib:[UINib nibWithNibName:NSStringFromClass([KWMWishCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([KWMWishCell class])];
    
    self.wishArray = [NSMutableArray array];
    self.productArray = [NSMutableArray array];
    [self setTotalPrice];
}

-(void)removeWish:(NSNumber *)variantId{
    for(KWMWish *wish in self.wishArray){
        if([wish.variantId isEqualToNumber:variantId]){
            [self.wishArray removeObject:wish];
        }
    }
}

//计算总价格
- (void) setTotalPrice{
    NSArray *shopCartList = (NSMutableArray *)[[KWMShoppingCart sharedInstance] items];
    NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithDecimal:@(0).decimalValue];
    for (KWMShopCartModel *model in shopCartList) {
        if (model.line_price) {
            total = [total decimalNumberByAdding:model.line_price.priceValue];
        }else{
            total = [total decimalNumberByAdding:[model.price.priceValue decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@(model.quantity).stringValue]]];
        }
    }
    self.lbTotalPrice.text = total.priceFormatted;
}

#pragma mark --KWMVariantsVCDelegate
-(void)kwm_setVariant:(KWMVariantsVC *)variantsVC variant:(BUYProductVariant *)variant{
    for(KWMWish *wish in self.wishArray){
        if([wish.variantId isEqualToNumber:variantsVC.wish.variantId]){
            wish.variantId = variant.identifier;
            wish.variantSku = variant.sku;
            wish.variantTitle = variant.title;
            [self.tbvWish reloadData];
        }
    }
}

#pragma mark --KWMWishCellDelegate
-(void)kwm_onClickEdit:(KWMWishCell *)wishCell{
    //此edit并没有请求API,而只是暂时的在本页面修改wish,参考网页端cemarose。
    KWMVariantsVC *variantsVC = (KWMVariantsVC *)[KWMVariantsVC findControllerBy:[KWMVariantsVC kwmTag] fromStoryboard:@"NewProduct"];
    variantsVC.wish = wishCell.wish;
    variantsVC.product = wishCell.product;
    
    variantsVC.delegate = self;
    CGSize size = [UIScreen mainScreen].bounds.size;
    [self showPresentation:variantsVC size:size tapOutsideClose:YES style:MZFormSheetPresentationTransitionStyleFade];
}

-(void)kwm_onClickRemove:(KWMWishCell *)wishCell{
    [self requestRemoveWish:wishCell.wish.variantId];
}

-(void)kwm_onClickAddToShopCart:(KWMWishCell *)wishCell{
    if(!self.productArray){
        [self requestProductsApi];
        return;
    }
    NSNumber *variantId = wishCell.wish.variantId;
    BUYProduct *product = wishCell.product;
    BUYProductVariant *variant = wishCell.variant;
    if(!product || !variant){
        return;
    }
    __weak KWMWishListVC *this = self;
    [[KWMShoppingCart sharedInstance] increaseProductWithVariantId:variantId quantity:1 callback:^(NSError *error, KWMCartResult *cart) {
        if (cart.items.firstObject && !cart.items.firstObject.product_id) {
            KWMShopCartModel *model = cart.items.firstObject;
            BUYImageLink *il = product.images.firstObject;
            model.imageStr = [KWMImageUtil getProductImageUrlByOriginalUrl:il.sourceURL.absoluteString ImageSize:NormalImage];
            model.name = product.title;
            model.brand = product.vendor;
            model.size = variant.title;
            model.price = variant.price;
            model.product_id = product.identifier;
        }
        if (!error) {
//            [this showToast:@"添加成功"];
            [this setTotalPrice];
            //[this.btnShopCart setTitle:cart.item_count.stringValue forState:UIControlStateNormal];
            //callback(YES);
        }else{
            [this showError:error];
            //callback(NO);
        }
    }];
}

#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.wishArray ? self.wishArray.count:0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWMWishCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([KWMWishCell class]) forIndexPath:indexPath];
    
    KWMWish *wish = [self.wishArray objectAtIndex:indexPath.row];
    BUYProduct *product;
    BUYProductVariant *variant;
    if(self.productArray){
        for(BUYProduct *mProduct in self.productArray){
            if([mProduct.identifier isEqualToNumber:wish.productId]){
                product = mProduct;
            }
        }
    }
    if(product){
        for(BUYProductVariant *mVariant in product.variantsArray){
            if([mVariant.identifier isEqualToNumber:wish.variantId]){
                variant = mVariant;
                break;
            }
        }
    }

    cell.wish = wish;
    cell.variant = variant;
    cell.product = product;
    cell.delegate = self;
    return cell;
}

#pragma mark-- KWMAPIManager
-(void)requestWishList{
    __weak KWMWishListVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
    if(!customer){
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"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){
            NSMutableArray *wishArray = (NSMutableArray *)result.data;
            weakSelf.wishArray = wishArray;
            [weakSelf.tbvWish reloadData];
            [weakSelf requestProductsApi];
        }
    };
    [self.api getWishList:parament success:success failure:failure];
    [self showLoading];
}

-(void)requestRemoveWish:(NSNumber *)variantId{
    __weak KWMWishListVC *weakSelf = self;
    NSDictionary *customerDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"customer"];
    BUYCustomer *customer = [[BUYCustomer alloc] initWithModelManager:self.client.modelManager JSONDictionary:customerDict];
    if(!customer || !variantId){
        return;
    }
    NSDictionary *parament = @{
                               @"customer_id":customer.identifier.stringValue,
                               @"customer_email":customer.email,
                               @"variant_id":variantId.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"]){
                [weakSelf removeWish:variantId];
            }
        }
    };
    [self.api removeWish:parament success:success failure:failure];
    [self showLoading];
}

#pragma mark-- BuyClient+storefront.h
-(void)requestProductsApi{
    NSMutableArray *productIds = [NSMutableArray array];
    for(KWMWish *wish in self.wishArray){
        [productIds addObject:wish.productId];
    }
    if(productIds.count == 0){
        return;
    }
    __weak KWMWishListVC *weakSelf = self;
    NSArray *productIdsArray = [KWMStringUtil splitArray:productIds withSubSize:50];
    for(NSArray *mProductIds in productIdsArray){
        //经过测试,该api一次最多返回50个product,所以如果有100个商品,需要分成两次请求
        [self.client getProductsByIds:mProductIds completion:^(NSArray<BUYProduct *> * _Nullable products, NSError * _Nullable error) {
            [weakSelf hideLoading];
            if (!error && products && products.count>0) {
                [weakSelf.productArray addObjectsFromArray:products];
                [weakSelf.tbvWish reloadData];
                weakSelf.tbvWish.hidden = NO;
            }else if (error){
                [weakSelf showError:error];
            }
        }];
    }
    [self showLoading];
    
}


@end